#!/usr/bin/perl

# The following are lookup tables to convert the values.  See the description
# file for more information.

@vdiv=(.003, .01, .03, 0.1, 0.3, 1, 3, 10, 30, 100);
@sdiv=(50e-9, 100e-9, 200e-9, 500e-9, 1e-6,
    2e-6, 5e-6, 10e-6, 20e-6, 50e-6, 100e-6, 200e-6, 500e-6,
    1e-3, 2e-3, 5e-3, 10e-3, 20e-3, 50e-3, 100e-3, 200e-3,
    500e-3, 1, 2);

$_=<>; # heading
    die "This data file does not appear to have a DSO section.\n"
	unless $_ =~ /^DSO/;

$_=<>; # MODE - skip

$_=<>;
/1_V\/D ([0-9a-fA-F]{2})/ or die "Can't read 1_V/D\n";
$vdiv=$vdiv[hex $1];

$_=<>; # 1_CPL
$_=<>; # 1VPOS
/1VPOS ([0-9a-fA-F]{2})/ or die "Can't read 1VPOS\n";
$vpos=hex $1;

$_=<>; # 2_V/D
$_=<>; # 2_CPL
$_=<>; # 2VPOS

$_=<>; # S/DIV
/S\/DIV ([0-9a-fA-F]{2})/ or die "Can't read S/DIV\n";
$sdiv=$sdiv[hex $1];
$roll = (hex $1) >= 0x14;

$_=<>; # MEM
$_=<>; # T_MOD
$_=<>; # T_SOU
$_=<>; # T_CPL
$_=<>; # SLOPE
$_=<>; # POINT
$_=<>; # LEVEL

$_=<>;
die "Problems with the data" unless $_ =~ "^WAVE1";

# Cut off after 8 divisions in roll mode
$max = $roll ? 8 : 50;

for ($i=0; $i<$max; $i++)
{
    $_=<>;

    # Chop twice, because we have DOS-style \r\n pairs
    chop;chop;
    @data=split /,/;

    for ($j=0; $j<20; $j++)
    {
	$datum=hex $data[$j];

	# Now scale.  20 is one division.  0x80 is the center of the screen,
	# and smaller values are towards the *top* (so it's backwards).
	# Also, we must correct for the VPOS, which is (approximately) 19
	# per division.

	$datum=(127-$datum)*$vdiv/20 + (128-$vpos)*$vdiv/18;

	# Now we want the time.  This is the ($i*20+j)th data point, and
	# each data point is $sdiv/20 seconds.

	$time=($i*20+$j)*$sdiv/20;

	print "$time, $datum\n";
    }
}
