#!/usr/local/bin/perl5.004
# Contact: dn1

  ####    ####   #    #  #####    ####   ######
 #       #    #  #    #  #    #  #    #  #
  ####   #    #  #    #  #    #  #       #####
      #  #    #  #    #  #####   #       #
 #    #  #    #  #    #  #   #   #    #  #
  ####    ####    ####   #    #   ####   ######


 #####   #         ##     #####  ######
 #    #  #        #  #      #    #
 #    #  #       #    #     #    #####
 #####   #       ######     #    #
 #       #       #    #     #    #
 #       ######  #    #     #    ######

# An interface to allow user entry of source_plates into the system
# Author dn1g (dpv, dn1)

#BEGIN {
#    print STDERR "Using !LOCAL! version of pt2_sourceplate.pl \n";
#    print STDERR "Connecting to development database \n";
#};

use Tk;
use strict;
use WrapDBI;
use WaitBox;

use sql_engine;

use Checkbarcode;
use Data::Dumper;

# Does this work ok with the new version of Barcode* ?
use BarcodeRevised;
use NewBrowseEntry;

# need to move this requirement over to pt2_general.pm
use platetrack_general;
# used in id_person2email id_person2id_role package covert sub go_who

require 'badgerGetOpt.pl';
require Tk::Dialog;

$| = 1;

my $prog = 'pt2_sourceplate_aug28';
$ENV{'DISPLAY'} || die "$prog: \$DISPLAY environment variable not set, Please set via 'ncd' or 'dis' command.\n";



################
# Set the fonts
################
my $title_f = "-adobe-helvetica-bold-r-normal--24-240-75-75-p-138-iso8859-1";
my $entry_f = "-adobe-helvetica-medium-r-normal--17-120-100-100-p-88-iso8859-1";
my $button_f = "-adobe-helvetica-bold-r-normal--17-120-100-100-p-92-iso8859-1";
my $label_f = "-adobe-helvetica-bold-r-normal--14-100-100-100-p-82-iso8859-1";



#########################
# Init. some global vars
#########################
my $barcode_entry = "pale green";
my $stage; # Controls where the interface has got to
my ($who, $who_team, $session);
my ($email, $vector_ref, $sourceplatetype, $remark, $rem_var, $rem, $remt, $zero, $h, $zero_var, $zero_t, $add, $addt, $l, $library_var, $library, $libraryt, $e,$format, $format_var, $formatt, $Organise, $Name, $Fromt, $sourcetype, $sourcetypet, $sourcetype_var, $organ, $organt, $org_var, $To, $to, $tott, $to_var, $roott, $root, $root_var, $fromt, $from, $from_var,$ligation_var,$ligation,$lig,$ligationt, $preps);
$from_var = 1; # Default starting value for platenames



######################
# Database connection
######################

my $db1 = 'platetrack';
#my $db1 = 'trackingclone_apr2002';

my $STATEMENTS = statements->new("$db1");



my $dbh1 = $STATEMENTS->{DBH};
# Specify use of a local version of the sql-lib

#$STATEMENTS->default_sql_lib_path('./'); 
$STATEMENTS->load_sql_lib(["Platetrack2.sql_lib::all"]);



################
# Printer setup
################
my $printer = Barcode->new($STATEMENTS->{DBH});
$printer->Type("SO");


##################
# Make the window
##################
my $mainWindow = MainWindow->new;
$mainWindow-> configure(cursor  => 'hand2');
$mainWindow->wm('minsize', 900, 530); 
$mainWindow->wm('maxsize', 900, 530);
my $f = $mainWindow->Frame(-height => 530, -width => 900);
$f->pack();
$mainWindow->idletasks();
$mainWindow->packPropagate(0);
$f->packForget();




#####################################
# Setup some binds on the mainwindow
#####################################
$mainWindow->bind('<KeyPress-Tab>', sub{Tk::break;} );

$mainWindow->bind('<Alt-Key-r>' => sub { 
    &reset_int;
});
sub reset_int {
    &update("Reseting interface.");
    $stage = 'reset';
    &start_process();
}


$mainWindow->bind('<Alt-Key-c>' => sub { 
    &clear_int;
});
sub clear_int {
    &update("Clearing interface.");
    $stage = 'clear';
    &start_process();
}


$mainWindow->bind('<Alt-Key-p>' => sub {
    &print_int;
});
sub print_int {
    $printer->Viewprinters();
}


$mainWindow->bind('<Alt-Key-s>' => sub {
    &sub_int;
});


$mainWindow->bind('<Alt-Key-q>' => sub {
    &quit_int;
});
sub quit_int {
    exit;
}


#################
# Make a waitbox
#################
my $utxt = "Initializing...";
my $wd = $mainWindow->WaitBox(-title => 'Please wait...');	
$wd->wm('minsize', 120, 30);
$wd->wm('maxsize', 120, 30);
my $f = $wd->Frame(-height => 30, -width => 120);
$f->pack();
$mainWindow->idletasks();
$wd->packPropagate(0);
$wd->idletasks();
$f->packForget();





####################
# Setup some frames
####################
my $title_frame = $mainWindow->Frame();
$title_frame->pack(-side => 'top');

my $title_frame2 = $mainWindow->Frame();
$title_frame2->pack(-side => 'top');

$title_frame->Label(font => $title_f,
		    text => '  User:')->pack(-side => 'left');
my $user_label = $title_frame->Entry(-width => 5,
				     -font => $button_f,
				     -textvariable => \$who,)->pack(side => 'top');
$user_label->pack(-side => 'left');

$title_frame->Label(font => $title_f,
		    text => '  Working for team:')->pack(-side => 'left');
my $team_label = $title_frame->Entry(-state => 'disabled',
				     -width => 5,
				     -font => $button_f,
				     -textvariable => \$who_team,)->pack(side => 'top');
