package main;

  use strict;
  use Getopt::Long;
  use English;
  use Constants;

# Global variables
  my $SCRIPTNAME = 'generate';
  my $VERSION = '0.1';
  my $VERBOSE = 0;
  my $SHOW_HELP = 0;
  my $SHOW_VERSION = 0;
  my $EDGESIN = '';
  my @Cases = ();
  my $edges = ();
  my %Graph = {};

  my $TestSize = 1;
  my $TestLength = 1;

  &ParseCommandLine();

  # slurp the dataflow spec
  open (EDGES, "<$EDGESIN") or die "could not open file $EDGESIN";
  while (<EDGES>) { $edges .= $_ unless /^%/; }
  close EDGES; 

  # parse each edge 
  foreach my $edge (split("\n",$edges)) {
    my ($transition, $from, $to) = split(/\s*,\s*/, $edge);

    $Graph{$from} = {} unless defined $Graph{$from};
    my $h = $Graph{$from};
    $$h{$transition} = $to;
    #print "$from $to\n";
    }

  my $i = 0;
  for ($i = 1; $i <= $TestSize; $i++) {
    print join(",", @{&generateTest($TestLength)}) . "\n";
    }

sub generateTest {
  my ($length) = @_;
  my $case = [];
  # Starting state
  my $from = 'main';
  while ($length--) {
    my $h = $Graph{$from};
    my $choice = int(rand(scalar keys %$h));
    foreach my $key (keys %$h) {
      if ($choice == 0) {
        push @$case, $key;
        $from = $$h{$key};
        }
      $choice--;
      }
    }
  return $case;
  }

  #open (DATAFLOWOUT, ">$DATAFLOWOUT") or die "could not open file $DATAFLOWOUT";
  #print DATAFLOWOUT join("\n", @FlowRules);
  #close DATAFLOWOUT;

#------------------------------------------------------------------------
sub ParseCommandLine {
  my @switches = (
    'version',      \$SHOW_VERSION,
    'help',         \$SHOW_HELP,
    'verbose',      \$VERBOSE,
    );
 
  &GetOptions(@switches) || die "use -help switch to display brief help\n";
 
  if ($SHOW_VERSION) {
    print "This is $SCRIPTNAME, version $VERSION\n\n";
    exit 0;
    }
 
  if ($SHOW_HELP) {
    print <<EofHelp;
    $SCRIPTNAME, version $VERSION - Generate test cases

    Usage: 

      $SCRIPTNAME  \
         [-help] \
         [-version] \
         [-verbose] \
         [-nop ] \
         < input
 
    Options: 
 
        -help            : display this message
        -verbose         : display verbose information as running
        -version         : display the version of $SCRIPTNAME
        -nop             : turn off <P> 
EofHelp
    exit 0;
    }
 
 if (scalar(@ARGV) != 3) { die "$SCRIPTNAME needs three argument.\n"; }
 $EDGESIN = $ARGV[0];
 $TestSize = $ARGV[1];
 $TestLength = $ARGV[2];
}
