#!/usr/bin/perl -w

# transpose.pl
# 8.5.2; djd
# 10.18.3; kam

use strict;

my($i, $j, $k, $l, $m, $z, @a, @omitted, $block, $trial, $timpt, $npts, $index, $channels, $totalom, $skipme);

$block =0;
$trial =0;
$timpt =0;
$npts  =0;
$index =0;
$channels =0;

# Note that usage is different here: We spec timepoints too
if($#ARGV <= 3){
  print STDERR "Usage: transpose.pl <input.strip> <output.flip> <timepoints.total> <channels.total> optional: <channel.omit.1> <channel.omit.2> etc\n";
  exit;
};

open(FILE1, $ARGV[0])    || die "Could not open $ARGV[0]: $!\n";
open(FILE2, ">$ARGV[1]") || die "Could not open $ARGV[1]: $!\n";

$npts = $ARGV[2];
$channels = $ARGV[3];

for($m=4; $m<$#ARGV+1; $m++)
{
   $omitted[$m-4] = $ARGV[$m]+5;
}
$totalom = $m-4;

print STDERR "Number of time points is $npts.\n";

$npts = $npts-1; # For-loop correction
$channels = ($channels+6)-1;

while(<FILE1>){
  push @a, [ split ];
}

for $i (0..$#a){  

  if($a[$i][1] ne $a[$i-1][1]){

    $index++;
    $block = $a[$i][0];
    $trial = $a[$i][1];
    $timpt = $a[$i][2];

    # Adjust this if IDChannels changes
    # First channel starts in col 7
    for $k (6..$channels){
	
    $skipme = 0;
	
        #Check to see if we are ignoring this channel
        if($#ARGV > 3)
	{
	    for $z (0..$totalom-1)
	    {
	       if($k == $omitted[$z])
	       {
 		    $skipme = 1;
		    $z = $totalom;
	       }
	   }
        }
     
	if($skipme == 0)
        {
	   # First print header for channel
    	   print FILE2 "$block\t$trial\t$timpt\n";

    		# For each timepoint (e.g., 1..1520 ) print data
      		for $l (0..$npts)
                {
			print FILE2 "$a[$i+$l][$k]\t";
      		}

    	print FILE2 "\n";
        }
    } 
  }
}

close(FILE2);
$channels-5; # Subtract the 5 we added (+6-1)
print STDERR "There were $index trials in block $block, $channels channels each.\n";