$team_label->pack(-side => 'left');


#############################################
# What is the current barcode_printer ? 
#############################################
$title_frame->Label(font => $title_f,
		    text => 'Barcode Printer:')->pack(-side => 'left');
my $sel_printer = $title_frame->Entry(
				      -state => 'disabled',
				      -width => 15,
				      -font => $button_f,
				      -textvariable => \$printer->{'Printer'}
)->pack(side => 'top');
$sel_printer->pack(-side => 'left');



my $action;
$title_frame2->Label(font => $title_f,
		     text => '  Action:')->pack(-side => 'left');
my $action_label = $title_frame2->Entry(-state => 'disabled',
					-width => 40,
					-font => $title_f,
					-bg => $barcode_entry,
					-textvariable => \$action,)->pack(side => 'top');
$action_label->pack(-side => 'left');


my $menuBar1 = $mainWindow->Frame();
$menuBar1->pack(side => 'top', fill => 'x');

my $frame_update = $mainWindow->Frame();
$frame_update->pack(-side => 'top', -fill => 'x');
my $update_screen = $frame_update->ScrlListbox (-bg => 'white',
						-scrollbars => 'e',
						-font => $button_f,
						-label => "Update",
						-height => 3,
						-width => 30);
$update_screen->pack(-side => 'left', -expand => 1, -fill => 'both');
&update("Welcome to Platetrack -> Sourceplate generation section.");

my $main_frame = $mainWindow->Frame(-borderwidth => '6');
$main_frame->pack(-side => 'top', -expand => 'no', -fill => 'x');

my $button_frame = $main_frame->Frame();
$button_frame->pack(-side => 'bottom', 
		    -expand => 'no', 
		    -fill => 'x',
		    ipady => 5,
		    ipadx => 5);

my $main_frame_top = $main_frame->Frame();
$main_frame_top->pack(-side => 'top', 
		      ipady => 20,);

my $main_frame_bottom = $main_frame->Frame();
$main_frame_bottom->pack(-side => 'bottom');

my $main_frame_bottom_1 = $main_frame_bottom->Frame();
$main_frame_bottom_1->pack(-side => 'top');

my $main_frame_bottom_2 = $main_frame_bottom->Frame();
$main_frame_bottom_2->pack(-side => 'top');

my $frame_left = $main_frame_top->Frame();
$frame_left->pack(-side => 'left');
my $frame_right = $main_frame_top->Frame();
$frame_right->pack(-side => 'right');






#####################
# Setup some buttons
#####################
my $quit_button = $button_frame->Button(-font => $button_f,
					-text => "Quit <Alt-q>",
					-command => \&quit_int);
$quit_button->pack(-side => 'left');

my $reset_button = $button_frame->Button(-font => $button_f,
					 -text => "Reset <Alt-r>",
					 -command => \&reset_int);
$reset_button->pack(-side => 'left');

my $clear_button = $button_frame->Button(-font => $button_f,
					 -text => "Clear <Alt-c>",
					 -command => \&clear_int);
$clear_button->pack(-side => 'left');

my $printer_button = $button_frame->Button(-font => $button_f,
					   -text => "Printer <Alt-p>",
					   -command => \&print_int);
$printer_button->pack(-side => 'left');

my $submit_button = $button_frame->Button(-font => $button_f,
					  -text => "Submit <Alt-s>",
					  -command => \&sub_int);
$submit_button->pack(-side => 'right');


&setup_entry_fields();


####################################
# Load some pull-downs with options
####################################
&organisation();
&library_name();
&sourceplate_type();

# Do not activate 96 format until the code has been tested
#foreach my $pf ('96','384'){

# 96 well activated
foreach my $pf ('384', '96'){
    $format->insert('end', $pf);
    $format_var = $pf;  
}
foreach my $h ('no','Yes'){
    $zero->insert('end', $h);
    $zero_var = $h;  
}


print STDOUT "pt2_sourceplate.pl started...\n";


#########################
# Start the ball rolling
#########################
$stage = 'who';
&start_process();

MainLoop();





##############
# Subroutines
##############
sub update_clear {
    $update_screen->delete ('0', 'end');
    &update("Window cleared.");
}


sub update {
    my (@update_contents)=@_;
    $update_screen->insert('end', @update_contents);
    $update_screen->see('end'); 
    $update_screen->update('idletasks');
}


