#!/usr/bin/perl -w
use strict;
use Astro::Time;
use ATNF::MoniCA;
use IO::Socket;

use constant PORT => 4343;
use constant AK07 => '202.9.10.119';
use constant AK32 => '202.9.10.126';
use constant LOGDIR => '/home/vlbiobs/logs';

use constant MONSERVER => 'localhost';
use constant MONROOT => 'mro.mro.vlbi.';
use constant ELPOINT => 'el';
use constant AZPOINT => 'az';
use constant DELPOINT => 'Del';
use constant DAZPOINT => 'Daz';
use constant STACKPOINT => 'stack';
use constant ELMOTORPOINT => 'elmaster';
use constant AZMOTORPOINT => 'azmaster';
use constant PLCPOINT => 'PLC';

my ($ANT, $antname);
if (@ARGV) {
  my $a = shift;
  if ($a eq 'l' || $a eq 'L' || $a eq '7') {
    $ANT = AK07;
    $antname = 'AK07';
    warn "Connecting to $antname\n";
  } elsif ($a eq 'x' || $a eq 'X' || $a eq '32') {
    $ANT = AK32;
    $antname = 'AK32';
    warn "Connecting to $antname\n";
  } else {
    die "Do not support connecting to antenna $a\n";
  }
} else {
  warn "Assuming connecting to AK07 (L-band)\n";
  $ANT = AK07;
  $antname = 'AK07';
}


my $sock = new IO::Socket::INET (PeerAddr => $ANT,
				 PeerPort => PORT,
				 Proto => 'tcp');

die "Could not create socket: $!\n" unless $sock;


my $mon = monconnect(MONSERVER);
warn "Could not connect to MoniCA host \"".MONSERVER."\"\n" if (!defined $mon);

my @setpoints;
push @setpoints, new MonSetPoint({point => MONROOT.AZPOINT,
				  val => 0,
				  type => 'flt'});
push @setpoints, new MonSetPoint({point => MONROOT.ELPOINT,
				  val => 0,
				  type => 'flt'});
push @setpoints, new MonSetPoint({point => MONROOT.DAZPOINT,
				  val => 0,
				  type => 'flt'});
push @setpoints, new MonSetPoint({point => MONROOT.DELPOINT,
				  val => 0,
				  type => 'flt'});
push @setpoints, new MonSetPoint({point => MONROOT.STACKPOINT,
				  val => 0,
				  type => 'int'});
push @setpoints, new MonSetPoint({point => MONROOT.PLCPOINT,
				  val => 0,
				  type => 'int'});
push @setpoints, new MonSetPoint({point => MONROOT.AZMOTORPOINT,
				  val => 0,
				  type => 'int'});
push @setpoints, new MonSetPoint({point => MONROOT.ELMOTORPOINT,
				  val => 0,
				  type => 'int'});

my $mjd = now2mjd();
my ($dayno, $year, $ut) = mjd2dayno($mjd);
my $lastdayno = $dayno;

my $filename = sprintf("%s/%s-%04d%03d.log", LOGDIR, $antname, $year, $dayno);
open(LOG, '>>', $filename) || die "Could not open $filename: $!\n";

my ($thisline, $line, $status, $size, @vals, $az, $el, $newdayno, $daz, $del, $stack, $tryagain, $match);
my ($elmotor, $azmotor, $plc, $elslave, $azslave, $polmotor);
my $first = 1;

$line = '';
$tryagain=0;
while (1) {

  while ($tryagain || length($line)<20) {
    $status = recv($sock, $thisline, 256,0);
    # Should check $status
    $line .= $thisline;
    $tryagain = 0;
  }

  if (!($line =~ /^fr_ant/)) {
    if ($line =~ /^(.*?)(fr_ant.*)/) {
      warn "Skipping $1\n";
      $line = $2;
      next;
    } else {
      warn "Skipping $line\n\n";
      $line = '';
    }
  }


#fr_ant123456 103OK - 56457.156161007 233.5575 89.9968 -1.297e-3 0.0 0.0 0.0 0 0.2 0.3 0.2 0.0 0.0 49 1285 5 1285 5 1285

  if ($line =~ /^(fr_ant123456\s+\S+ - \d+\.\d+ \S+ \S+ \S+ \S+ \S+ \S+ \S+ \S+ \S+ \S+ \S+ \S+ \d+ \d+ \d+ \d+ \d+ \d+)(.*)$/) {

    $match = $1;
    $line = $2;
    #$size = length($match);
    @vals = split ' ', $match;

    $mjd = $vals[3];
    ($dayno, $year, $ut) = mjd2dayno($mjd);
  
    if ($dayno!=$lastdayno) {
      close(LOG);
      my $filename = sprintf("%s/%s-%04d%03d.log", LOGDIR, $antname, $year, $dayno);
      open(LOG, '>>', $filename) || die "Could not open $filename: $!\n";
      $lastdayno = $dayno;
    }

    $az = $vals[4];
    $el = $vals[5];
    # pol
    $daz = $vals[7];
    $del = $vals[8];
    # dpol
    $stack = $vals[10];

    $plc = $vals[16];
    $azmotor = $vals[17];
    $azslave = $vals[18];
    $elmotor = $vals[19];
    $elslave = $vals[20];
    $polmotor = $vals[21];

    printf(LOG "%d %d/%s %s @vals[4..21]\n", $year, $dayno, turn2str($ut,'H',0), $vals[1]);
    printf("%d %d/%s %s %s %s $daz, $del, %s $plc $azmotor $azslave $elmotor $elslave $polmotor\n", $year, $dayno, turn2str($ut,'H',0), $vals[1], $az, $el, $stack);

    $setpoints[0]->val($az);
    $setpoints[1]->val($el);
    $setpoints[2]->val($daz);
    $setpoints[3]->val($del);
    $setpoints[4]->val($stack);
    $setpoints[5]->val($plc);
    $setpoints[6]->val($azmotor);
    $setpoints[7]->val($elmotor);

    if (defined $mon) {
      my $ret = monset($mon, 'vlbiscript', 'iblv', @setpoints);
      
      if (!$ret->success) {
	warn "Failed to set monitor points\n";
      }
    }
  } else {
    if ($line =~ /^(fr_ant123456.*?)(fr_ant123456.*)$/) {
      warn "\nSkipping:\n\n $1\n\n";
      $line = $2;
    } else {
      $tryagain = 1;
    }
  }
}
