# This shows how to use Asymptote (http://asymptote.sourceforge.net/,
# or http://www.ctan.org/pkg/asymptote/)
# with latexmk.  Asymptote is a vector graphics language with a
# processing program that generates graphics files that can be used in
# a LaTex file.
#
# The definitions in this file enable automatic compilation of .asy files
# containing asymptote code to be compiled to graphics files.  The .asy files
# may be created as stand-alone files or may be created during a *latex
# run by the use of the asymptote package with a document that contains
# sections of asymptote code.


# The following definitions arrange to run asy with the correct output
# file type.  They run asy in a verbose mode so that dependency
# information on imported files can be extracted.  To avoid adding a
# lot of extra printout on the screen of unimportant messages, the
# output is sent to a log file.  Since this includes error messages,
# which the user should see, latexmk types out error messages and the
# like. These definitions need latexmk 4.48 or later.

add_cus_dep("asy","eps",0,"asy2eps");
add_cus_dep("asy","pdf",0,"asy2pdf");
add_cus_dep("asy","tex",0,"asy2tex");

sub asy2eps { return asy2x( $_[0], 'eps' ); }
sub asy2pdf { return asy2x( $_[0], 'pdf' ); }
sub asy2tex { return asy2x( $_[0], 'tex' ); }

sub asy2x   {
  my ($base, $fmt ) = @_;
  my $log_file = "$base.log";
  my $cmd = "asy -vv -noV -f \"$fmt\" -o \"$base.$fmt\" \"$base\" > '$log_file' 2>&1";
  print "asy2x: Running '$cmd'\n";
  my $ret = system($cmd);
  my $FH = undef;
  if (! open(  $FH, "<", $log_file ) ) {
     warn "asy2x: Couldn't read log file '$log_file':\n $!";
     return $ret;
  }

  my %imports = ("$base.asy" => 1);
  while (<$FH>) {
      s/\s*$//;
      if (/^(Including|Loading) .* from (.*)$/) {
         my $import = $2;
         # Convert MSWin directory separator to /
         $import =~ s(\\)(/)g;
         $imports{$import} = 1;
      }
      elsif ( /^error/ || /^.*\.asy: \d/ ) {
          warn "==Message from asy: $_\n";
          $ret = 1;
      }
      elsif ( /^kpsewhich / || /^Processing / || /^Using /
              || /^Welcome / || /^Wrote /|| /^cd /|| /^gs /
            ) {
      }
      else {
#           warn "==Message from asy: $_\n";
      }
  }
  close $FH;
  show_hash( '', \%imports );
  rdb_set_source( $rule, keys %imports );
  return $ret;
}