sub setup_entry_fields {

    $sourceplatetype = 'Sourceplate type';
    $sourcetypet = $frame_left->Entry(-state => 'disabled',
				     -width => 20,
				     -font => $button_f,
				     -textvariable => \$sourceplatetype,)->pack(side => 'top');
    $sourcetypet->pack(-side => 'top');
    $sourcetype = $frame_right->BrowseEntry(-width => 38,
					  -font => $entry_f,
					  -textvariable => \$sourcetype_var,
					  -state => 'readonly')->pack(side => 'top');


    $Organise = 'Organisation';
    $organt = $frame_left->Entry(-state => 'disabled',
				-width => 20,
				-font => $button_f,
				-textvariable => \$Organise,)->pack(side => 'top');
    $organt->pack(-side => 'top');
    $organ = $frame_right->BrowseEntry(-width => 38,
				       -font => $entry_f,
				       -textvariable => \$org_var,
				       -state => 'readonly')->pack(side => 'top');

    
    $Name = 'Base name';
    $roott = $frame_left->Entry(-state => 'disabled',
				-width => 20,
				-font => $button_f,
				-textvariable => \$Name,)->pack(side => 'top');
    $roott->pack(-side => 'top');
    $root = $frame_right->Entry(-width => 40,
				-font => $entry_f,
				-textvariable => \$root_var,)->pack(side => 'top');



    $Fromt = 'From';
    $fromt = $frame_left->Entry(-state => 'disabled',
				-width => 20,
				-font => $button_f,
				-textvariable => \$Fromt,)->pack(side => 'top');
    $fromt->pack(-side => 'top');
    $from = $frame_right->Entry(-width => 40,
				-font => $entry_f,
				-textvariable => \$from_var,)->pack(side => 'top');



    $To = 'To';
    $tott = $frame_left->Entry(-state => 'disabled',
			       -width => 20,
			       -font => $button_f,
			       -textvariable => \$To,)->pack(side => 'top');
    $tott->pack(-side => 'top');
    $to = $frame_right->Entry(-width => 40,
			      -font => $entry_f,
			      -textvariable => \$to_var,)->pack(side => 'top');
    $ligation = 'Fake ligation number';
    $ligationt = $frame_left->Entry(-state => 'disabled',
				     -width => 20,
				     -font => $button_f,
				     -textvariable => \$ligation,)->pack(side => 'top');
    $ligationt->pack(-side => 'top');
    $lig = $frame_right->Entry(-width => 40,
			       -font => $entry_f,
			       -textvariable => \$ligation_var)->pack(side => 'top');



    $e = 'Plate format';
    $formatt = $frame_left->Entry(-state => 'disabled',
				   -width => 20,
				   -font => $button_f,
				   -textvariable => \$e,)->pack(side => 'top');
    $formatt->pack(-side => 'top');
    $format = $frame_right->BrowseEntry(-width => 38,
					-font => $entry_f,
					-state => 'readonly',
					-textvariable => \$format_var,)->pack(side => 'top');



    $l = 'library name';
    $libraryt = $frame_left->Entry(-state => 'disabled',
				    -width => 20,
				    -font => $button_f,
				    -textvariable => \$l,)->pack(side => 'top');
    $libraryt->pack(-side => 'top');
    $library = $frame_right->BrowseEntry(-width => 38,
					 -font => $entry_f,
					 -state => 'readonly',
					 -textvariable => \$library_var,)->pack(side => 'top');

    
    $add = 'Add zero';
    $addt = $frame_left->Entry(-state => 'disabled',
				-width => 20,
				-font => $button_f,
				-textvariable => \$add,)->pack(side => 'top');
    $addt->pack(-side => 'top');
    $zero = $frame_right->BrowseEntry(-width => 38,
				      -font => $entry_f,
				      -state => 'readonly',
				      -textvariable => \$zero_var,)->pack(side => 'top');
    

    $rem = 'Remark';
    $remt = $frame_left->Entry(-state => 'disabled',
				-width => 20,
				-font => $button_f,
				-textvariable => \$rem,)->pack(side => 'top');
    $remt->pack(-side => 'top');
    $remark = $frame_right->Entry(-width => 40,
				  -font => $entry_f,
				  -textvariable => \$rem_var)->pack(side => 'top');
}




