#!/usr/bin/env perl

# This code is part of the MOCAT analysis pipeline
# Code is (c) Copyright EMBL and BGI, 2012-2013
# This code is released under GNU GPL v3.

# Takes an abundance tabke as input and produces fractions file as output

# Usage: MOCATFraction.pl -in INFILE -out OUTFILE [-colnames 1 -rownames 1 -sep '\t']
# NOTE: colnames and rownames are number of header rows and number of rownames rows (rownames is always 1 I suppose), and this number
# excludes the number of comment lines starting with #. This means, even though MOCAT tables has 4 comment lines, colnames is still 1.

use strict;
use warnings;
use Getopt::Long;

my ($in, $out, @sum);
my $rownames = 1;
my $colnames = 1;
my $sep = "\t";

GetOptions(
	'in:s'  => \$in,
	'out:s' => \$out,
	'colnames:s' => \$colnames,
	'rownames:s' => \$rownames,
	'sep:s'      => \$sep
	);


open IN, "<$in" or die "ERROR & EXIT: Cannot read $in";
my $counter = 0;
while (<IN>){
	chomp;
	unless (m/^#/) {
		$counter++;
		if ($counter > $colnames) {
			my @line = split "$sep", $_;
			for my $i ($rownames .. scalar @line - 1 ){
				unless ($line[$i] eq 'NA') {
					$sum[$i] += $line[$i];
				}
			}
		}
	}
}
close IN;

open IN, "<$in" or die "ERROR & EXIT: Cannot read $in";
open OUT, ">$out" or die "ERROR & EXIT: Cannot write $out";
$counter = 0;
while (<IN>){
	chomp;
	my $final_line = "";
	if (m/^#/) {
		$final_line = "$_";
	} elsif ($counter < $colnames) {
		$counter++;
		$final_line = "$_";
	} else {
		$counter++;
		my @line = split "$sep", $_;
		for my $i (0 .. $rownames - 1) {
			$final_line = "$final_line$line[$i]$sep";
		}
		for my $i ($rownames .. scalar @line - 1 ){
			if ($line[$i] eq 'NA') {
				$final_line = "$final_line" . "NA" . "$sep";
			} else {
				$final_line = "$final_line" . ($line[$i] / $sum[$i]) . "$sep";
			} 
		}
	}
	if ($final_line =~ m/^# MOCAT/) {
		$final_line = $final_line . " (fractions)";
	}
	$final_line =~ s/$sep$//;
	print OUT "$final_line\n";
}
close IN;
close OUT;

exit 0;
