#!/usr/bin/perl -w
use strict;
use Astro::Time;
#use DateTime::Format::Strptime;
#use Time::Piece;
#use Time::Local;
use POSIX qw(strftime mktime);

my $year;
my $stdout;
my $overwrite;
my $help;
use Getopt::Long;

GetOptions('stdout'=>\$stdout, 'h|help'=>\$help);

my $longAt = deg2turn(-149.56476);
my $longPa = deg2turn(-148.26352);

sub usage {
  print STDERR<<EOF
Usage: schedblock2csv.pl [options] <blockschedule>
--help, -h     print this information and exit
--stdout       print output to <stdout> instead of posting to a file
EOF
  ;
}

sub redirect($) {
  my $schedule = shift;
  my $fileAt = $schedule =~ s/\.[^\.]*$/_at.json/r;
  my $filePa = $schedule =~ s/\.[^\.]*$/_pa.json/r;

  my ($outAt, $outPa);
  
  if (!$stdout) {
    print "Writing to $fileAt, $filePa\n";
    open $outAt, '>', $fileAt || die "Could not open $fileAt";
    open $outPa, '>', $filePa || die "Could not open $filePa";
  } else {
    $outAt = *STDOUT;
    $outPa = *STDOUT;
  }
  print $outAt "[\n";
  print $outPa "[\n";
  return ($outAt, $outPa);
}

if ($help) {
  usage();
  exit;
}

my ($filename) = $ARGV[0];

my $dayno;
($dayno, $year) = mjd2dayno(now2mjd());

my $outfile = ();
my $timestamp = ();
my $basedate = 0;

my ($outAt, $outPa) = redirect($filename);

sub printExper($$$$$$$) {
  my ($ant, $fh, $exper, $start, $end, $startLST, $endLST) = @_;

  print $fh <<EOF;
   {
      "className": "Schedule",
      "backend": "DAS",
      "array": "",
      "startLST": "$startLST",
      "endLST": "$endLST",
      "receivers": "",
      "start": "$start",
      "end": "$end",
      "title": "$exper"
   }
EOF

}

sub addExper($$$$$$$$$) {
  my ($exper, $outAt, $outPa, $stations, $startdayno, $starttime, $enddayno, $endtime, $year) = @_;

  my $TZ = $ENV{TZ};
  $ENV{TZ}="UTC";
  
  my ($day, $month) = dayno2cal($startdayno, $year);
  my ($hour, $min) = $starttime =~ /(\d+):(\d+)/;
  my $start_t = mktime(0,$min,$hour,$day,$month-1,$year-1900);
  my $startMJD = dayno2mjd($startdayno, $year, ($min/60.0+$hour)/24.0);
  
  ($day, $month) = dayno2cal($enddayno, $year);
  ($hour, $min) = $endtime =~ /(\d+):(\d+)/;
  my $end_t = mktime(0,$min,$hour,$day,$month-1,$year-1900);
  my $endMJD = dayno2mjd($enddayno, $year, ($min/60.0+$hour)/24.0);

  $ENV{TZ}=$TZ;

  my $start = strftime("%Y-%m-%dT%H:%M:%S", localtime($start_t))."+00:00";
  my $end = strftime("%Y-%m-%dT%H%M:%S", localtime($end_t))."+00:00";

  if ($stations =~ /At/ || $stations =~ /All/) {
    my $startLST = turn2str(mjd2lst($startMJD, $longAt), 'H', 0);
    my $endLST = turn2str(mjd2lst($endMJD, $longAt), 'H', 0);
    printExper('At', $outAt, $exper, $start, $end, $startLST, $endLST);
  }
  if ($stations =~ /Pa/ || $stations =~ /All/) {
    my $startLST = turn2str(mjd2lst($startMJD, $longPa), 'H', 0);
    my $endLST = turn2str(mjd2lst($endMJD, $longPa), 'H', 0);
    printExper('Pa', $outPa, $exper, $start, $end, $startLST, $endLST);
  }
}

while (<>) {
  s/#!//; # #! indicates a subarray. # on its own is a comment
  s/#.*$//;
  s/^\s+//;
  next if ($_ eq '');

  if (/(\S+)\s+                # Experiment
       (\S+)\s+                # Setup
       (\S+)\s+                # Stations
       ([+-]?\d+)\s+(\d\d)(\d\d)\s+ # start
       ([+-]?\d+)\s+(\d\d)(\d\d)\s+ # end
       (\S+)                   # PI
      /x) {
    my $exper = $1;
    my $freq = $2;
    my $stations = $3;
    my $startdayno = $4 + $basedate;
    my $starttime = "$5:$6";
    my $enddayno = $7 + $basedate;
    my $endtime = "$8:$9";
    my $pi = $10;

    $pi =~ s/check//;
    $pi =~ s/evlbi//i;
    $pi =~ s/_/ /;
    $pi =~ s/\([^)]*\)//;

    my ($day, $month) = dayno2cal($startdayno, $year);
    my $startdate = sprintf("%2d/%02d/%d", $day, $month, $year);

    ($day, $month) = dayno2cal($enddayno, $year);
    my $enddate = sprintf("%2d/%02d/%d", $day, $month, $year);

    addExper($exper, $outAt, $outPa, $stations, $startdayno, $starttime, $enddayno, $endtime, $year);

  } elsif (/Basedate\s+(\d+)/) {
    $basedate = $1;
  } elsif (/Version/) {
    /Time-stamp: (.*)/;
    print STDERR "Version: $1\n";
  } elsif (/Start\s+(\d+)\s+\d+\s+\S+/) {
    $year=$1;
  } elsif (/Stop\s+(\d+)\s+\d+\s+\S+/) {
    $year = $1;
  } else {
    warn "Skipping $_"; 
  }
}

print $outAt "]\n";
print $outPa "]\n";
if (!$stdout) {
  close($outAt);
  close($outPa);
}