sub start_process {


    if ($stage eq 'clear'){
        ($sourcetype_var, $org_var, $root_var, $to_var, $library_var, $rem_var, $ligation_var) = '';
	
        $from_var = '1';
	$format_var = '384';
	$zero_var = 'Yes';

	$mainWindow->bind ('<Return>' => sub {});
	
	$sourcetype->grabRelease();
	$organ->grabRelease();
	$root->grabRelease();
	$from->grabRelease();
        $lig->grabRelease();
	$to->grabRelease();
        $format->grabRelease();
	$library->grabRelease();
	$zero->grabRelease();
	$remark->grabRelease();

	$sourcetype->bind ('<Return>' => sub {});
	$organ->bind ('<Return>' => sub {});
	$to->bind ('<Return>' => sub {});
        $from->bind ('<Return>' => sub {});
	$root->bind ('<Return>' => sub {});
	$lig->bind ('<Return>' => sub {});
        $format->bind ('<Return>' => sub {});
        $library->bind ('<Return>' => sub {});
        $zero->bind ('<Return>' => sub {});
        $remark->bind ('<Return>' => sub {});

	$sourcetype->configure(-bg => 'grey85');
	$organ->configure(-bg => 'grey85');
	$root->configure(-bg => 'grey85');
	$from->configure(-bg => 'grey85');
	$to->configure(-bg => 'grey85');
        $lig->configure(-bg => 'grey85');
	$format->configure(-bg => 'grey85');
	$library->configure(-bg => 'grey85');
	$zero->configure(-bg => 'grey85');
	$remark->configure(-bg => 'grey85');
	
	$sourcetype->configure(-state => 'readonly');
	$organ->configure(-state => 'readonly');
	$root->configure(-state => 'normal');
	$from->configure(-state => 'normal');
        $lig->configure(-state => 'normal'); 
	$to->configure(-state => 'normal');
	$format->configure(-state => 'readonly');
	$library->configure(-state => 'readonly');
	$zero->configure(-state => 'readonly');
	$remark->configure(-state => 'normal');

	$sourcetype->Subwidget("entry")->configure(-bg => 'grey85');
	$sourcetype->Subwidget("arrow")->configure(-bg => 'grey85');
	$sourcetype->Subwidget("entry")->Subwidget("entry")->configure(-bg => 'grey85');
	$sourcetype->Subwidget("slistbox")->Subwidget("listbox")->configure(-bg => 'grey85');

        $organ->Subwidget("entry")->configure(-bg => 'grey85');
	$organ->Subwidget("arrow")->configure(-bg => 'grey85');
	$organ->Subwidget("entry")->Subwidget("entry")->configure(-bg => 'grey85');
	$organ->Subwidget("slistbox")->Subwidget("listbox")->configure(-bg => 'grey85');

	$format->Subwidget("entry")->configure(-bg => 'grey85');
	$format->Subwidget("arrow")->configure(-bg => 'grey85');
	$format->Subwidget("entry")->Subwidget("entry")->configure(-bg => 'grey85');
	$format->Subwidget("slistbox")->Subwidget("listbox")->configure(-bg => 'grey85');

	$library->Subwidget("entry")->configure(-bg => 'grey85');
	$library->Subwidget("arrow")->configure(-bg => 'grey85');
	$library->Subwidget("entry")->Subwidget("entry")->configure(-bg => 'grey85');
	$library->Subwidget("slistbox")->Subwidget("listbox")->configure(-bg => 'grey85');

	$zero->Subwidget("entry")->configure(-bg => 'grey85');
	$zero->Subwidget("arrow")->configure(-bg => 'grey85');
	$zero->Subwidget("entry")->Subwidget("entry")->configure(-bg => 'grey85');
	$zero->Subwidget("slistbox")->Subwidget("listbox")->configure(-bg => 'grey85');

        $action_label->configure(-bg => $barcode_entry);
	
	$stage = 'type';
	&start_process;
    }



    if ($stage eq 'reset'){
	($who, $who_team, $session, $sourcetype_var, $org_var, $to_var, $root_var, $library_var, $rem_var, $ligation_var) = '';

	$from_var = '1';
	$format_var = '384';
	$zero_var = 'Yes';
	
	$mainWindow->bind ('<Return>' => sub {});
	
	$user_label->configure(-state => 'normal');

	$sourcetype->grabRelease();
	$organ->grabRelease();
	$root->grabRelease();
	$from->grabRelease();
	$to->grabRelease();
        $lig->grabRelease();
        $format->grabRelease();
	$library->grabRelease();
	$zero->grabRelease();
	$remark->grabRelease();

	$user_label->bind ('<Return>' => sub {});
	$sourcetype->bind ('<Return>' => sub {});
	$organ->bind ('<Return>' => sub {});
	$root->bind ('<Return>' => sub {});
	$from->bind ('<Return>' => sub {});
	$to->bind ('<Return>' => sub {});
        $format->bind ('<Return>' => sub {});
        $library->bind ('<Return>' => sub {});
        $zero->bind ('<Return>' => sub {});
        $remark->bind ('<Return>' => sub {});
	$lig->bind ('<Return>' => sub {});

        $sourcetype->configure(-bg => 'grey85');
	$organ->configure(-bg => 'grey85');
	$root->configure(-bg => 'grey85');
	$from->configure(-bg => 'grey85');
	$to->configure(-bg => 'grey85');
	$format->configure(-bg => 'grey85');
	$library->configure(-bg => 'grey85');
	$zero->configure(-bg => 'grey85');
	$remark->configure(-bg => 'grey85');
	$lig->configure(-bg => 'grey85');

	$sourcetype->configure(-state => 'readonly');
	$organ->configure(-state => 'readonly');
	$root->configure(-state => 'normal');
	$from->configure(-state => 'normal');
	$to->configure(-state => 'normal');
	$format->configure(-state => 'readonly');
	$library->configure(-state => 'readonly');
	$zero->configure(-state => 'readonly');
	$remark->configure(-state => 'normal');
        $lig->configure(-state => 'normal');

	$sourcetype->Subwidget("entry")->configure(-bg => 'grey85');
	$sourcetype->Subwidget("arrow")->configure(-bg => 'grey85');
	$sourcetype->Subwidget("entry")->Subwidget("entry")->configure(-bg => 'grey85');
	$sourcetype->Subwidget("slistbox")->Subwidget("listbox")->configure(-bg => 'grey85');

        $organ->Subwidget("entry")->configure(-bg => 'grey85');
	$organ->Subwidget("arrow")->configure(-bg => 'grey85');
	$organ->Subwidget("entry")->Subwidget("entry")->configure(-bg => 'grey85');
	$organ->Subwidget("slistbox")->Subwidget("listbox")->configure(-bg => 'grey85');

	$format->Subwidget("entry")->configure(-bg => 'grey85');
	$format->Subwidget("arrow")->configure(-bg => 'grey85');
	$format->Subwidget("entry")->Subwidget("entry")->configure(-bg => 'grey85');
	$format->Subwidget("slistbox")->Subwidget("listbox")->configure(-bg => 'grey85');

	$library->Subwidget("entry")->configure(-bg => 'grey85');
	$library->Subwidget("arrow")->configure(-bg => 'grey85');
	$library->Subwidget("entry")->Subwidget("entry")->configure(-bg => 'grey85');
	$library->Subwidget("slistbox")->Subwidget("listbox")->configure(-bg => 'grey85');

	$zero->Subwidget("entry")->configure(-bg => 'grey85');
	$zero->Subwidget("arrow")->configure(-bg => 'grey85');
	$zero->Subwidget("entry")->Subwidget("entry")->configure(-bg => 'grey85');
	$zero->Subwidget("slistbox")->Subwidget("listbox")->configure(-bg => 'grey85');

        $action_label->configure(-bg => $barcode_entry);
	
        $stage = 'who';
	&start_process;
    }



    if ($stage eq 'who'){ 
	&go_who;
    }


    if ($stage eq 'type'){
	$user_label->configure(-state => 'disabled');
	&go_type;
    }


    if ($stage eq 'organisation'){
	&go_organ;
    }


    if ($stage eq 'ligation'){
	&go_lig;
    }


    if ($stage eq 'base_name'){
	&go_base;
    }


    if ($stage eq 'from'){
	&go_from;
    }


    if ($stage eq 'to'){
	&go_to;
    }

    
    if ($stage eq 'format'){
	&go_format;
    }


    if ($stage eq 'library'){
	&go_library;
    }

    
    if ($stage eq 'zero'){
	&go_add_zero;
    }


    if ($stage eq 'remark'){
	&go_remark;
    }
}


