#!/usr/bin/perl
use Bio::SeqIO;
use Bio::Seq::Quality;
use Bio::Seq::SequenceTrace;
use Statistics::Descriptive;


# to run need to generate a list of all scf files in the directory
# one way to do this is to use the unix expression ls * > list
#the STDOUT is a csv file of data output.  can also print a tab delimited summary of mean, count, stderror etc
# Usage:
#perl scf-qscores.pl <list file name> <tab-delimited outfile name>
# T. Read October 2009
# No warranties of any kind attached to using this file!

$" = "\,";  #list separator
my @AoA;

open (IN,"$ARGV[0]");
while (<IN>) {
	chomp;
	#print "processing $_\n";
	my $in  = Bio::SeqIO->new(-file => "$_",
						   -format => 'scf');
	my $trace = $in->next_seq ; 
	my @qual = @{$trace->qual()};
	#print "@qual\n";
	push (@AoA, [ @qual ]);	
	}

print "row\,values";	

open (OUT,">$ARGV[1]");
print OUT  "Dist from Start\tCount\tmean\tStdDev\n";	
for (my $i = 0;$i <651;$i++) {
	print "\n".$i."\,";
	my $stat = Statistics::Descriptive::Sparse->new();
	for (my $array = 0; $array < scalar(@AoA);$array++) {
			if ($AoA[$array][$i] eq "UNKNOWN") {$AoA[$array][$i] = "\.";}
			elsif ($AoA[$array][$i]) {
				print "$AoA[$array][$i]\,";
				$stat->add_data($AoA[$array][$i]);
				}
			else {$AoA[$array][$i] = "\.";}
			}
	my $mean = $stat->mean();
	my $count = $stat->count();
	my $stddev = $stat->standard_deviation();
	print OUT "$i\t$count\t$mean\t$stddev\n";	
		
	}