#!/usr/local/bin/perl


#Adaptation of PUZZLEBOOT (Holder, Roger, 1999) for Perl (for exercise only)

# PUZZLEBOOT - A simple utility for using PUZZLE with the PHYLIP suite of
#              programs in distance bootstrap analysis.
#


#tree-puzzle is a program that (among many other things)
#can reconstruct a distance matrix from sequence data

#problem: it works with one sequence alignment at a time, and we want to analyze 100 alignments
#(e.g. 100 bootstrap samples)


while(defined($file=glob("*.boot"))){

    open(IN,"<$file") or die "cannot open $file:$!";
    $header=<IN>;
    #close(IN);
    #open(IN,"<$file") or die "cannot open $file:$!";
    seek IN,-1,1; #move pointer of the file IN one line back(-1) from the current position, i.e. unread the line
    $/=$header;
    while(defined($line=<IN>)){
	$newfile="temp.seq";
	open (OUT,"> $newfile") or die "cannot open $newfile";
	print OUT $header; #print header
	print OUT $line; #print sequences
	close(OUT);
	
	$control_file="puzzle.cmds";
	open (OUT,"> $control_file") or die "cannot open $control_file";
	print OUT "$newfile\nk\nk\n\y\n"; #print filename
	close(OUT);
	system("puzzle < puzzle.cmds"); #execute puzzle
	$outfile=$file.".outdist";
	if(-e "outdist"){
	    system("cat outdist >> $outfile");
	    unlink "outdist";
	}
	
	if(-e "outfile"){
	    unlink "outfile";
	}
	if(-e "outtree"){
	    unlink "outtree";
	}
	if(-e $newfile){
	    unlink $newfile;
	}
	if(-e "puzzle.cmds"){
	    unlink "puzzle.cmds";
	}
	
	
    }
    $/="\n";   


}

###########################################################################################
#
# Home Work
#
#
# Improve your GenBank to FASTA conversion program to generate customized
# definition lines (the content of the definition line should be provided by user, e.g.
# GI number, organism, etc...)
#
###########################################################################################


