#!/usr/bin/perl -w

use strict;
use FileHandle;

if (scalar @ARGV < 3) {
        die "usage: $0 <model template> <analysis template> <generated directory> <values>\n";
}

my $template = shift;
my $analysisTemplate = shift;
my $dir = shift;
my $valuesString = shift;
my @values = split /,/,$valuesString;

if (! -d $dir) {
        die "Unable to create generated directory $dir: $!\n" unless
                mkdir $dir;
}

open(TEMPLATE,"<$template") or die "Unable to open template file: $!\n";
open(GRAPHS,">$dir/graphs.xml") or die "Unable to open graphs file: $!\n";
print GRAPHS <<END_OF_HEADER;
<?xml version="1.0" encoding="iso-8859-1"?>
<rdf:RDF
  xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
  xmlns:cs="http://www.cellml.org/metadata/simulation/1.0#"
  xmlns:cg="http://www.cellml.org/metadata/graphs/1.0#">
  <rdf:Description>
    <cg:graph>
      <rdf:Description rdf:ID="ActionPotentials">
        <cg:traces rdf:parseType="Collection">
END_OF_HEADER

foreach my $value (@values) {
        print GRAPHS <<END_OF_TRACE;
          <rdf:Description>
            <cg:label>$value</cg:label>
            <cg:type rdf:resource="http://www.cellml.org/metadata/graphs/1.0#line"/>
            <cg:x-variable rdf:parseType="Resource">
              <cs:simulation rdf:resource="$value.xml#simulation"/>
              <cg:variable rdf:resource="../../../experiments/TNNP-S1S2.xml#time"/>
              <cg:minimum rdf:datatype="http://www.w3.org/2001/XMLSchema#double">9.99e3</cg:minimum>
              <!--<cg:maximum rdf:datatype="http://www.w3.org/2001/XMLSchema#double">59.65e3</cg:maximum>-->
            </cg:x-variable>
            <cg:y-variable rdf:parseType="Resource">
              <cs:simulation rdf:resource="$value.xml#simulation"/>
              <cg:variable rdf:resource="../../../../../cellml/models/2004_tenTusscher-version-2/2004_tenTusscher_noble_noble_panfilov-epi.xml#V"/>
            </cg:y-variable>
          </rdf:Description>
END_OF_TRACE
        open(CELLML,">$dir/$value.xml") or die "Unable to open CellML file: $!\n";
        while (<TEMPLATE>) {
                s/VALUE/$value/g;
                print CELLML $_;
        }
        seek TEMPLATE,0,0;
        close CELLML;
}

print GRAPHS <<END_OF_FOOTER;
        </cg:traces>
      </rdf:Description>
    </cg:graph>
  </rdf:Description>
</rdf:RDF>
END_OF_FOOTER

close GRAPHS;
close TEMPLATE;

open(ANALYSIS,">$dir/analysis.xml") or die "Unable to open analysis file: $!\n";
open(TEMPLATE,"<$analysisTemplate") or die "Unable to open analysis template: $!\n";
while (<TEMPLATE>) {
        my $g = "graphs.xml";
        s/GRAPHS/$g/g;
        print ANALYSIS $_;
}
close TEMPLATE;
close ANALYSIS;

# execute the analysis
my $analysis = "$dir/analysis.data";
my $command = "$ENV{HOME}/sf.net/CellMLSimulator/build/release/CellMLSimulator";
$command .= " --data $dir/data.h5 --graph-directory $dir --analysis-file $analysis";
$command .= " $dir/analysis.xml > $dir/CellMLSimulator.log";
system($command);

# create the APD data file for plotting
my $data = "$dir/apd.data";
open(SRC,"<$analysis") or die "Unable to open data source: $!\n";
open(DATA,">$data") or die "Unable to open data file: $!\n";
my $counter = 0;
print DATA "#   stimulusInterval  DI  APD  APD90  APD50\n";
while (<SRC>) {
        if (/^--> trace: (\d+)/) {
                $counter++;
                print DATA "$counter $1 ";
        }
        if (/^2\t/) {
                chomp $_;
                my @line = split /\t/;
                print DATA "$line[7] $line[4] $line[6] $line[5]\n";
        }
}
close SRC;
close DATA;

# and plot using gnuplot
open(GP,"|gnuplot") or die "Unable to connect to gnuplot: $!\n";
GP->autoflush(1);
print GP <<END_GNUPLOT;
set terminal postscript eps enhanced color solid
set output "$dir/APDR.eps"
set xlabel "DI (ms)"
set ylabel "APD_{90} (ms)"
plot "$data" using 3:5 with linespoints lw 2 title ""
END_GNUPLOT
close GP;
