#!/usr/bin/perl

sub Usage {

  print "usage: runPwi.pl <start> <stop>\n\n";
  print "where:     <start> = start date (YYDDD)\n";
  print "           <stop>  = stop date (YYDDD)\n\n";

}


sub IncDate {

  my ($Date) = @_;

  my $Year = substr($Date, 0, 2);
  my $Day  = substr($Date, 2);

  $Day++;

  $Date = sprintf "%02d%03d", $Year, $Day;

  return ($Date);

}


################
# main program #
################

my @DataTypes = ('sfrA', 'sfrB', 'lfcA', 'lfcB', 'sfrph', 'lfcph', 'DCEF');

my %Type = ('sfrA', 0, 'sfrB', 0, 'lfcA', 1, 'lfcB', 1, 'sfrph', 2, 'lfcph', 3, 'DCEF', 4);
my %Rcvr = ('sfrA', A, 'sfrB', B, 'lfcA', A, 'lfcB', B);

my $PATH = "/cache2/THEMIS_weygand/DE1/waves_pwi/highres_vmsbin";
my $PWI  = '/cache2/THEMIS_weygand/DE1/waves_pwi/highres_vmsbin/pwi';

if (! @ARGV) {
  Usage();
  exit();
}

my ($Date, $Stop) = @ARGV;

if (! ($Date =~ /\d{5}/)) {
  print "runPwi.pl: Invalid start date: $Date\n";
  Usage();
  exit();
}

if (! ($Stop =~ /\d{5}/)) {
  print "runPwi.pl: Invalid stop date: $Stop\n";
  Usage();
  exit();
}

while ($Date le $Stop) {

  foreach my $Type (@DataTypes) {

    my $OutFile = sprintf "de1_pwi_%s_%05d.dat", $Type, $Date;

    print "creating file: $OutFile\n";
    open (PWI, "|$PWI");
    print PWI "$Type{$Type}\n";
    if ( exists ($Rcvr{$Type})) {
      print PWI "$Rcvr{$Type}\n";
    }
    print PWI "$Date 000000\n";
    print PWI "$Date 235959\n";
    print PWI "$Type/$OutFile\n";
    close (PWI);

  }

  $Date = IncDate($Date);

}
