#!/usr/bin/perl -w
use strict;
use File::Spec;

load_global_templates();

(my $volume, my $directories, my $file) = File::Spec->splitpath($ARGV[0]);

if ($directories eq '') { $directories = '.'; }
opendir (DIR, File::Spec->catpath($volume, $directories, ''));
my @files = grep(/^$file.*\.in\.html$/,readdir(DIR));
closedir (DIR);

foreach $file (@files) {
    $file =~ m/^(.*tracematch\$(\d)+)\.in\.html$/;
    my $choppedFile = $1;
    my $tmNum = $2;

    $main::tmPfgHTML = $main::tmPfgHTML_master;
    $main::tmPfgHTML =~ s /<<name>>/$choppedFile/;
    $main::tmPfgHTML =~ s /<<m>>/$tmNum/;

    processTracematch($choppedFile);
}
exit;

sub processTracematch {
    my ($name) = @_;
    my $escapedName = $name;
    $escapedName =~ s /\$/\\\$/g;
    my $cl = join " ", ('/usr/bin/dot', "$escapedName.dot", '-Tcmapx', '-o', "$escapedName.in.cmap", '-Tpng', '-o', "$escapedName.png");
    `$cl`;

    # substitute href="#foo" with class="supernote-click-foo" href="#foo" in the cmap. -->
    open (IN, "$name.in.cmap") || die;
    my @cmap = ();
    while ($_ = <IN>) {
	if (/map id="(\w+)" name="(\w+)"/) {
	    my $h = "$1-<<\$1>>";
	    s /map id="(\w+)" name="(\w+)"/map id="$h" name="$h"/;
	}
	if (/href="#(\w+)"/) {
	    my $h = camelCase($1);
	    s /href=\"#\w+\"/class=\"supernote<<\$1>>-click-$h\" href=\"#$h-<<\$1>>\"/;
	}
	push (@cmap, $_);
    }
    close (INC);
    
    # remaining steps:
    
    # read in the in.html file and put the failure groups into an array

    open (IN, "$name.in.html");
    my @failureGroups = ();
    my $line = "";
    my @currentFailureGroup = ();
    while ($line = <IN>) {
	if ($line =~ m /name='([\w\d_-]+)'/) {
	    my $n = $1; my $nn = camelCase($n);
	    $line =~ s /$n/$nn/;
	}
	
	if ($line =~ m /<div id='([\w\d_-]+)'/) {
	    my $n = $1; my $nn = camelCase($n);
	    $line =~ s /$n/$nn/;
	}
	
	push (@currentFailureGroup, $line);
	if ($line =~ m!<h1>Potential point of failure (\d+)</h1>!) {
	    my $groupNum = $1;

	    my $tmPfgCopy = $main::tmPfgHTML;
	    $tmPfgCopy =~ s /<<n>>/$groupNum/g;
	    push (@failureGroups, (@currentFailureGroup, $tmPfgCopy));
	    @currentFailureGroup = (merge_cmap($groupNum, @cmap));
	}
    }
    push (@failureGroups, @currentFailureGroup);
    close (IN);
    
    # Merge template (tm-template) and add one copy of the cmap per template, as defined by the .in.html file.
    open (OUT, ">$name.html");
    my $tmHTML = $main::tmTemplateHTML_master;
    $tmHTML =~ s /<<\$name>>/$name/mg;
    $tmHTML =~ s /<<\$MAPS>>/@failureGroups/mg;
    print OUT $tmHTML;
    close (OUT);
}
    
sub merge_cmap {
    my ($groupNum, @cmap) = @_;
    my @rv = ();
    for (@cmap) {
	s/<<\$1>>/$groupNum/g;
	push (@rv, $_);
    }
    return @rv;
}

# lifted from W3C code (ical2rdf.pl)
sub camelCase{
  my($n, $initialCap) = @_;

  my(@words) = split(/_/, $n);

  if($initialCap){
    return join('', map(ucfirst, @words));
  }else{
    return $words[0] . join('', map(ucfirst, @words[1..$#words]));
  }
}

sub load_global_templates {
$main::tmPfgHTML_master = '<p><img src="<<name>>.png" usemap="#tracematch_<<m>>-<<n>>" alt="tracematch_<<m>>-<<n>>" /></p>';
$main::tmTemplateHTML_master = <<EOS;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title>Potential Points of Failure for <<\$name>></title>
 <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
 <!-- SuperNote v1.0beta by Angus Turnbull htpp://www.twinhelix.com -->
 <script type="text/javascript" src="supernote.js"></script>
 <link rel="stylesheet" type="text/css" href="supernote.css" />
</head>

<body>

<script type="text/javascript">
addEvent(document, 'click', function(evt)
{
 var elm = evt.target || evt.srcElement, closeBtn, note;

 while (elm)
 {
  if ((/note-close/).test(elm.className)) closeBtn = elm;
  if ((/snb-pinned/).test(elm.className)) { note = elm; break }
  elm = elm.parentNode;
 }

 if (closeBtn && note)
 {
  var noteData = note.id.match(/([a-z_\\-0-9]+)-note-([a-z_\\-0-9]+)/i);
  for (var i = 0; i < SuperNote.instances.length; i++)
   if (SuperNote.instances[i].myName == noteData[1])
   {
    setTimeout('SuperNote.instances[' + i + '].setVis("' + noteData[2] +
     '", false, true)', 100);
        cancelEvent(evt);
   }
 }
});
</script>

<<\$MAPS>>

<p>SuperNote thanks to <a href="http://www.twinhelix.com/">TwinHelix Designs</a>.</p>
</body>
</html>
EOS
}
