#!/usr/bin/perl -w

use strict;

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

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

my $ant = 'At';
my $debug=0;
my $paddledur=180;
my $pointingdur=240;

my $antname = 'ATCA';

GetOptions('ant=s'=>\$ant, 'debug'=>\$debug, 'paddle=i'=>\$paddledur, 'pointing=i'=>\$pointingdur);

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

my $vexfile = shift;
my $scanfile = shift;

$antname = 'Mopra' if (uc $ant eq 'MP');

# Parse the vexfile

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

# Read the additional scans to add

my %newscans = ();

open(FH, $scanfile) or die "Could not open $scanfile: $!";

while (<FH>) {
  chomp;
  s/\#.*$//;  # Remove comments
  next if (/^\s*$/); # Skip blank lines
  
  my ($scan, $type, $pos) = split;
  if (!defined $scan || !defined $scan || !defined $scan) {
    warn "Skipping $_\n";
    next;
  }

  $newscans{$scan} = [$type, $pos];
}

# Read the unparsed vex onto a scaler

my $vexstr;
{
  local $/;
  open my $fh, '<', $vexfile or die "can't open $vexfile: $!";
  $vexstr = <$fh>;
}

my $outvex = "$vexfile.$$.out";
open(VEXOUT, '>', $outvex) || die "Could not open output $vexfile: $!\n";

$vexstr =~ /\$SCHED\s*\;/is;
print VEXOUT "$`$&";

$vexstr = $';

while ($vexstr =~ /scan.*?endscan\s*\;/si) {
  my $pre = $`;
  my $scan = $&;
  $vexstr = $';
  
  $scan =~ /scan\s+(\S+)\s*\;/si;
  my $name = $1;

  if (exists $newscans{$name}) {
    my $type = $newscans{$name}[0];
    my $pos = $newscans{$name}[1];

    if (uc $pos eq 'POST') {
      print VEXOUT $pre, $scan;
    } elsif (uc $pos eq 'PRE') {

    } else {
      die "Don't understand relative position $pos for scan $name\n";
    }
    my $vexscan = $vex->sched($name);

    my ($intent, $start, $dur);

    my $postfix;
    if (uc $type eq 'POINTING' or uc $type eq 'POINT') {
      $dur = $pointingdur;
      $intent = "REFERENCE_POINTING_DETERMINE";
      $postfix = 'P';
    } elsif (uc $type eq 'PADDLE') {
      $dur = $paddledur;
      $intent = "${antname}:PADDLE";
      $postfix = 'p';
    } else {
      die "Don't understand scan type $type\n";
    }

    my $newname = "$name$postfix";
    my $newscan = $scan;

    if (uc $pos eq 'POST') {
      $start = $vexscan->start + $vexscan->stations($ant)->datastop->unit('day')->value;
    } else { # PRE
      $start = $vexscan->start - $dur/(60*60*24);
    }

    $start = mjd2vextime($start);
    
    $newscan =~ s/^.*?intent\s*=.*?\n//mig; # Remove existing intents
    $newscan =~ s/scan\s+\S+\s*\;/scan $newname\;\n* intent = \"$intent\"/;

    #$newscan =~ s/station\s*=$ant/statXXXion=$ant/; #  Will change back later
    #$newscan =~ s/^\s*station\s*=.*?\;\n//msig; # Remove other stations
    #$newscan =~ s/statXXXion=$ant/station=$ant/; #  Will change back later

    $newscan =~ s/(station\s*=.*?sec\s*:\s*)\d+(\s*sec)/$1$dur$2/ig; #  Change length of scan
    $newscan =~ s/start\s*=.*?\S+\s*\;/start=$start\;/i; #  Change start time of scan
    
    print VEXOUT "\n* Scan added by addATCAscans.pl\n";
    print VEXOUT $newscan;

    if (uc $pos eq 'PRE') {
      print VEXOUT $pre, $scan;
    } 
  } else {
    print VEXOUT $pre, $scan;
  }
}

print VEXOUT $vexstr;

close(VEXOUT);

# Rename files and move original to backup

if ($vexfile =~ /^(.*)\.([^\.]+)$/) {
  my $index = 1;
  while (-f "$1.$index.$2") {
    $index++;
  }
  my $newvex = "$1.$index.$2";
  print "Moving $vexfile -> $newvex\n";
  rename $vexfile, $newvex;
  rename $outvex, $vexfile


} else {
  warn "Could not rename $vexfile. Output left as $outvex\n";
}



