#!/usr/bin/perl
#
# hp8566b-plot.pl

#----------

use strict;
use POSIX qw(setsid);
use Getopt::Std;
use Time::HiRes qw(usleep time gettimeofday);
use LinuxGpib;
use Number::Format;
use n8ur qw(trim squash parse_value);
use hp3585b qw(get_settings fix_freq fix_db fix_sweep);

my $device = "hp8566b";
my $command;

#----------
# handle signals and errors -- mainly to clear lockfile on termination
sub sig_handler {
	sleep 2;
	exit(0);
}

# there's got to be a better way!
$SIG{'HUP'} = 'sig_handler';
$SIG{'INT'} = 'sig_handler';
$SIG{'KILL'} = 'sig_handler';
$SIG{'STOP'} = 'sig_handler';
$SIG{'TERM'} = 'sig_handler';
#----------

#----------------------
# initialize instrument
my $dev = LinuxGpib::ibfind($device) ||
	die "Can't open device $device!\n";

#----------
# Send command

$command = "TRDEF NEWTRACE,1001;TRDEF LOWER,250;VARDEF COUNT,0.0;VARDEF DONE,0.0;VARDEF AMP,0.0;";
LinuxGpib::ibwrt($dev,$command,length($command));

$command = "FUNCDEF MONSETUP !TRPRST;ANNOT OFF;GRAT OFF;";
LinuxGpib::ibwrt($dev,$command,length($command));

$command = "TRDSP TRA OFF;MOV TRB,0;VIEW TRB;EM;KSj;RB3KZ;VB3KZ;AT0DB;LG10DB;RL-10DM;S2;";
LinuxGpib::ibwrt($dev,$command,length($command));

$command = "DA3574DW1026,0,2598,3048,0,2048,420,2072,0,2048,604,0,2098,3048,0,2048,420,2072,0,2048,604,0,3040,1025,200,208,1026,400,3040,";
LinuxGpib::ibwrt($dev,$command,length($command));

$command = "1025,65,77,32,77,79,78,73,84,79,82,32,68,69,77,79,1026,400,2560,1025,83,87,69,69,80,32,79,70,32,65,77,32,66,65,78,68,1026,400,2048,1025,";
LinuxGpib::ibwrt($dev,$command,length($command));

$command = "68,69,77,79,68,32,79,70,32,80,69,65,75,32,83,73,71,78,65,76,1056;";
LinuxGpib::ibwrt($dev,$command,length($command));

$command = "TH-70;MKPX 9;MKTRACE TRB;!";
LinuxGpib::ibwrt($dev,$command,length($command));

$command = "FUNCDEF MONITOR !ST200MS;LG10DB;RL-10DM;RB3KZ;VB3KZ;FA0.5MZ;FB2MZ;TS;MOV NEWTRACE,TRA;MPY NEWTRACE,NEWTRACE,0.42;ADD NEWTRACE,NEWTRACE,550;MOV TRB,NEWTRACE;IF COUNT,GT,0;THEN MKPK NH;MOV CF,MF;ADD COUNT,COUNT,1;ELSE MKPK HI;MOV CF,MF;MOV COUNT,1;ENDIF;IF COUNT,GT,10 THEN MOV,COUNT,0;ENDIF;MOV AMP,MA;ADD AMP,AMP,100;SUB AMP,AMP,RL;MPY AMP,AMP,10;SUB AMP,AMP,550;DIV AMP,AMP,0.42;SUB AMP,AMP,1000;DIV AMP,AMP,10;ADD AMP,AMP,RL;MOV RL,AMP;LN;SP0HZ;RB10KZ;VB10KZ;ST20MS;TS;COMPRESS LOWER,TRA,SMP;MPY LOWER,LOWER,0.42;TRGRPH 3072,0,50,4 LOWER;!";
LinuxGpib::ibwrt($dev,$command,length($command));

#$command = "KEYDEF 13 !MONSETUP;REPEAT MONITOR UNTIL DONE,EQ,1;!";
$command = "KEYDEF 13 !MONSETUP;!";
LinuxGpib::ibwrt($dev,$command,length($command));

$command = "KEYDEF 14 !REPEAT MONITOR UNTIL 0.0,EQ,1.0;!";
LinuxGpib::ibwrt($dev,$command,length($command));

$command = "IP;";
LinuxGpib::ibwrt($dev,$command,length($command));
