#!/usr/bin/perl -w  
use lib 'C:/Perl64/cpan/build/Tk-804.028_503';
use lib 'C:/Perl64/cpan/build/Tk-804.028_503';

use Tk;
use Cwd;
use Tk::DirSelect;
use Tk::ROText;
require Tk::Pane;

#################################################################################
#										#
#	Script name:	Bracket.pl						#
#	Author: 	Anneleen Van Geystelen					#
#	Version:	v1.0							#
#	Created:	18/06/2011						#
#	Last Modified:	02/03/2012						#
#										#
#	Description:	This Perl script is the Tk frame around the script	#
#			Bracket_batch.pl which can also be run without this GUI.#
#										#
# 	PERL MODULES:	Tk							#
#			Cwd							#
#			Tk::DirSelect						#
#			Tk::ROText						#
#			Tk::Pane						#
#										#
#################################################################################

#################################################################################
#				VARIABLES					#
#################################################################################

#################################################################################
#				END OF VARIABLES				#
#################################################################################

#################################################################################
#			 PERL SUBROUTINES					#
#################################################################################

# Change backslashes in forward slashes and forward slashes in backslashes depending on the system.
sub getPathRigth {
	my ($path) = @_;
	while ($path =~ m/\\/ ) {
		$path =~ s/\\/\//; 
	}
	return $path;
}

#################################################################################
#			END OF PERL SUBROUTINES 		  		#
#################################################################################

# Keep track of number of runs.
my $run = 0;

# Open main window. 
my $mw = new MainWindow;
$mw->geometry("1000x700+0+0");
$mw->title("Bracket");

# Create some space above first line. 
my $frm_name = $mw -> Frame(-pady => '15') -> pack();
$frm_name->Label(-text => "    ", -width => 15)->pack(-side => 'left');

# Create second line.
my $frm_name2 = $mw -> Frame( -pady => '15') -> pack();
$frm_name2->Label(-text => "Input Folder  ", -width => 25, -anchor=>'e')->pack(-side => 'left');
$frm_name2->Button( -text => "Select", -command => \&selectFolder2, -width => 15 )->pack(-side => 'right');
my $text2 = $frm_name2->Entry()->pack(-side => 'right');
$text2->configure(-background  => 'white',
		 -foreground  => 'black',
		 -width => 80);

# Create third line.
my $frm_name3 = $mw -> Frame() -> pack(-pady => '15'); #New Frame
$frm_name3->Label(-text => "Case Number  ", -width => 25, -anchor=>'e')->pack(-side => 'left');
$frm_name3->Label(-text => "", -width => 86)->pack(-side => 'right');
my $text3 = $frm_name3->Entry()->pack(-side => 'right');
$text3->configure(-background  => 'white',
		 -foreground  => 'black',
		 -width => 10);

# Create fourth line.
my $frm_name4 = $mw -> Frame() -> pack(-pady => '15'); #New Frame
$frm_name4->Label(-text => "Kit #1  ", -width => 25, -anchor=>'e')->pack(-side => 'left');
$frm_name4->Label(-text => "", -width => 86)->pack(-side => 'right');
my $text4 = $frm_name4->Entry()->pack(-side => 'right');
$text4->configure(-background  => 'white',
		 -foreground  => 'black',
		 -width => 10);

# Create fifth line.
my $frm_name5 = $mw -> Frame() -> pack(-pady => '15'); #New Frame
$frm_name5->Label(-text => "File Kit #1  ", -width => 25, -anchor=>'e')->pack(-side => 'left');
$frm_name5->Button( -text => "Select", -command => \&selectFile5, -width => 15 )->pack(-side => 'right');
my $text5 = $frm_name5->Entry()->pack(-side => 'right');
$text5->configure(-background  => 'white',
		 -foreground  => 'black',
		 -width => 80);

# Create sixth line.
my $frm_name6 = $mw -> Frame() -> pack(-pady => '15'); #New Frame
$frm_name6->Label(-text => "Kit #2  ", -width => 25, -anchor=>'e')->pack(-side => 'left');
$frm_name6->Label(-text => "", -width => 86)->pack(-side => 'right');
my $text6 = $frm_name6->Entry()->pack(-side => 'right');
$text6->configure(-background  => 'white',
		 -foreground  => 'black',
		 -width => 10);	

