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

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

my $antenna = undef;
my $debug=0;
my $help = 0;
GetOptions('antenna=s'=>\$antenna, 'debug'=>\$debug, 'help'=>\$help);

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

sub mode2setup($$$) {
  my ($mode, $bits, $complex) = @_;
  my @chans = $mode->chan_def;

  my $bandwidth = $chans[0]->bw->unit('MHz')->value;
  foreach (@chans) {
    if ($_->bw != $bandwidth) {
      die "Inconsistent channel bandwidths. Mode not supported!!\n";    
    }
  }

  # Assume for now dual pol as that is all Parkes supports

  my $j5mode = 'VDIF';
  $j5mode .= 'C' if $complex;
  my $nchan = 2;
  my $framesize = 8000;
  $framesize = 8192 if $bandwidth == 128;
  my $rate = $bandwidth*2*$nchan*$bits;
  $j5mode .= sprintf("_%s-%d-%d-%d", $framesize, $rate, $nchan, $bits);

  return $j5mode;
  
}

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

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

my $exper = $vex->exper->exper_name;


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

if (@scans==0) {
  die "No scans found for antenna $antenna\n";
}

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

my $first = 1;
my $last_stop;

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

my $bits = 2;
my $complex = 1;

# Looks for modes

my %modes;
foreach (@scans) {
  my $modename = $_->mode;
  if (! exists $modes{$modename}) {
    $modes{$modename} = mode2setup($vex->mode($modename)->{$antenna}, $bits, $complex);
  }
}

my $j5mode = $modes{(keys %modes)[0]};
if (keys %modes > 1) {
  foreach (values %modes) {
    die "Multiple modes ($_/$j5mode) detected. Aborting\n" if ($_ ne $j5mode);
  }
}

print<<EOF;
mtu 9000
net_port 10000
mode $j5mode
net_protocol udpsnor
exper $exper
antenna $antenna
EOF

foreach (@scans) {

  $scanid = $_->scanid;
  $start = $_->start;
  $stop = $start + $_->stations($antenna)->datastop->unit('day')->value;

  ($dayno, $year, $ut) = mjd2dayno($start);
  my $startstr = sprintf("$dayno/%s",turn2str($ut,'H',0));
  ($dayno, $year, $ut) = mjd2dayno($stop);
  my $stopstr = sprintf("$dayno/%s",turn2str($ut,'H',0));
  print "$scanid $startstr $stopstr\n", ;
}


