#!/usr/bin/perl -w
use strict;

use Astro::Time;

my $exper;
my $startDate;
my $stopDate;
my $startUT;
my $stopUT;
my $tels;

sub resetVars() {
  $exper = 'xx';
  $startDate = 'xx';
  $startUT = 'xx';
  $stopDate = 'xx';
  $stopUT = 'xx';
  $tels = 'xx';
}

my @LBAant = ('At', 'Mp', 'Ho', 'Cd', 'Pa', 'Wa', 'Td');
sub isLBA ($) {
  my $tels = shift;
  foreach (@LBAant) {
    if ($tels =~ /$_/) {
      return(1);
    }
  }
  return(0);
}

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

resetVars();

my $preamble = 1;
while (<>) {
  s/\#.*$//;
  if (/^\s*$/) {
    next;
  }

  if ($preamble) {
    if (/^\s*Version\s+\S+/) {
      $preamble = 0;
      next;
    } else {
      next;
    }
  } elsif (/Observational code:\s*(\S+)/) {
    $exper = $1;
  } elsif (/Start\(UT\): (\S+)\s*(\S+)/) {
    $startDate = $1;
    $startUT = $2;
    $startDate =~ s/\./\//g;
  } elsif (/Stop\(UT\)\s*:\s*(\S+)\s*(\S+)/) {
    $stopDate = $1;
    $stopUT = $2;
    $stopDate =~ s/\./\//g;
  } elsif (/GRT: (\S.*\S)/) {
    $tels = $1;
    if (isLBA($tels)) {
      $tels =~ s/\(.*?\)//g;
      $tels =~ s/,//g;
      print "$exper, $startDate, $startUT, $stopDate, $stopUT, \"$tels\"\n";
    }
    resetVars();
  } elsif (/^\s*GRT:/) {
    resetVars();
  } elsif (/^\s*Pcal:/ || /^\s*Task:/ || /^\s*Proposals:/ || /^\s*Source:/ || /^\s*Comments:/) {
    # Ignore
  } elsif (/^\s*Band:\s*(\S+)/) {
    # Ignore for now
  } elsif (/^\s*=+\s*$/) {
    last;
  } else {
    warn "Skipped $_\n";
  }

  

}
