#!/usr/bin/perl -w

$input=$ARGV[0];

if (!$input) {
  warn "usage: render-gdamps gdam.sgml";
}

$workdir = "/tmp/rendergdampsworkspace";
$imagedir = "$workdir/images";
$ladspadir = "$workdir/ladspaimages";
$always_remake_img = 1;
$debug = 1;

mkdir $workdir, 0755;
mkdir $imagedir, 0755;
mkdir $ladspadir, 0755;

$dir = `pwd`;
chomp $dir;

$curdir = `pwd`;
chomp $curdir;

open SGML, "$input" or die "Couldnt find sgml file $input from $curdir";

while(<SGML>){
	if (/\@image_path\@/){
		if (m,\@/([^"]+),){
			print "match $1\n";
			push @image_list, $1;
		}
	}
	if (/\@ladspa_image_path\@/){
		if (m,\@/([^"]+),){
			push @ladspa_image_list, $1;
		}
	}
}


sub run {
	my $cmd = $_[0];
	print "running $cmd\n" if $debug;
	if ((system $cmd) != 0){
		die "error running $cmd";
	}
}

# (regex, convert-option) pairs,
# these regexes are matched from top-to-bottom, and
# the first match wins.
@image_match_options = 
 ( '@ladspa_image@/ladspa.jpg',
          "-density 144x144",

   '@ladspa_image@/mininet.jpg',
          "-density 144x144",

   '@image@/((play)|(stop)|(nudge)).*',
          "",

   '@image@.*',
          "-density 144x144",

   '@ladspa_image@.*',
          ""
 );

sub get_image_options($) {
  my $image_name = $_[0];
  my $regex;
  for (@image_match_options) {
    if (!defined $regex) {
      $regex = $_;
      next;
    }
    $opts = $_;
    return $_ if ($image_name =~ m,$regex,);
  }
  return "";
}

chdir "$imagedir";

if (!-d "jpegs") {
    mkdir "jpegs", 0755;
}
for (@image_list){
    $image = $_;
    $epsfile = $_;
    $epsfile =~ s/\.jpe?g$/.eps/;
    $image_opt = get_image_options("\@image\@/$image");
    if (!-e "jpegs/$image") {
	$wgetcommand = "cd jpegs ; wget -N -q http://www.ffem.org/gdam/images/$_";
	run $wgetcommand;
    }
    $convertcommand = "convert $image_opt jpegs/$image $epsfile";
    if (!-e $epsfile || $always_remake_img || -M $image > -M $epsfile) {
	run $convertcommand;
    }
}

chdir "$ladspadir";

for (@ladspa_image_list){
    $epsfile = $_;
    $epsfile =~ s/\.jpe?g$/.eps/;
    $wgetcommand = "wget -N -q http://www.ffem.org/gdam/ladspa/$_";
    $convertcommand = "convert $_ $epsfile";
    run $wgetcommand;
    if (!-e $epsfile || $always_remake_img || -M $image > -M $epsfile) {
	run $convertcommand;
    }
}

PAST_IMAGES:

chdir "$dir";

$curdir = `pwd`;

open SGML, "$input" or die "Couldnt find sgml file $input from $curdir";
open DVI, ">gdam.tmp.ps.sgml" or die "Couldn't open temp file in $curdir";

while(<SGML>){
	$aline = $_;
	$aline =~ s/\@image_path\@(.*)\.jpe?g/$imagedir$1.eps/;
	$aline =~ s/\@ladspa_image_path\@(.*)\.jpe?g/$ladspadir$1.eps/;
	$aline =~ s/format="jpg"/format="eps"/;
	print DVI $aline;
}
close(DVI);

run "sgmltools -b ps gdam.tmp.ps.sgml";
run "cp gdam.tmp.ps.ps gdam.ps";
__END__
