#!/usr/bin/perl
#
# tds2012-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 n8ur_gpib qw(checkSRQ serviceSRQ);

my $board = "gpib0";
my $device = "scope";
my $command;
my $status;
my $device_status;
my $done = 0;
my $plot;
my $tmp;


#----------
# handle signals and errors -- mainly to clear lockfile on termination
sub sig_handler {
	sleep 2;
	close PLOTFILE;
	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';
#----------
sub timestamp() {
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
	if ($mon < 10) { $mon = "0$mon"; }
	if ($hour < 10) { $hour = "0$hour"; }
	if ($min < 10) { $min = "0$min"; }
	if ($sec < 10) { $sec = "0$sec"; }
	$year=$year+1900;
	return $year . $mon . $mday . $hour . $min . $sec;
	}

#----------
# display usage
my $opt_string = 'h:s:f:';

sub usage() {
print STDERR << "EOF";

usage: $0 [-h] [-s size] -f output file 

-h      : this (help) message
-f      : output file name; format depends on extension

EOF
}

getopts( "$opt_string", \my %opt ) or usage() and exit;

# print usage
usage() and exit if $opt{h};
usage() and exit if !$opt{f};

# set variables to command line params

my $outfile;
$outfile = $opt{f};

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

# clear any in-progress screen dump
$command = "hardcopy abort";
LinuxGpib::ibwrt($dev,$command,length($command));

$command = "hardcopy:port gpib";
LinuxGpib::ibwrt($dev,$command,length($command));

$command = "hardcopy:layout portrait";
LinuxGpib::ibwrt($dev,$command,length($command));

$command = "hardcopy:format laserjet";
LinuxGpib::ibwrt($dev,$command,length($command));


$command = "hardcopy?";
LinuxGpib::ibwrt($dev,$command,length($command));
LinuxGpib::ibrd($dev,$tmp,80);
print "$tmp\n";

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

LinuxGpib::ibrd($dev,$plot,2000000);

# go local
LinuxGpib::ibloc($dev);

# output routine
open (PLOTFILE, ">$outfile") || die "Can't open $outfile!\n";
print PLOTFILE $plot;
close PLOTFILE;

exit 0;
