#!/usr/local/bin/perl -w

use Getopt::Long;
use Astro::Vex;
use Astro::Time;
use Carp;

use strict;

$Astro::Time::StrZero = 2;

sub getintent ($);

my $dotels = 0;
my $domode = 0;
my $dogap = 0;
my $dointent = 0;
my $antid = undef;

GetOptions('telescopes'=>\$dotels, 'mode'=>\$domode, 'gap'=>\$dogap, 'ant=s'=>\$antid, 'intent'=>\$dointent);

if (@ARGV!=1) {
  die "Usage vexsum.pl <vexfile>\n";
}

my $vexfile = shift;

my $vex = new Astro::Vex($vexfile);

print $vex->exper->exper_name, "\n";

my %intents = getintent($vexfile);


# Determine maximum sourcename length
my @sources = $vex->source;
my $maxsource = 0;
foreach (@sources) {
  $maxsource = length($_->source_name)
    if (length($_->source_name)>$maxsource);
}
my $sfmt = " %-${maxsource}s";


my @scans;
if (defined $antid) {
  @scans = $vex->ant_sched($antid);
} else {
  @scans = $vex->sched;
}

my $lastend;
foreach (@scans) {
  my $start = $_->start;
  my $end;
  if (defined $antid) {
    $end = $start + $_->stations($antid)->datastop->unit('day')->value;
  } else {
    $end = $_->stop;
  }
  my $gap = ' ';
  if (defined $lastend && $start-$lastend>5) {
    $gap = '*';
  }
  my ($dayno, $junk1, $ut1) = mjd2dayno($start);
  my ($junk2, $junk3, $ut2) = mjd2dayno($end);
  my $dur = ($end-$start)*60*60*24;

  printf("%-9s %03d/%s - %s$gap %5.0f", $_->scanid, $dayno,
	 turn2str($ut1,'H',0), turn2str($ut2,'H',0), $dur);

  if ($dogap) {
    if (defined $lastend) {
      printf(' %4.0f', ($start-$lastend)*60*60*24);
    } else {
      print '     ';
    }
  }

  printf($sfmt, $_->source);

  if ($domode) {
    print ' ', $_->mode;
  }
  if ($dotels) {
    my @stations = $_->stations;
    print ' ';
    foreach (@stations) {
      print $_->station;
    }
  }

  if ($dointent) {
    if (exists $intents{$_->scanid}) {
      print '  ', join(', ', @{$intents{$_->scanid}});
    }
  }
  
  print "\n";

  $lastend = $end;
}

use constant FINDSCHED => 0;

sub getintent ($) {
  my $vexfile = shift;

  my $mode=0;
  my $scan=undef;

  open(VEX, $vexfile) || croak "Could not open $vexfile: $!\n";

  my %intents;
  while (<VEX>) {
    if ($mode==FINDSCHED) {
      if (/\$SCHED\s*\;/) {
	$mode++;
      }
    } else {
      if (/scan\s+(\S+)\s*\;/) {
	$scan=$1;
      } elsif (/\*\s*intent\s*=\s*\"([^\"]*)\"/) {
	if (!defined $scan) {
	  carp "Intent \"$1\" outside scandef = ignoring\n";
	} else {
	  if (exists $intents{$scan}) {
	    push @{$intents{$scan}}, $1;
	  } else {
	    $intents{$scan} = [$1];
	  }
	}
      } elsif (/endscan\s*\;/) {
	$scan=undef;
      }
    }
  }
  close(VEX);
  return %intents;
}
