#!/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, 'o|overwrite'=>\$overwrite);


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 the session wiki page
-o             overwrite existing wiki page instead of appending
EOF
  ;
}


sub redirect($) {
  my $schedule = shift;
  $schedule =~ s/\.[^\.]*$/.csv/;

  print "Writing to $schedule\n";
  open OUTFILE, '>', $schedule;
  select OUTFILE
}

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

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

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


#my $first=1;
#my $session;
my $outfile = ();
my $timestamp = ();
my $basedate = 0;

unless ($stdout) {
  redirect($filename);
}

sub printExper($$$$$$$) {
  my ($exper, $description, $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 $startdate = sprintf("%2d/%02d/%d", $day, $month, $year);
  my $start_t = mktime(0,$min,$hour,$day,$month-1,$year-1900);
  
  ($day, $month) = dayno2cal($enddayno, $year);
  ($hour, $min) = $endtime =~ /(\d+):(\d+)/;
  #my $enddate = sprintf("%2d/%02d/%d", $day, $month, $year);
  my $end_t = mktime(0,$min,$hour,$day,$month-1,$year-1900);

  my $long = 0;
  if ($startdayno != $enddayno) {
    if ($end_t-$start_t>=60*60*24) {
      warn("Splitting $exper as it is long\n");
      $long = 1;
    }
  }

  $ENV{TZ}=$TZ;

  if ($long) {
    printf("$exper, %s, %s, %12s\n", strftime("%d/%m/%Y, %H:%M", localtime($start_t)), strftime("%d/%m/%Y, 23:59:59", localtime($start_t)), "\"$description\"");
    printf("$exper, %s, %s, %12s\n", strftime("%d/%m/%Y, 00:00", localtime($end_t)), strftime("%d/%m/%Y, %H:%M", localtime($end_t)), "\"$description\"");

    #printf("$exper, $startdate, $starttime, $startdate, 24:00, %12s\n", "\"$pi: $subtext$stations\"");
    #printf("$exper, $enddate, 00:00, $enddate, $endtime, %12s\n", "\"$pi: $subtext$stations\"");
  } else {
    printf("$exper, %s, %s, %12s\n", strftime("%d/%m/%Y, %H:%M", localtime($start_t)), strftime("%d/%m/%Y, %H:%M", localtime($end_t)), "\"$description\"");
  }
}

print "Subject, Start Date, Start Time, End Date, End Time, Description\n";

while (<>) {
  # #! indicates a subarray. # on its own is a comment
  my ($subarray) = 0;
  if (s/#!//) {
    $subarray = 1;
  };
  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);

#    if ($first) {
#      $first=0;
#      $session = sprintf("LBA%s%d", month2str($month), $year);
#    }

    my ($subtext) = '';
    if ($subarray) {
      # display subarrays in italics
      $subtext = '(subarray)';
    }

    printExper($exper, "$pi: $subtext$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 $_"; 
  }
}



