# Definitions for use of splitindex package: Arrange to use the splitindex
# program instead of makeindex when needed, otherwise to do standard run of
# makeindex.

# John Collins and Ernst Reissner, 2024-09-27.


# Specify extra files that need to be cleaned up when splitindex is in use:
$clean_ext .= " %R-*.ind %R-*.idx %R-*.ilg %R-*.ind";

# Use an internal subroutine to do the processing.  **Important**: Pass the
# name of the source file, etc as arguments obtained by place-holder
# substitution instead of having the subroutine use variables like
# $$Psource.  This is because by default latexmk temporarily changes
# directory to the aux directory before the invoking the command (or
# whatever) specified by $makeindex.  The change of directory is to avoid
# some deficiencies in the standard makeindex program.  See the latexmk
# documentation for further information. After the change of directory, the
# value of $$Psource will typically be wrong. Instead we use placeholders
# for the relevant quantities, since after doing the change of directory,
# latexmk's internal processing adjusts the substitutions for %S, %D etc
# appropriately.  Also, include the string for aux_dir in the arguments, as
# needed for the treatment of dependencies.

$makeindex = 'internal splitindex3 %S %D %Y %R %B %O';

#-------------

sub HaveMultiIdx {
  # Subroutine to test whether (.idx) file has entries of the form given by
  # splitindex package with multiple indexes.
  use strict;
  my $fileName = $_[0];

  # Use a precompiled RE:
  my $patternMultiIndex = qr/^\\indexentry\[[^\]]*\]\{/;

  my $info;
  if (! open $info, '<', $fileName ) {
      die "In splitindex processing, the file '$fileName' was supposed to\n",
          "exist, but I could not read it:\n$!";
      return 0;
  }
  while (my $line = <$info>) {
    if ( $line =~ $patternMultiIndex ) {
      #  We have a multi-index 
      close $info;
      return 1;
    }
  }
  close $info;
  # There was no multi-index:
  return 0;
}

#-------------

sub splitindex3 {
   use strict;
   my ($source, $dest, $auxdir, $root, $base, @opts) = @_;

   if (! HaveMultiIdx($source)) {
      print "Running standard makeindex program:\n";
      return system( "makeindex", @opts, '-o', $dest, $source );
   }
   # Else:
   print "Running splitindex program:\n";
   
   # Ensure dummy file for standard destination file exists, so that
   # latexmk is satisfied that its expectation for the main generated file
   # is satisfied.
   open( my $ind_fh, '>>', $dest );
   close $ind_fh;

   # Arrange to obtain dependency information from splitindex by invoking
   # it in a verbose mode, and redirecting its output to the standard .ilg
   # file, and later parsing it for the relevant lines.
   my $ilg = $dest;
   $ilg =~ s/\.[^\.]+$/\.ilg/;
   my $ret2 = system "splitindex -v -v \"$source\" >> \"$ilg\"";
   if ($ret2) { return $ret2;}

  
   my $ilg_fh;
   if (! open( $ilg_fh, '<', $ilg ) ) {
       warn "In sub splitindex, could not read '$ilg'\n";
       return 1;
   }
   while (<$ilg_fh>) {
       if ( /^New index file (.*)\s*$/ ) {
            # .idx file generated by splitindex
          my $idx = $1;
            # Ensure path to idx file is correct if we've done the change of
            # directory caused by the setting of $makeindex_fudge:
          if ($makeindex_fudge) { $idx = $auxdir.$idx; }
            # In addition to the .idx files that the splitindex program
            # reports that it generates, there are corresponding .ind files
            # generated by the instances of makeindex that are invoked by
            # splitindex.  These are important to latexmk's knowledge of
            # the network of dependencies because they are read in by the
            # next run of *latex.
          my $ind = $idx;
          $ind =~ s/\.idx$/\.ind/;
          print  "splitindex generated files '$idx' '$ind'\n";
          rdb_add_generated( $ind, $idx );
       }
   }
   close $ilg_fh;
   return $ret2;
}

#-------------
