#!/usr/bin/perl -w

#        Fix trial numbering schemes

use strict;

# The variable $pti stands for pre-trial-interval
my($i, $k, $m, $n, $index, $timepoints, $block, $stimulus, $pti, $prev_trial, $prev_cond, $prev_trial2, $prev_cond2, @a);

$timepoints = 0;
$stimulus = 0;
$block = 0;
$pti = 0;
$index=1;
$prev_trial=0;
$prev_cond=0;
$prev_trial2=0;
$prev_cond2=0;


if($#ARGV != 5){
  print STDERR "Usage: strip.pl <input.asc> <output.strip> <timepoints> <stimulus> <block> <pre-trial interval>\n";
  exit;
};

open(FILE1, $ARGV[0])    || die "Could not open $ARGV[0]: $!\n";
open(FILE2, ">$ARGV[1]") || die "Could not open $ARGV[1]: $!\n";

$timepoints = $ARGV[2];
$stimulus = $ARGV[3];
$block = $ARGV[4];
$pti = $ARGV[5];

$n = $timepoints+$pti;

print STDERR "In block $block, the number of time points per trial using stimulus $stimulus is $n.\n";

while(<FILE1>){
  push @a, [ split ];
}

my $j=0;

# Loop through all elements of the array (starting at line 5)
for $i (10..$#a-1){

    if( $a[$i][0] != $a[$i-1][0] ){
    	$prev_trial2 = $a[$i-1][0];
	$prev_cond2  = $a[$i-1][1];
    }

    # If we match the first stimulus
    if( $a[$i][3] eq $stimulus ){
	
	# Name variables for block of data
	my $trial = $a[$i][0];
	my $cond  = $a[$i][1];
	
	# If we are starting a new trial and
	#  the current (new) trial does not equal
	#  the previous_trial_number+1, then print
	#  a block of dummy values.  This is to 
	#  provide a continuous trial series for
	#  emcp.
	
	if($trial != $prev_trial+1   &&
	   $trial > 0                ){
	    print STDERR "** HEY: Stm detected at current trial $trial, but last stm was at trial $prev_trial.\n";
	    
	    for $k ( 0..($pti+($timepoints-1)) ){
		$j++;
		print FILE2 "$block\t$prev_trial2\t$prev_cond2\t$j";
		
		for $m (3..$#{$a[$i]}){
		    print FILE2 "\t0";
		}

		# Tag a return on the end
		print FILE2 "\n";	
	    }
	}
	
	# Print out N lines following
	for $k (($i-$pti)..($i+$timepoints-1)){
	    $j++;
	    print FILE2 "$block\t$trial\t$cond\t$j";
	    
	    for $m (3..$#{$a[$k]}){
		print FILE2 "\t$a[$k][$m]";
	    }
	    
	    # Tag a return on the end and record trial number and cnd
	    print FILE2 "\n";
	}

	$prev_trial = $a[$i-1][0];
	$prev_cond  = $a[$i-1][1];
	
    }
}

close(FILE1);
close(FILE2);