# Create seventh line.	 
my $frm_name7 = $mw -> Frame() -> pack(-pady => '15'); #New Frame
$frm_name7->Label(-text => "File Kit #2  ", -width => 25, -anchor=>'e')->pack(-side => 'left');
$frm_name7->Button( -text => "Select", -command => \&selectFile7, -width => 15 )->pack(-side => 'right');
my $text7 = $frm_name7->Entry()->pack(-side => 'right');
$text7->configure(-background  => 'white',
		 -foreground  => 'black',
		 -width => 80);

# Create eighth line. 		 
my $frm_name8 = $mw -> Frame() -> pack(-pady => '15'); #New Frame
$frm_name8->Label(-text => "Output Folder  ", -width => 25, -anchor=>'e')->pack(-side => 'left');
$frm_name8->Button( -text => "Select", -command => \&selectFolder8, -width => 15 )->pack(-side => 'right');
my $text8 = $frm_name8->Entry()->pack(-side => 'right');
$text8->configure(-background  => 'white',
		 -foreground  => 'black',
		 -width => 80);

# Create ninth line. 		 
my $frm_name80 = $mw -> Frame() -> pack(-pady => '15'); #New Frame
$frm_name80->Label(-text => "Thresholds Soft Brackets", -width => 25, -anchor=>'e')->pack(-side => 'left');
$frm_name80->Label( -width => 15 )->pack(-side => 'right');
my $text80 = $frm_name80->Entry(-text => "Use the \"Enter Thresholds\" button.")->pack(-side => 'right');
$text80->configure(-background  => 'white',
		 -foreground  => 'black',
		 -width => 80);

# Create row of buttons. 
my $frm_name9 = $mw -> Frame() -> pack(-pady => '15'); #New Frame		 
my $enterButton = $frm_name9->Button( 
		 -text => "Enter Thresholds", 
		 -command =>\&enter, 
		 -width => 25, 
		 -background=>"black", 
		 -activebackground => "white", 
		 -foreground  => 'white', 
		 -activeforeground => 'black', 
		 -height=>2)->pack(-side=>'left', -padx=> '40');
my $runButton = $frm_name9->Button( 
		 -text => "Run", 
		 -command =>\&run, 
		 -width => 25, 
		 -background=>"black", 
		 -activebackground => "white", 
		 -foreground  => 'white', 
		 -activeforeground => 'black', 
		 -disabledforeground => 'darkgrey', 
		 -height=>2)->pack(-side=>'left', -padx=> '40');	 
$frm_name9->Button( 
		 -text => "Exit", 
		 -command =>sub{exit}, 
		 -width => 25, 
		 -background=>"black", 
		 -activebackground => "white", 
		 -foreground  => 'white', 
		 -activeforeground => 'black', 
		 -height=>2)->pack(-side=>'left', -padx=> '40');

# Create output box. 
my $frm_name10 = $mw -> Frame() -> pack(-pady => '15'); #New Frame
$frm_name10->Label(-text => "", -width => 25, -anchor=>'e')->pack(-side => 'left');
$frm_name10->Label( -text => "", -width => 15 )->pack(-side => 'right');
my $text10 = $frm_name10->Scrolled('ROText', -scrollbars=>"oe") -> pack;
		 	 
MainLoop;

#################################################################################
#				 TK SUBROUTINES					#
#################################################################################

# Open window to select script file.
sub selectFile1 {
	my $file = $mw->getOpenFile();
	$file = getPathRigth($file);
	$text1->delete(0, 'end'); 
	$text1->insert("end", "$file"); 
}

# Open window to select input directory.
sub selectFolder2 {
	my $ds  = $mw->DirSelect();
	my $dir = $ds->Show();
	$dir = getPathRigth($dir);
	$text2->delete(0, 'end'); 
	$text2->insert("end", "$dir"); 	
}

# Open window to select input file for kit 1.
sub selectFile5 {
	my $file = $mw->getOpenFile();
	$file = getPathRigth($file);
	$text5->delete(0, 'end'); 
	$text5->insert("end", "$file"); 
}

