#!/usr/bin/perl 
#
# fetch waveforms from the scope and store as a simple "comma separated
# value" (CSV) file. Channels that are visible on the scope are
# fetched. 
#
use Lab::Instrument::TDS2024B;
use Data::Dumper;
use Getopt::Long;


my $filename;
my $force = 0;
my $tmc_address;
my $visa_name;
my $usb_serial;
my $help = 0;

    
Getopt::Long::GetOptions(
           "force|f" => \$force,
           "tmc_address|t" => \$tmc_address,
           "visa_name|v" => \$visa_name,
           "usb_serial|u" => \$usb_serial,
           "h|?|help" => \$help,
    );

if ($help) {
    print "usage: $0 [options] OUTFILE\n";
    print "\t-f  --force                              force output file overwrite\n";
    print "\t-tX --tmc_address=X                      use /dev/usbtmcX device\n";
    print "\t-vUSB... --visa_name=USB:0xAAAA::0xBBBB::0xCCCC  use visa-style address\n";
    print "\t-uSN     --usb_serial=SerialNumber       select device by serial number\n";
    print "\n";
    print "If device is not specified, first TDS2024B found is used\n";
    exit(0);
}

my $args = {};
$args->{tmc_address} = $tmc_address if defined $tmc_address;
$args->{visa_name} = $visa_name if defined $visa_name;
$args->{usb_serial} = $usb_serial if defined $usb_serial;

$filename = shift;
die("output CSV file must be specified") unless defined($filename);

if (! -e $filename || $force) {
    open(OUT,">$filename") || die("unable to open '$filename' for writing");
} else {
    die("use --force to force overwriting of existing output file");
}

my $s = new Lab::Instrument::TDS2024B($args);

my $nvis = 0;
my (%vis);
foreach my $ch (qw(CH1 CH2 CH3 CH4 REFA REFB REFC REFD MATH)) {
    next unless $s->get_visible($ch);
    $vis{$ch} = $s->get_waveform(waveform=>$ch);
    $nvis++;
}

die("no channels visible") unless $nvis > 0;

my $line;
$line = 'Sample';
my ($jmin,$jmax);
foreach my $ch (sort(keys(%vis))) {
    $line .= ",\"${ch}_X [".$vis{$ch}->{'WFMP:XUN'}.']"';
    if ($vis{$ch}->{'WFMP:PT_F'} eq 'Y') {
	$line .= ",\"${ch}_Y [".$vis{$ch}->{'WFMP:YUN'}.']"';
    } else {
	$line .= ",\"${ch}_Ymin [".$vis{$ch}->{'WFMP:YUN'}.']"';
	$line .= ",\"${ch}_Ymax [".$vis{$ch}->{'WFMP:YUN'}.']"';
    }
    $jmin = $vis{$ch}->{'DAT:STAR'} 
    unless defined($jmin) && $jmin < $vis{$ch}->{'DAT:STAR'};
    $jmax = $vis{$ch}->{'DAT:STOP'} 
    unless defined($jmax) && $jmax > $vis{$ch}->{'DAT:STOP'};    
}
print OUT "$line\n";


for (my $j = $jmin; $j <= $jmax; $j++) {
    $line = $j;
    foreach my $ch (sort(keys(%vis))) {
	$line .= ','.$vis{$ch}->{t}->[$j];
	if ($vis{$ch}->{'WFMP:PT_F'} eq 'Y') {
	    $line .= ','.$vis{$ch}->{v}->[$j];
	} else {
	    $line .= ','.$vis{$ch}->{vmin}->[$j];
	    $line .= ','.$vis{$ch}->{vmax}->[$j];
	}
    }
    print OUT "$line\n";
}
close(OUT);




