#!/usr/bin/perl -w

use strict;

use Astro::Time;
use Astro::Vex;

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

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

if ((!defined $vex)) {
  die "Error reading vexfile\n";
}

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

my @scans = $vex->sched;

#my $time = "20030618:105010";
my $time = "20040418:040210";

# Convert time code to MJD

my ($year, $month, $day, $hr, $min, $sec) = $time =~ /(\d\d\d\d)(\d\d)(\d\d):
						      (\d\d)(\d\d)(\d\d)/x;
my $mjd = cal2mjd($day, $month, $year, hms2time($hr, $min, $sec));

# Find which scan this time corresponds to. Assume that the scan list is in order
my $found = 0;
my ($sourcename, $modename);
foreach (@scans) {

  last if ($_->start > $mjd);
  next if ($_->stop < $mjd);

  # This must be the scan we want!

  $found = 1;
  printf("Found: %s start=%s source=%-8s\n", $_->scanid,  $_->startepoch, 
	 $_->source);
  $sourcename = $_->source;
  $modename = $_->mode;
  last;
}
if (!$found) {
  print "No scan found\n";
} else {
  my $source = $vex->source($sourcename);
  
  printf "Source: %s  %s %s\n", $source->source_name,
    rad2str($source->ra, 'H', 2) , rad2str($source->dec, 'D', 1);
  print "Mode: $modename\n";

  # Just grab the first two stations
  my @stations = $vex->stationlist;
  my $id = $stations[0];

  my $mode = $vex->mode($modename)->{$id};

  my $rate = $mode->sample_rate;

  print "Mode: $modename  $rate\n";
  my @chans = $mode->chan_def;

  my $c = $mode->chan_def('CH01');
  print $c->freq, "\n";

  foreach (@chans) {
    print @$_, "\n";
    print $_->freq, "\n";
  }
}

