#! /usr/bin/perl -w
# Xcute  [-V] [-Z] [-O[2]] [-T[134]] [-S] [-A] <[.ccf[c]]file> [<instart> <instop> <incount> <ststart> <ststop> <stcount>]
#
#  "runs" and plots a component's behavior using Xcutel for stateless,
#    XcuteS for state/concurrent 
#
#  Default is output behavior; -T for run time; -S for state.
 #  -O2, -T1, -T3, -T4 are detail graphs for concurrent; -T adds all runtimes.
#
#  Bare file, assume .ccf
#    If bare is "theory" assume .ccfc if state/concurrent.
#
#  For .ccf, plot actual component, and also subdomain plateaux,
#    because .ccf[ct] must also exist.
#

$plotOpt = "O"; #default is to plot output
$altOpt = 0;  #plot form: -A means a contour surface & towers; else floating rectangles & points
$Voption = 1; #always print messages
$hw = -1; #last "-" arg
for ($opt=0; defined($ARGV[$opt]); $opt++) {
  if ($ARGV[$opt] eq "-V") {
    $Voption = 1;
    $hw = $opt;
  } elsif ($ARGV[$opt] eq "-Z") {
    $Zoption = 1;
    $hw = $opt;
  } elsif ($ARGV[$opt] eq "-A") {
    $altOpt = 1;
    $hw = $opt;
# fix for pattern:  -A xxx -10 ...
  } elsif (substr($ARGV[$opt],0,1) eq "-" && substr($ARGV[$opt],1,1) =~ /\p{IsLu}/) {
    $plotOpt = substr($ARGV[$opt],1);
    $hw = $opt;
  }
  
}
die "A .ccf[ct] file must be given" unless (defined($ARGV[$hw+1]));
$ccf = $ARGV[$hw+1];
$stateless = 0;
$bare = "";
if ($ccf !~ /\./) { #bare file
  $bare = $ccf;
  $ccf .= ".ccf";
}
@names = split(/\./,$ccf);
$ext = $names[1];
if ($ccf =~ "theory" && $ext eq "ccf") { #intermediate stateless calc file?
  if (-e $ccf) { #check for .ccf
    $stateless = 1;
  } else {
    if ($bare) { # try .ccfc
      $ccf .= "c";
    }
    unless (-e $ccf) {
      if ($bare) {
        die "Can't find calculated file $bare.ccf[c]";
      } else {
        die "Can't find calculated file $ccf";
      }
    }
  }
} else {
  if ($ext eq "ccft") {
    $stateless = 1;
  }
  if ($ext eq "ccf") {
    open (CCF, "<$ccf") || die "No configuration file $ccf";
    $head = <CCF>;
    @heads = split(' ', $head);
    if (not defined($heads[1])) {
      $stateless = 1;
    }
    close CCF;
  }
die "given file ",$ccf," not found" unless (-e $ccf);
}
#print "Xcute file: |$ccf|  stateless $stateless\n";  #debug
$ranges = "";
for ($r=$hw+2; defined($ARGV[$r]); $r++) {
  $ranges .= " $ARGV[$r]";
}

$options = "";
$options .= " -V" if ($Voption);
$options .= " -A" if ($altOpt);
$options .= " -Z" if ($Zoption);
if ($stateless) {
  system "perl Xcutel $ccf $ranges";
} else {
  system "perl XcuteS $options -$plotOpt $ccf $ranges";
}