sub go_who {
    $action = "Identify yourself via your personal barcode.";
    
    $user_label->configure(-bg => $barcode_entry);
    $user_label->focusForce();
    $user_label->grab();
    $user_label->bind ('<Return>' => sub { 
	$wd->Show;
	my $hash_return = Verifynumber("$who", "ID");
	if ($hash_return->{Process} eq 'Good'){
	    
	    my $email_a = $STATEMENTS->get('Platetrack2.sql_lib::get_person' , [$hash_return->{Number}]);
	    my $email = $email_a->[0][0];
	    
	    my $id_role;
	    $user_label->grabRelease();
	    ($id_role, $who_team) = convert->id_person2id_role($STATEMENTS->{DBH}, $hash_return->{Number}, $mainWindow );
	    
	    if ($email eq ''){
		&update("There is no current person.id_person entry of $hash_return->{Number} in the database. CONTACT BUG.");
		$stage = 'who';
		$who = '';
		$who_team = '';
		$session = '';
	    }

	    if ($id_role eq 'Not a shotgun person'){
		&update("You are not registered to use this software. CONTACT BUG.");
		$stage = 'who';
		$who = '';
		$who_team = '';
		$session = '';
	    }
	    
	    if ($email ne 'Not a person' && $id_role ne 'Not a shotgun person'){
		&update("User authorised.");
		$stage = 'type';
		$who = $email;
		$printer->User("$who");
	    }

	} else {
	    $stage = 'who';
	    $who = '';
	    $who_team = '';
	    $session = '';
	}
	
	$user_label->configure(-bg => 'grey85');
	$wd->unShow;
	&start_process();
    } ); 
}


sub go_type {
    $action = "Specify a sourceplate type.";
          
    $lig->configure(-state => 'disabled');
    $organ->configure(-state => 'disabled');
    $root->configure(-state => 'disabled');
    $from->configure(-state => 'disabled');
    $to->configure(-state => 'disabled');
    $format->configure(-state => 'disabled');
    $library->configure(-state => 'disabled');
    $zero->configure(-state => 'disabled');
    $remark->configure(-state => 'disabled');           
    
    $user_label->bind ('<Return>' => sub {});
    
    $mainWindow->focusForce();
    
    $sourcetype->Subwidget("arrow")->configure(-bg => $barcode_entry);
    $sourcetype->Subwidget("entry")->Subwidget("entry")->configure(-bg => $barcode_entry);
    $sourcetype->Subwidget("slistbox")->Subwidget("listbox")->configure(-bg => $barcode_entry);
    
    $mainWindow->bind ('<Return>' => sub { 
	if ( $sourcetype_var eq '') {
	    $stage = 'type';
	} else {
	    $stage = 'organisation';
	    $organ->configure(-state => 'readonly');
	    $sourcetype->Subwidget("arrow")->configure(-bg    => 'grey85', -state => 'disabled');
	    $sourcetype->Subwidget("entry")->Subwidget("entry")->configure(-bg => 'grey85');
	    $sourcetype->Subwidget("slistbox")->Subwidget("listbox")->configure(-bg => 'grey85');
	}
	&start_process();
    }); 
}
 
     
sub go_organ {
    $action = "Specify a sourceplate type.";
    
    $lig->configure(-state => 'disabled');
    $sourcetype->configure(-state => 'disabled');
    $root->configure(-state => 'disabled');
    $from->configure(-state => 'disabled');
    $to->configure(-state => 'disabled');
    $format->configure(-state => 'disabled');
    $library->configure(-state => 'disabled');
    $zero->configure(-state => 'disabled');
    $remark->configure(-state => 'disabled');
    
    $user_label->bind ('<Return>' => sub {});
    
    $mainWindow->focusForce();
    
    $organ->Subwidget("arrow")->configure(-bg => $barcode_entry);
    $organ->Subwidget("entry")->Subwidget("entry")->configure(-bg => $barcode_entry);
    $organ->Subwidget("slistbox")->Subwidget("listbox")->configure(-bg => $barcode_entry);
    
    $mainWindow->bind ('<Return>' => sub { 
	if ( $org_var eq '') {
	    $stage = 'organ';
	} else {
	    $stage = 'base_name';
	    $root->configure(-state => 'normal');
	    $organ->configure(-state => 'disabled');
	    $organ->Subwidget("arrow")->configure(-bg    => 'grey85', -state => 'disabled');
	    $organ->Subwidget("entry")->Subwidget("entry")->configure(-bg => 'grey85');
	    $organ->Subwidget("slistbox")->Subwidget("listbox")->configure(-bg => 'grey85');
	    $mainWindow->bind ('<Return>' => sub {});
	}
	&start_process();
    }); 
}


