#!/usr/bin/perl

use strict;

sub setBCL {
    my $period = shift;
    my $infile = shift;
    my $outfile = shift;

    open(INPUT,"<$infile") or die "Unable to open infile: $!\n";
    open(OUTPUT,">$outfile") or die "Unable to open outfile: $!\n";

    while (<INPUT>) {
        s/name=\"stimPeriod\" initial_value=\"1000\"/name=\"stimPeriod\" initial_value=\"$period\"/;
        print OUTPUT $_;
    }

    close INPUT;
    close OUTPUT;
}

my $base = "/usr/people/nickerso/data/papers/ProgBiophysMolecBiol-NobleReview/models/2004_tenTusscher/experiments";

my $cellml = "$base/periodic-stimulus-";

my $text2sig = "/product/cmiss/cmgui/utilities/i686-linux/unemap/text2sig";
my $mozCellML = "/usr/people/nickerso/physiome/cellml/mozCellML/mozCellML-standalone/bin/MozCellML";

my $tmpData = "/tmp/HVM-tmp.data";
my $tmpXML = "/tmp/HVM-tmp.xml";
my $cnfg = "$base/data.cnfg";

my $outputRoot = "/tmp/signals";

#my @BCLs = (250,300,350,400,450,500,750,1000,2000,3000,4000,5000);
my @BCLs = (5000);

#my @cellTypes = ("epicardial","endocardial","M");
my @cellTypes = ("endocardial","M");

foreach my $BCL (@BCLs) {
    print "BCL: $BCL\n";
    foreach my $type (@cellTypes) {
        print "Cell type: $type\n";
        my $infile = $cellml.$type.".xml";
        &setBCL($BCL,$infile,$tmpXML);
        my $tEnd = 150 * $BCL;
        my $command = "$mozCellML url file://$tmpXML start 0 end $tEnd grid 0.5 maxstep 0.5 relerr 1e-6 abserr 1e-6 output $tmpData";
        my $blah = `$command`;
        print "------------------------------\n";
        print "$blah\n";
        print "------------------------------\n";
        unlink $tmpXML;
        my $signalFile = sprintf "$outputRoot/$type-%04d.signal",$BCL;
        $command = "$text2sig $tmpData $cnfg $signalFile";
        $blah = `$command`;
        print "------------------------------\n";
        print "$blah\n";
        print "------------------------------\n";
        unlink $tmpData;
    }
}