# Open window to select input file for kit 2.
sub selectFile7 {
	my $file = $mw->getOpenFile();
	$file = getPathRigth($file);
	$text7->delete(0, 'end'); 
	$text7->insert("end", "$file"); 
}

# Open window to select output directory.
sub selectFolder8 {
	my $ds  = $mw->DirSelect();
	my $dir = $ds->Show();
	$dir = getPathRigth($dir);
	$text8->delete(0, 'end'); 
	$text8->insert("end", "$dir"); 	
}

# Replaces spaces in path of file or directory.
sub replaceSpacesInPath {
	my ($string) = @_;
	my $offset = length($string);
	my $result = rindex($string, " ", $offset);
	my @results;
	while ($result != -1) {
		push(@results, $result);
		$offset = $result - 1;
		$result = rindex($string, " ", $offset);
	}  

	foreach $result (@results) {
		$string = substr($string, 0, $result)."\\".substr($string, $result, length($string));
	}
	return $string;
}

# Run script.
sub enter {
	%markers;
	my $kit1File = $text5->get();
	my $kit2File = $text7->get();
	if ($kit1File ne '') {
		if (!(-e $kit1File)) {
			$text10->delete('1.0', 'end'); 
			$text10->insert('end', "Please give a valid path to file of kit #1.\n");
		} elsif (!(-e $kit2File) && $kit2File ne '') {
			$text10->delete('1.0', 'end'); 
			$text10->insert('end', "Please give a valid path to file of kit #2.\n");
		} else {
			open (KIT1, "< $kit1File");
			# Put all markers of kit #1 in hash. 
			while (<KIT1>) {
				my $line = $_; 
				chomp($line); 
				$line =~ s/\x{d}//;
				$markers{$line} = 0.5; 
			}
			close KIT1;
			# Put all markers of kit #2 in array. 
			if ($kit2File ne '') {
				open (KIT2, "< $kit2File");
				while (<KIT2>) {
					my $line = $_; 
					$line =~ s/\x{d}//;
					chomp($line); 
					$markers{$line} = 0.5; 
				}
				close KIT2;
			}
			# Create new window.
			$sw = new MainWindow;
			$sw->geometry("500x700+1050+0");
			$sw->title("Bracket: give thresholds per marker");
			# Create boxes for each of the markers.
			my $pane = $sw->Scrolled('Pane', Name => 'scroll test',
				       -width => 600,
				       -height => 400,
				       -scrollbars => 'osoe',
				       -sticky => 'ne',
				      );
			$pane->pack;
			foreach $marker (sort keys %markers) {
				${"frm".$marker} = $pane -> Frame(-pady => '15') -> pack();
				${"frm".$marker}->Label(-text => "$marker  ", -width => 15, -anchor=>'e')->pack(-side => 'left');
				${"frm".$marker}->Label(-text => "", -width =>40)->pack(-side => 'right');
				${"text".$marker} = ${"frm".$marker}->Entry(-text=>$markers{$marker})->pack(-side => 'right');
				${"text".$marker}->configure(-background  => 'white',
						 -foreground  => 'black',
						 -width => 10);
			}
			# Create file select box.
			my $frm0 = $sw -> Frame() -> pack(-pady => '15'); #New Frame	
			$frm0->Label(-text => "", -width =>10)->pack(-side => 'right');
			$frm0->Label(-text => "OR", -width => 15, -anchor=>'e')->pack(-side => 'left');
			$frm1 = $sw->Frame()->pack(-pady => '15'); #New Frame	
			$frm1->Label(-text => "File with thresholds ", -width => 15, -anchor=>'e')->pack(-side => 'left');
			$frm1->Button( -text => "Select", -command => \&selectFileParam, -width => 15 )->pack(-side => 'right');
			$text1a = $frm1->Entry(-text=>'')->pack(-side => 'right');
			$text1a->configure(-background  => 'white',
					 -foreground  => 'black',
					 -width => 80);

			$frmButton = $sw->Frame()->pack(-pady => '15'); #New Frame		 
			$enterButton = $frmButton->Button( 
					 -text => "Enter", 
					 -command =>\&pass, 
					 -width => 25, 
					 -background=>"black", 
					 -activebackground => "white", 
					 -foreground  => 'white', 
					 -activeforeground => 'black', 
					 -height=>2)->pack(-side=>'left', -padx=> '40');

			# Create output box. 
			$frmOut = $sw->Frame()-> pack(-pady => '15'); #New Frame
			$frmOut->Label(-text => "", -width => 25, -anchor=>'e')->pack(-side => 'left');
			$frmOut->Label( -text => "", -width => 15 )->pack(-side => 'right');
			$textOut = $frmOut->Scrolled('ROText', -scrollbars=>"oe") -> pack;
			
			
			sub selectFileParam {
				my $file = $sw->getOpenFile();
				$file = getPathRigth($file);
				$text1a->delete(0, 'end'); 
				$text1a->insert("end", "$file"); 
			}		
			
			sub pass {
				my $values;
				my @thresholds;
				$filename = $text1a->get();
				if ($filename eq '') {
					foreach $marker (sort keys %markers) {
						$value = ${"text".$marker}->get();
						$values = $values."$marker $value ";
						push(@thresholds, $value);
					}
				} else {
					open (FILE, "< $filename");
					while (<FILE>) {
						my $line = $_; 
						chomp($line);
						($marker, $value) = split(/\t/,$line); 
						$values = $values."$marker $value ";
						push(@thresholds, $value);
					}
					close FILE;
				}
				if (testThresholds(@thresholds) eq 0) {
					# Print comment in box.
					if ($textOut->get('1.0', 'end') eq "\n") {
						$textOut->insert("end", "Please give thresholds between 0  and 1 for each marker.\n");
					}
				} else {
					# Print values in box.
					$text80->delete('0', 'end');
					while ($values =~ /\x{d}/) {
						$values =~ s/\x{d}//;
					}
					$text80->insert("end", "$values");
					$textOut->insert("end","OK.\n");
					$sw->destroy;
				}
			}
		}
	} else {
		# Print comment in box.
		$text10->delete('1.0', 'end'); 
		$text10->insert("end", "Please give valid paths to files of the kits.\n");
	}

}

