#!/usr/bin/perl
use strict;
my $group=`cat ../qiime/compare.txt`;
chomp $group;

$group="Group";
my %meta;

open(IN,"../qiime/meta.txt")||die;
open(OUT,">meta.txt")||die;
my $head=<IN>;chomp $head;
my @header=split("\t",$head);
my $samplehead=shift(@header);
my $i=0;
my $keep;
foreach my $ea(@header){
	$keep=$i if $ea eq $group;
	$i++;
}
if(!$keep){
	open(LOG,">error.log")||die;
	print LOG "No column found for $group.\n";
	close LOG;
	exit;
}
print OUT join("\t",($samplehead,$header[$keep]))."\n";
while(my $line=<IN>){
	chomp $line;
	my @tmp=split("\t",$line);
	my $sid=shift(@tmp);
	print OUT join("\t",($sid,$tmp[$keep]))."\n";
}
close IN;
close OUT;
	


system("summarize_taxa.py -i ../qiime/qiime_results/data_mc100/final_otu_map_mc100_tax.biom -m meta.txt -L 7 -a -d ';' ");

system("sed -i 's/[|]/_/g' meta_L7.txt");
system("sed -i 's/;/|/g' meta_L7.txt");

open(IN,"meta_L7.txt")||die;
open(OUT,">lefse_L7.txt")||die;
my $firstline=<IN>;
chomp $firstline;
my @header=split("\t",$firstline);
my @header1;

my $smaplehead=shift(@header);
my $group=shift(@header);
#print join("\n",@header)."\n";
foreach my $ea(@header){
	my @tmp=split("\\|",$ea);
	$tmp[0]=~s/^k__/K\:/;
	$tmp[1]=~s/^p__/P\:/;
	$tmp[2]=~s/^c__/C\:/;
	$tmp[3]=~s/^o__/O\:/;
	$tmp[4]=~s/^f__/F\:/;
	$tmp[5]=~s/^g__/G\:/;
	my $genus=$tmp[5];
	$genus=~s/^G\://;
	$tmp[6]=~s/^s__//;
	$tmp[6]=$genus."_".$tmp[6];
	$ea=join("\|",@tmp);
	push(@header1,$ea);
}
print OUT join("\t",($samplehead,$group,@header1))."\n";
while(my $line=<IN>){
	print OUT $line;
}
close OUT;
close IN;