sub go_base {
    $action = "Supply a root for the platenames (if needed)";
    
    $lig->configure(-state => 'disabled');        
    $sourcetype->configure(-state => 'disabled');
    $organ->configure(-state => 'disabled');
    $from->configure(-state => 'disabled');
    $to->configure(-state => 'disabled');
    $format->configure(-state => 'disabled');
    $library->configure(-state => 'disabled');
    $zero->configure(-state => 'disabled');
    $remark->configure(-state => 'disabled');
    
    $root->focusForce();
    $root->configure(-bg => $barcode_entry);
    $root->grab();
    $root->bind ('<Return>' => sub {
	if ( $root_var =~ /(^\w+$|^\w+-?$)/ ) {
	    if  ($root_var eq '') {
		$stage = 'base_name';
	    } else {
		$stage = 'from';
		$from->configure(-state => 'normal');
		$root->configure(-bg => 'grey85');
		$root->grabRelease();
	    }
	    &start_process();
	}
   });
}	

    
sub go_from {
    $action = "Platenumber from";
	    
    $lig->configure(-state => 'disabled');
    $sourcetype->configure(-state => 'disabled');
    $organ->configure(-state => 'disabled');
    $root->configure(-state => 'disabled');
    $to->configure(-state => 'disabled');
    $format->configure(-state => 'disabled');
    $library->configure(-state => 'disabled');
    $zero->configure(-state => 'disabled');
    $remark->configure(-state => 'disabled');

    $from->focusForce();
    $from->configure(-bg => $barcode_entry);
    $from->grab();
    $from->bind ('<Return>' => sub { 
	unless ( ($from_var =~ /(^\d+$)/) && ($from_var > 0) ){
	    $stage = 'from';
	    $from->configure(-state => 'normal');
	    &update("You must enter a valid Platenumber\n");
	} else {
	    $stage = 'to';
	    $to->configure(-state => 'normal');
	    $from->configure(-bg => 'grey85');
	    $from->grabRelease();
	}
	&start_process();
   }); 
}


sub go_to {
    $action = "Platenumber to";
    
    $lig->configure(-state => 'disabled');
    $sourcetype->configure(-state => 'disabled');
    $organ->configure(-state => 'disabled');
    $root->configure(-state => 'disabled');
    $from->configure(-state => 'disabled');
    $format->configure(-state => 'disabled');
    $library->configure(-state => 'disabled');
    $zero->configure(-state => 'disabled');
    $remark->configure(-state => 'disabled');
    
    $to->focusForce();
    $to->configure(-bg => $barcode_entry);
    $to->grab();
    $to->bind ('<Return>' => sub { 
	if ( ($to_var =~ /(^\d+$)/) || ($to_var eq '') ){
	    
	    if  ( ($to_var eq '') || ($to_var < $from_var) ) {
		$stage = 'to';
		$to->configure(-state => 'normal');
		&update("You must enter a valid Platenumber\n");
	    } else {
		$stage = 'ligation';
		$lig->configure(-state => 'normal');
		$to->configure(-bg => 'grey85');
		$to->grabRelease();
	    }
	    &start_process();
	}
    });
}



sub go_lig {
    $action = "Enter a ligation number";
    
    $sourcetype->configure(-state => 'disabled');
    $organ->configure(-state => 'disabled');
    $root->configure(-state => 'disabled');
    $from->configure(-state => 'disabled');
    $format->configure(-state => 'disabled');
    $library->configure(-state => 'disabled');
    $zero->configure(-state => 'disabled');
    $remark->configure(-state => 'disabled');

    $lig->focusForce();
    $lig->configure(-bg => $barcode_entry);
    $lig->grab(); 

    $lig->bind ('<Return>' => sub { 
	my ($lig_test, $lib_test);


	if ($ligation_var =~ /(^\d+$)/) {

	    
	    &update("Checking ligation $ligation_var is valid...\n");
	    my $ligation_id = $STATEMENTS->get('Platetrack2.sql_lib::get_ligation_type', [$ligation_var]);


	    $lig_test = $ligation_id->[0][0];
	    $lib_test = $ligation_id->[0][1];
	}
 

	if (($ligation_var eq '') || ($lig_test eq '') || ($lib_test eq '')) {
	    $stage = 'ligation';
	    $lig->configure(-state => 'normal');
	    &update("You must enter a valid ligation number ? $ligation_var ?\n");
	} else {

	    $library_var = $lib_test;
		
	    $stage = 'format';
	    $format->configure(-state => 'readonly');
	    $lig->configure(-bg => 'grey85');
	    $lig->grabRelease();
	}
	&start_process();
    });
}



sub go_format {
    $action = "Specify a sourceplate format.";

    $lig->configure(-state => 'disabled');
    $sourcetype->configure(-state => 'disabled');
    $root->configure(-state => 'disabled');
    $from->configure(-state => 'disabled');
    $to->configure(-state => 'disabled');
    $organ->configure(-state => 'disabled');
    $library->configure(-state => 'disabled');
    $zero->configure(-state => 'disabled');
    $remark->configure(-state => 'disabled');
    
    $user_label->bind ('<Return>' => sub {});
    
    $mainWindow->focusForce();

    $format->Subwidget("arrow")->configure(-bg => $barcode_entry);
    $format->Subwidget("entry")->Subwidget("entry")->configure(-bg => $barcode_entry);
    $format->Subwidget("slistbox")->Subwidget("listbox")->configure(-bg => $barcode_entry);
    
    $mainWindow->bind ('<Return>' => sub {
	$zero->configure(-state => 'readonly');
	$mainWindow->bind ('<Return>' => sub {});
	
	
	$stage = 'zero';
	
	$format->Subwidget("arrow")->configure(-bg    => 'grey85',
					       -state => 'disabled');
	$format->Subwidget("entry")->Subwidget("entry")->configure(-bg => 'grey85');
	$format->Subwidget("slistbox")->Subwidget("listbox")->configure(-bg => 'grey85');
	&start_process();
    }); 
}



