#!/usr/bin/perl -w

#
#	collect_data_v4.pl
#
#	Syntax:  collect_data_v4.pl <number of words to read> <output file>
#
#	7 December 2009 v3: Add input variable to allow specifying which slot to use
#
#	2008 v3: Put board to sleep for a bit at beginning
#
#	6 March 2008 v2: Change to accept the number of words to read
#			on the command line.  Then, issue one write/read
#			command, read the buffers, then issue one more
#			write/read command.
#
#	15 Oct 2007 v1:	Starts a vme write command, then
#			waits for buffer to be full and then
#			reads the buffer, converts to decimal
#			and writes it to a file.  This process
#			can be repeated a number of times.
#			

# Check that have the correct number of strings on the input line
if ($#ARGV != 2)
{
	print "Usage:  collect_data_v4.pl <slot> <number of words to read> <output file>\n";
	exit(1);
}

# Setup some variables for items that might change in the future
@ADDRESSES = ("100000","200000","300000","400000","500000","600000","700000","800000"); # Addresses to read

# Get slot of the board
$SLOT = $ARGV[0];
# Get the number of words to read
$WORDS = $ARGV[1];

# Get the output file name and open a stream to that file
$output = $ARGV[2];
open (OUTFILE, ">>$output");

# First step is to prepare the board

`./vme7700 write $SLOT 3c 0`;
`sleep 1`;

print "\nRunning vme7700 write $SLOT 3c 1\n";
# Start of runme_bilbo_slot10------------------
`./vme7700 write $SLOT 3c 1`;

print "\nRunning vme7700 read $SLOT 3c\n";
`./vme7700 read $SLOT 3c`;

print "\nReading data from addresses...\n";

$channel = 0;

foreach $address (@ADDRESSES)
{
	# Print address for debug
	print "$address\n";

	# Initialize $i for arrays
	$i = 0;

	# Put all the hexvalues in a variable hexvalues
	@hexvalues = `./vme7700_block read $SLOT $address $WORDS`;
	
	# There are two channels read with each block, so use nextchannel as well as channel
	$nextchannel = $channel + 1;

	foreach $value (@hexvalues)
	{
		# Convert each hex value to dec and break up by channel
		# 001122aa => 0011 is for channel 1, and 22aa is for channel 0
		$hex1=substr($value,0,4);
		$hex2=substr($value,4,4);
		$data[$channel][$i]=hex($hex2);
		$data[$nextchannel][$i]=hex($hex1);
		$i++;
	}
	$channel=$channel+2;
}	

# Write a 0 to 3c and read again
print "Running vme7700 write $SLOT 3c 0\n";
# Start of runme_bilbo_slot10------------------
`./vme7700 write $SLOT 3c 0`;

print "\nRunning vme7700 read $SLOT 3c\n";
`./vme7700 read $SLOT 3c`;

print "\nReset the board";
`./vme7700 write $SLOT 3c 1`;
# `./vme7700 write $SLOT 44 0`;
`./vme7700 write $SLOT 3c 0`;

# Write the data array to the output file, remember to increment by 2
print "\nWriting the output file...\n";

for( $j=0; $j<$WORDS; $j++)
{
	for($ch=0; $ch<$channel; $ch++)
	{
		print OUTFILE "$data[$ch][$j]\t";
	}
	print OUTFILE "\n";
}

close OUTFILE;