# Run script.
sub run {
	$run++;
	my $dir = getcwd;
	my $script = $dir."/Bracket_batch.pl";
	# my $arg0 = "\'".getPathRigth($script)."\'";
	my $arg0 = getPathRigth($script);
	my $arg1 = $text2->get();
	$arg1 = replaceSpacesInPath($arg1);

	my $arg2 = $text3->get();
	my $arg3 = $text4->get();
	my $arg4 = $text5->get();
	$arg4 = replaceSpacesInPath($arg4);

	my $arg5 = $text6->get();
	my $arg6 = $text7->get();
	$arg6 = replaceSpacesInPath($arg6);
	my $arg7 = $text8->get();
	$arg7 = replaceSpacesInPath($arg7);

	my $arg8 = $text80->get();
	my @arg8 = split(/ /, $arg8);
	$text10->delete('1.0', 'end'); 
	$runButton->configure(-state => 'disabled');
	if ($arg5 eq '') {$arg5 = '-'}
	if ($arg6 eq '') {$arg6 = '-'}
	if ($arg1 ne '' && $arg2 ne '' && $arg3 ne '' && $arg4 ne '' && $arg5 ne '' && $arg6 ne '' && $arg7 ne '' && $arg8 ne '') {
		$text10->insert("end", "Run $run\nProgram started\n");
		my @results = `perl $arg0 $arg1 $arg2 $arg3 $arg4 $arg5 $arg6 $arg7 @arg8`;
		if (@results ne "") {
			$text10->insert("end", "\n\t@results\n");
		} 
		$text10->insert("end", "Program ended\n");
	} else {
		$text10->insert("end", "Run $run\n\n\tPlease fill in all fields.\n");
	}
	$runButton->configure(-state => 'normal');
}

sub testThresholds {
    my @list = @_;
    my $ret = 1;
    foreach $threshold (@list) {
    	if ($threshold eq '' || $threshold < 0 || $threshold > 1) {
    		$ret = 0;
    	}
    }
    return $ret;
}