sub go_library {
    $action = "Specify a library source.";

    $lig->configure(-state => 'disabled');
    $organ->configure(-state => 'disabled');
    $root->configure(-state => 'disabled');
    $from->configure(-state => 'disabled');
    $to->configure(-state => 'disabled');
    $format->configure(-state => 'disabled');
    $sourcetype->configure(-state => 'disabled');
    $zero->configure(-state => 'disabled');
    $remark->configure(-state => 'disabled');           
    
    $user_label->bind ('<Return>' => sub {});
    
    $mainWindow->focusForce();
    
    $library->Subwidget("arrow")->configure(-bg => $barcode_entry);
    $library->Subwidget("entry")->Subwidget("entry")->configure(-bg => $barcode_entry);
    $library->Subwidget("slistbox")->Subwidget("listbox")->configure(-bg => $barcode_entry);

    $mainWindow->bind ('<Return>' => sub { 
	if ( $library_var eq '') {
	    $stage = 'library';
	    $library->configure(-state => 'normal');
	} else {
	    $stage = 'zero';
	    $zero->configure(-state => 'readonly');
	    $library->Subwidget("arrow")->configure(-bg    => 'grey85', -state => 'disabled');
	    $library->Subwidget("entry")->Subwidget("entry")->configure(-bg => 'grey85');
	    $library->Subwidget("slistbox")->Subwidget("listbox")->configure(-bg => 'grey85');
	}
	&start_process();
    });
}



sub go_add_zero {
    $action = "Do you want to pad with zeros on the platename (eg. 001 vs 1).";
    
    $lig->configure(-state => 'disabled');
    $sourcetype->configure(-state => 'disabled');
    $root->configure(-state => 'disabled');
    $from->configure(-state => 'disabled');
    $to->configure(-state => 'disabled');
    $organ->configure(-state => 'disabled');
    $library->configure(-state => 'disabled');
    $library->configure(-state => 'disabled');
    $remark->configure(-state => 'disabled');
    
    $user_label->bind ('<Return>' => sub {});
    
    $mainWindow->focusForce();

    $zero->Subwidget("arrow")->configure(-bg => $barcode_entry);
    $zero->Subwidget("entry")->Subwidget("entry")->configure(-bg => $barcode_entry);
    $zero->Subwidget("slistbox")->Subwidget("listbox")->configure(-bg => $barcode_entry);
    
    $mainWindow->bind ('<Return>' => sub { $remark->configure(-state => 'normal');
					   
					   $mainWindow->bind ('<Return>' => sub {});
					   
					   
					   $stage = 'remark';
					   
					   $zero->Subwidget("arrow")->configure(-bg    => 'grey85',
										-state => 'disabled');
					   $zero->Subwidget("entry")->Subwidget("entry")->configure(-bg => 'grey85');
					   $zero->Subwidget("slistbox")->Subwidget("listbox")->configure(-bg => 'grey85');
					   &start_process();
   }); 
}



sub go_remark {
    $action = "Please enter a remark or edit/use the default shown";
  

    
    my $vector_name = $STATEMENTS->get('Platetrack2.sql_lib::get_vector_name' , [$library_var]);
          
    $vector_ref = $vector_name->[0][0];
    
    if ($vector_ref eq ''){
	&update("No vector can be derived from library $library_var!\n");
    }

    $rem_var = "$library_var - $vector_ref";

    $lig->configure(-state => 'disabled');
    $sourcetype->configure(-state => 'disabled');
    $organ->configure(-state => 'disabled');
    $from->configure(-state => 'disabled');
    $to->configure(-state => 'disabled');
    $format->configure(-state => 'disabled');
    $library->configure(-state => 'disabled');
    $zero->configure(-state => 'disabled');
    $root->configure(-state => 'disabled');
    
    $remark->focusForce();
    $remark->configure(-bg => $barcode_entry);
    $remark->grab();
    $remark->bind ('<Return>' => sub { 
	if (($rem_var =~ /(^\w+$|^\w+-?$)/) || ($rem_var eq '')){
	    
	    if  ($rem_var eq '') {
		$stage = 'remark';
	    } else {
		$stage = 'end';
	    }
	}
	    
	$remark->configure(-bg => 'grey85');
	$remark->grabRelease();
	&sub_int();
    }); 
}



sub sub_int{
    my @Database_problems;
    my @to_print;
    
    ################################################################
    # We should only submit if the user is at the appropriate stage
    ################################################################
    unless ($stage eq 'remark') {
	return;
    }

    #######################
    # Grab a new sessionID
    #######################
    my $Session_id = $STATEMENTS->get('Platetrack2.sql_lib::select_session_id');  
    my $Session = $Session_id->[0][0]; 

    #######################
    # Go though each plate
    #######################
    foreach my $number ($from_var .. $to_var){
	
	if ($zero_var eq 'Yes'){
            if ($number < 10){
                $number = '0'.'0'.$number;
	    }
            if (($number > 9) && ($number < 100)){
		$number = '0'.$number;
	    }
	}
	
	my $platename = "$root_var" . "$number";

	############################################################
	# Check that the source platename has not already been used
	############################################################
	&update("Checking source_plate $platename does not already exist...\n");
	my $sourceplate_test = $STATEMENTS->get('Platetrack2.sql_lib::platename_check', [$platename]);
	$sourceplate_test = $sourceplate_test->[0][0];
	if ($sourceplate_test ne ''){
	    &update("A source_plate called $platename already exists !\n");
	    push @Database_problems, "A source_plate called $platename already exists !";
	} else {
	    &update("Processing information for $platename\n");
	    &create_sourceplate($platename, \@to_print, $Session, \@Database_problems);
	}
    }
    
    ###############################################################
    # Only print the barcodes if we have not seen any errors upto
    # this point
    ###############################################################

    push @Database_problems, 'End';
    
    
    if ($Database_problems[0] eq 'End'){
	&print_barcode(\@to_print);
    } else {
	&update("********************* Errors occured ! Rolling back entries. *********************");
	foreach my $t (@Database_problems){
	    &update("$t");
	    $update_screen->update('idletasks');
	}
	$STATEMENTS->{DBH}->rollback;
    }
    $stage = 'clear';
    &start_process();
}



