#Perl Code for Recovering Clustering Result from Preprocessed Sequences to Original Ones
#Provided with ESPRIT : Yijun Sun and Yunpeng Cai, et.al.
#Citation: ESPRIT: Estimating Species Richness Using Large Collections of 16S rRNA Pyrosequences
#Yijun Sun, Yunpeng Cai, Li Liu, Fahong Yu, Michael L. Farrell, William McKendree, William Farmerie
#Nucleic Acids Research, 2009; doi: 10.1093/nar/gkp285. 
#Website: http://www.biotech.ufl.edu/people/sun/esprit.html
# Usage: perl invmap.pl input_file map_file output_file
#
#Input: 
#input_file:  The clustering result *.Cluster file generated by ESPRIT on processed (_Clean.fas) sequences 
#map_file:  The .map file generated by preproc
#output_file:  The clustering result that are mapped to the orgininal FASTA file, where the first sequence is indexed as 0
#


unless (open(filein,$ARGV[0])) {die ("Invmap - Cannot Open Input File\n");}
unless (open(filemap,$ARGV[1])) {die ("Invmap - Cannot Open Input File\n");}
unless (open(fileout,">$ARGV[2]")) {die ("Invmap - Cannot Open Output File\n");}
@linesin=<filein>;
@maps=<filemap>;


for ($i=0;$i<@linesin;$i++) {
	$line=$linesin[$i];
	@grps=split(/\|/,$line);
	$numg=@grps;
	print fileout ("$grps[0]|");
	for ($j=1;$j<@grps-1;$j++){
		$gr=$grps[$j];
		@idxs=split(/\s/,$gr);
		for ($k=0;$k<@idxs;$k++){
			$stout=$maps[$idxs[$k]];
			$stout=~ tr/\n\r//d;
			print fileout ($stout);
			if ($k <@idxs -1){
				printf fileout (" ");
			}
		}
		print fileout ("|");
	}
	print fileout ("\n");
}
close(fileout);

print("Cluster Conversion Done\n");
