#!/usr/bin/perl -w

use strict;

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

my $ant = 'Mp';
my $dur = 30;  # Time paddle in
my $delay = 30;  # Insert paddle after this delay from start of scan
my $debug = 0;
GetOptions('ant=s'=>\$ant, 'debug'=>\$debug);

$Astro::Time::StrSep = ':';
$Astro::Time::StrZero = 2;

sub getintent ($);

if (@ARGV!=1) {
  die "Usage vex2padle.pl <vexfile> [-ant AA]\n";
}

my $vexfile = shift;

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

my @scans = $vex->ant_sched($ant);

my ($source, $start, $stop, $dayno, $year, $ut);

my $first = 1;
my $last_stop;

@scans = sort {$a->start <=> $b->start} @scans;

my %intents = getintent($vexfile);

foreach (@scans) {
  my $scan = $_->scanid;

  if (exists $intents{$scan}) {
    my $dopaddle = 0;
    foreach (@{$intents{$scan}}) {
      if ($_ =~ /ATCA:PADDLE/i or $_ =~ /Mopra:PADDLE/i) {
	$dopaddle = 1;
	last;
      }
    }
    if ($dopaddle) {
      $start = $_->start;
      my $scanlength = $_->stations($ant)->datastop->unit('sec')->value;
      if ($scanlength<$delay+$dur) {
	warn "$scan: Duration too short\n";
      } else {
	my ($day, $month, $year, $ut) = mjd2cal($start + $delay/(60*60*24));
	printf("%04d-%02d-%02d %s %d\n", $year, $month, $day, turn2str($ut,'H',0), $dur);
      }
    }
  }
}

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;
}