sub create_sourceplate {
    my ($platename, $to_print, $Session, $Database_problems) = @_;
    
    my ($Org, $Org_id, $Source, $Id_Sourceplate);

    #####################################################################
    # SO type; We need to convert a user supplied description into an id
    #####################################################################
    my $id_type;
    eval{
	$id_type = $STATEMENTS->get('Platetrack2.sql_lib::get_sptype_idtype',[$sourcetype_var]);
	$id_type = $id_type->[0][0];
    };
    
    if ($@ ne ''){
	push @$Database_problems, $@;
    }



    eval{
	$Id_Sourceplate = $STATEMENTS->get('Platetrack2.sql_lib::Create_Id_Sourceplate');
	$Source = $Id_Sourceplate->[0][0];
	$Org = $STATEMENTS->get('Platetrack2.sql_lib::get_organisation_idorg',[$org_var]);
	$Org_id = $Org->[0][0];
    };
    
    if ($@ ne ''){
	push @$Database_problems, $@;
    }
    
    my $CreatePlate;
    my $PlateStatus;
    
    #####################################################################################
    # What are we going to do about ligations ? At present a fake entry is a made
    # (which is associated with a clone+project) and the user must enter this correctly.
    #####################################################################################
    
    eval{
	$CreatePlate = $STATEMENTS->do('Platetrack2.sql_lib::create_sourceplate',[$Source,
										  $format_var,
										  $id_type,
										  $platename,
										  $Org_id,
										  $ligation_var,
										  $library_var,
										  $who_team]);
    };
    
    if ($@ ne ''){
	push @$Database_problems, $@;
	&update("Sourceplate $Source $platename hasn't been created !\n"); 
    }                    
    else {
	&update("Sourceplate $Source $platename has been created\n");
    }        
    
    
    eval{ 
	$PlateStatus = $STATEMENTS->do('Platetrack2.sql_lib::create_sourceplate_status',[$Source,
											 $Session,
											 $prog,
											 $who,
											 $rem_var]);
    };
    
    if ($@ ne ''){
	push @$Database_problems, $@;
	&update("Sourceplate status for $Source $platename hasn't been created\n");
    }                    
    else {
	&update("The Sourceplate status has been set for $Source $platename\n");

	
	###########################################
	# We only have so much room on the sticker
	###########################################
        my $library16 = substr($library_var, 0, 16);
        my $Vector9 = substr($vector_ref, 0, 9);     


	################################################
	# Push this plate onto the things-to-print list
	################################################
	my %print_hash = (
			  "id_sourceplate"  => $Source,
			  "platename"       => $platename,
			  "vector"          => $Vector9,
			  "description"     => $sourcetype_var,
			  "library_name"    => $library16,
                          "who"             => $who
			  );
	push @$to_print, \%print_hash;      
    
	###################################
	# Make the sourceplate_map entries
	###################################
	&create_sourceplate_map($Source,$platename, $Database_problems);
	
    }              
}




sub create_sourceplate_map {
    my ($Source, $platename, $Database_problems) = @_;
    
    my ($to, $from, $map_row);
    
    # Shouldn't really be hardcoded
    if ($format_var == 96){
        $from = 1;
        $to = 96;
    } elsif ($format_var == 384){
	$from = 97;
	$to = 480;
    } else {
	die "CONTACT BUG. This is an unknown plate type - $format_var !\n";
    }    

    foreach my $n ($from .. $to){
	eval{
	    $map_row = $STATEMENTS->get('Platetrack2.sql_lib::maprow_id', [$n]);
	};
	
	if ($@ ne ''){
	    push @$Database_problems, $@;
	}
	
	my $Row = $map_row->[0]->[0];
	my $Col = $map_row->[0]->[1];
	if ($Col < 10) {
	    $Col = "0" . "$Col";
	}
	
	my $map;
	my $Sample_name = "$platename" . "$Row" . "$Col";
	
	eval{
	    $map = $STATEMENTS->do('Platetrack2.sql_lib::create_sourceplatemap', 
				   [$Source, 
				    $n,
				    $Sample_name]);
	};       
	
	if ($@ ne ''){
	    push @$Database_problems, $@;
	    &update("Problems creating sourceplatemap entries for $Source $Sample_name id_map - $n\n");
	}  
    }
}	



sub print_barcode {
    my ($to_print) = @_;
    
    undef $printer->{"Label"};
    
    foreach my $this (@$to_print){
	$printer->Name("$this->{platename}");
	$printer->Project("$this->{library_name}");
	$printer->Suffix("$this->{vector}");
	$printer->Owner("$this->{who}");
	$printer->Barcode("$this->{id_sourceplate}");
	$printer->Quantity(1);
	$printer->Labellist();

    }

    &update("Printing labels for new sourceplates");
    eval {
	$printer->Printlabel();
    };
    
    if ($@){
	&update("$@");
	&update("There have been problems printing.\n");
	&update("Rolling back database entries.\n");
	$STATEMENTS->{DBH}->rollback;
    } else {
	&update("Stickers printed. Commiting entries\n");
	$STATEMENTS->{DBH}->commit;
    }
}    




sub organisation {
    my $Library = $STATEMENTS->get('Platetrack2.sql_lib::get_organisation');
    foreach my $Test (@{$Library}){
	my $Test1 = join ",", @{$Test};
	$organ->insert('end',$Test1);
    }		
}


sub library_name {
    my $Library = $STATEMENTS->get('Platetrack2.sql_lib::library_name');
    foreach my $Test (@{$Library}){
	my $Test1 = join ",", @{$Test};
	$library->insert('end',$Test1);
    }	
}


sub sourceplate_type {
    my $preps = $STATEMENTS->get('Platetrack2.sql_lib::get_sourceplatetype');
    foreach my $Test (@{$preps}){
	my $Test1 = join ",", @{$Test};
	$sourcetype->insert('end',$Test1);
    }	
}


END {

    if ($STATEMENTS){
        $STATEMENTS->end;
    }

};











