package SPECIALPlatemaker;

use strict;
use vars qw(@ISA @EXPORT);
use Exporter;
@ISA = ('Exporter');
@EXPORT = qw(&create_a_special_plate);


use Tk;
require Tk::Dialog;
use NewBrowseEntry;
use var_monitor;
use Checkbarcode;
use Chemchooser;
use finch2_sj_routine;
#require '/nfs/griffin2/kva/badger-bin/finch/finch2_sj_routine.pm';

#
###########################################
# Generates the interace to allow the
# processing of transposon entries
# into the database by use of a 
# dnaplate ID barcode
###########################################
#
# Fonts
my ($title_f, $entry_f, $button_f, $label_f);

# Other
my $dbh;
my $plate_win;
my $blurb;
my $ADDS;
my $valid_chems;
my $chem_return;
my $suffix_return;
my $titlecolour = 'honeydew2';
my ($who, $id_role, $currproject, $ID_TEAM_FINSERV);
my ($plate_var, $suff_var, $it_var, $chem_var, $additive_var, $start_var, $end_var);
my ($rowcol2id_96, $id2rowcol_96, $return_code);
my $plate_e;
my $chem_return;
my $suffix_return;
my $backwards;
my $suff_e;
my $iter_e;
my $chem_e;
my $format_e;
my ($valid_custom,$valid_additives, $auto, $chem2suff, $old_suff, $TEAM, $currprojectspecies, $currprojectchr, $FSNAME, $session_id,$proj_name,$quit_total);
my %titles;
my $plate;
my $format_var = '';
my ($start_e,$end_e);

&monitor(\$plate_var, 'entity', \&get_names);
&monitor(\$chem_return, 'entity', \&get_chem);

sub create_a_special_plate {
 
    ($dbh,$who, $id_role, $currproject, $ID_TEAM_FINSERV, $rowcol2id_96, $id2rowcol_96, $return_code, $title_f, $entry_f, $button_f, $label_f, $blurb, $ADDS, $valid_chems, $chem_return, $suffix_return,$backwards,$valid_custom,$valid_additives, $auto, $chem2suff, $old_suff, $TEAM, $currprojectspecies, $currprojectchr, $FSNAME, $session_id, $proj_name,$quit_total) = @_;

#$proj_name->configure(-state=>'disabled');

    if (! defined $plate_win){
#	print ">>$plate_var, $chem_var, $additive_var, $start_var, $end_var<<\n";
        

        $chem_var='';
        $suff_var='';
        $it_var='';
        my %valid_additives = %$ADDS;
        my @list;
        push @list,'NO_ADDITIVE';
        foreach my $keys (keys %valid_additives){
            push @list,$keys;
        }
        
	($plate_var, $chem_var, $additive_var, $start_var, $end_var) = '';
	
	# Window
#	$plate_win = $mainWindow->Toplevel;
        $plate_win = MainWindow->new;
	$plate_win->wm('minsize', 520, 300); 
	$plate_win->wm('maxsize', 520, 300);
        my $f = $plate_win->Frame(-height => 300, -width => 520);
        $f->pack();
        $plate_win->idletasks();
	$plate_win->packPropagate(0);
        $f->packForget();

	$plate_win->configure (
			       #-font=> $button_f, # Fix 5.004 to 5.8.0
			       -title => $blurb
			      );
        
        $plate_win->grab();
	
	# Disable the close option
	$plate_win->protocol('WM_DELETE_WINDOW' => sub { });
        
	# Frame
my $menuBar1 = $plate_win->Frame(-bg => 'grey77')->pack(-side => 'top', -fill => 'x');
	my $top_frame = $plate_win->Frame()->pack(side => 'top', fill => 'both');
	my $middle_frame = $plate_win->Frame(-relief => 'raised', -borderwidth => '5' )->pack(side => 'left');
	my $middle_frame_1 = $middle_frame->Frame()->pack(side => 'top');
	my $middle_frame_1a = $middle_frame->Frame()->pack(side => 'top');
        my $middle_frame_1b = $middle_frame->Frame()->pack(side => 'top');
        my $middle_frame_1c = $middle_frame->Frame()->pack(side => 'top');
	my $middle_frame_2 = $middle_frame->Frame()->pack(side => 'top');
	my $middle_frame_3 = $middle_frame->Frame()->pack(side => 'top');
	my $middle_frame_4 = $middle_frame->Frame()->pack(side => 'top');
	my $middle_frame_5 = $middle_frame->Frame()->pack(side => 'top');
	my $left_frame = $plate_win->Frame()->pack(side => 'right');

	my $fileMenu1 = $menuBar1->Menubutton(-font => $button_f, 
					      -bg => 'grey77', 
					      -text => 'Please Read', 
					      -underline => 0);
	$fileMenu1->configure(-menu => $fileMenu1 ->Menu(-tearoff => 0));
	$fileMenu1->pack(-side => 'left');

	$fileMenu1->command(-font => $button_f, 
			    -label => 'Information', 
			    -underline => 0, 
			    -command => sub {
				my $INFORMATION;
				my $ok = ('OK');
				if (! defined $INFORMATION) {
				    $INFORMATION= $plate_win->Dialog(-title          => 'INFO',
								      -font           => $button_f,
								      -text           => '',
								      -default_button => $ok,
								      -buttons        => [$ok],
								      );
				    $INFORMATION->configure(-wraplength => '4i',
							    -text       => "'Submit to DB' button will make finish batch and mapplate entries directly into the database (96 samples must be submitted).\n\n'To Interface' button will generate entries into the finch2 grid to be processed in the normal way",
							    );
				}
				my $button = $INFORMATION->Show;
			    });

	$fileMenu1->command(-font => $button_f, 
			    -label => 'How to use', 
			    -underline => 0, 
			    -command => sub {
				my $how_to_use;
				my $ok = ('OK');
				if (! defined $how_to_use) {
				    $how_to_use= $plate_win->Dialog(-title          => 'How To Use',
								     -font           => $button_f,
								     -text           => '',
								     -default_button => $ok,
								     -buttons        => [$ok],
								     );
				    $how_to_use->configure(-wraplength => '7i',
							   -text       => "Below are instructions on how to use this interface.\n\n1) Scan in the DNA plate barcode for the transposon library or paste in the DP number from the barcode i.e DP985532S. \n\n2) On scanning, if the dnaplate barcode or ID is recognised the format, start and end well fields will be filled in. \n\n3) Right click on the 'ChemID' name field and this will open the chemchooser interface.\n\n4) Select the chemistry of choice and select 'OK' which will fill in the relevant fields.\n\n5) The middle field is the entry box for the iteration (if needed).\n\n6) Their is a drop down menu for the additives, but by default this is set to 'BDT:dGTP4:1', if you do not require an additive, just select the 'NO_ADDITIVE' entry at the top.\n\n7) Then select one of the 2 options for generating the samples e.g 'Submit to DB' (require 96 samples) OR 'To Interface'.\n\n8)To clear the interface, just select the reset button which will clear all fields.",
							   );
				}
				my $button = $how_to_use->Show;
			    });

	my $label = $top_frame->Label(
				      -font => $title_f, 
				      -text => 'Please scan in your plate information.')->pack(-side => 'top');
        
	
	%titles = (
		   "plate" => "Scan DNA_plate",
		   "platescan" => "Platename",
		   "format" => "Format",
		   "chemistry" => "ChemID",
		   "additive" => "Additive",
		   "start" => "Start",
		   "end" => "End", 
		   );
	
	$plate = $middle_frame_1->Entry(
					-font => $button_f,
					-state => 'disabled',
					-width => 15,
					-bg => $titlecolour,
					-textvariable => \$titles{plate},
					)->pack(side => 'left');
	
	my $format = $middle_frame_1a->Entry(
					     -font => $button_f,
					     -state => 'disabled',
					     -width => 15,
					     -bg => $titlecolour,
					     -textvariable => \$titles{format},
					     )->pack(side => 'left');
	
        my $chemistry = $middle_frame_1b->Entry(
                                                -font => $button_f,
                                                -state => 'disabled',
                                                -width => 15,
                                                -bg => $titlecolour,
                                                -textvariable => \$titles{chemistry},
                                                )->pack(side => 'left');
	
        $chemistry->bind('<Button-3>', sub { 
	    $plate_win->grabRelease();
	    &chemistry($dbh, $plate_win, $valid_chems, \$chem_return, \$suffix_return, $title_f, $entry_f, $button_f, $label_f);
        });
	
        my $additive = $middle_frame_1c->Entry(
                                               -font => $button_f,
                                               -state => 'disabled',
                                               -width => 15,
                                               -bg => $titlecolour,
                                               -textvariable => \$titles{additive},
                                               )->pack(side => 'left');
	
	my $start = $middle_frame_3->Entry(
					   -font => $button_f,
					   -state => 'disabled',
					   -width => 15,
					   -bg => $titlecolour,
					   -textvariable => \$titles{start},
					   )->pack(side => 'left');
	
	my $end = $middle_frame_4->Entry(
					 -font => $button_f,
					 -state => 'disabled',
					 -width => 15,
					 -bg => $titlecolour,
					 -textvariable => \$titles{end},
					 )->pack(side => 'left');
	
	
	$plate_e = $middle_frame_1->Entry(
					  -font => $entry_f,
					  -state => 'normal',
					  -width => 25,
					  -textvariable => \$plate_var,
					  )->pack(-side => 'left' );
        $plate_e->focus();

        $format_e = $middle_frame_1a->Entry(
					    -font => $entry_f,
					    -state => 'normal',
					    -width => 25,
					    -textvariable => \$format_var,
					    )->pack(-side => 'left' );
        
        $suff_e = $middle_frame_1b->Entry(
					  -font => $entry_f,
                                          -state => 'disabled',
                                          -width => 10,
                                          -textvariable => \$suff_var,
                                          )->pack(-side => 'left' );
	
        $iter_e = $middle_frame_1b->Entry(
					  -font => $entry_f,
                                          -state => 'normal',
                                          -width => 2,
                                          -textvariable => \$it_var,
                                          )->pack(-side => 'left' );
	
        $chem_e = $middle_frame_1b->Entry(
					  -font => $entry_f,
                                          -state => 'disabled',
                                          -width => 10,
                                          -textvariable => \$chem_var,
                                          )->pack(-side => 'left' );
        
        my $addit_e = $middle_frame_1c->BrowseEntry(
						    -width => 21,
                                                    -font => $button_f,
                                                    -variable => \$additive_var,
                                                    -state => 'readonly'
                                                    )->pack(-side => 'left');
        $additive_var = 'BDT:dGTP4:1';
        $addit_e->insert('end',@list);
        my $ae = $addit_e->Subwidget("entry")->Subwidget("entry");
        $ae->configure(-bg => 'honeydew2');
        if ($additive_var){
	    $plate_win->grab();
	}

	$start_e = $middle_frame_3->Entry(
					  -font => $entry_f,
					  -state => 'normal',
					  -width => 25,
					  -textvariable => \$start_var,
					  )->pack(side => 'top');
	
	$end_e = $middle_frame_4->Entry(
					-font => $entry_f,
					-state => 'normal',
					-width => 25,
					-textvariable => \$end_var,
					)->pack(side => 'left');
	
	# Buttons on the right
	my $plate_submit = $left_frame->Button(
					       -font => $button_f, 
					       -text => 'Submit to DB',
					       -width => 10,
					       -command => sub {    
						   # Want no spaces in $plate_var,$chem_var,$additive_var
						   $plate_var =~ s/\s//g;
						   $chem_var =~ s/\s//g;
						   #$additive_var =~ s/\s//g;
						   $it_var =~ s/\s//g;
						   # We must have a valid entry in each box
						   if ( ($plate_var eq '') || ($chem_var eq '') || ($additive_var eq '')|| ($start_var eq '') || ($end_var eq'') || ($format_var!~ /96|384/) ){
						       if ($format_var!~ /96|384/){ 
                                                           &popup ("Warn", ["The format needs to be set to 96 or 384."]);
						       }
						       &highlight_errors($plate_var,$chem_var,$additive_var,$start_var,$end_var);
						       return();
						       
						   } else {
						           
						       &clear_errors();

						       # Convert any uppercase to lowercase in
						       # $start_var and $end_var
						       $start_var = lc $start_var;
						       $end_var = lc $end_var;
						       $it_var = lc $it_var;
						       
						       my $length = length $it_var;
						       if ((($it_var ne '') && ($it_var !~ /[a-z]/)) || ($length > 1)){
                                                           &popup ("Warn", ["The iteration field should only contain 1 letter."]);
							   return;   
						       }
						       
						       if ($suff_var=~ /2/g){
							     &popup ("Warn", ["Custome primer related suffices are not permitted for submission through this interface."]);
							   return;   
						       }
						       
						       # Check 'Start' nb. 384well plate is not yet valid
						       my ($start_row, $start_col);
						       if ($start_var =~ /^([a-h])(\d+)/) {
							   $start_row = $1;
							   $start_col = $2;
						       } else {
							   &well("Start");
							   return();
						       }
						       
						       if ( ($start_col > 12) || ($start_col < 1) ){
							   &well("Start");
							   return();
						       }
						       
						       # Check 'End'
						       my ($end_row, $end_col);
						       if ($end_var =~ /^([a-h])(\d+)/) {
							   $end_row = $1;
							   $end_col = $2;
						       } else {
							   &well("End");
							   return();
						       }
						       if ( ($end_col > 12) || ($end_col < 1) ){
							   &well("End");
							   return();
						       }
						       
						       # Make sure 'Start' comes before 'End'
						       my ($start_no, $end_no);
						       $start_no = $rowcol2id_96->{$start_var};
						       $end_no = $rowcol2id_96->{$end_var};
						       
						       
						       if ($end_no < $start_no){
                                                           &popup ("Warn", ["Sorry, 'Start' must come before 'End'."]);
							   return;
						       }
						       
						       if ($end_no == $start_no){
                                                           &popup ("Warn", ["Sorry, 'Start' must not be equal to 'End'."]);
							   return;
						       }
						       
##need to add a bit more here
						       if ($end_no != 96){
							     &popup ("Warn", ["You need to submit 96 samples."]);
							   return;
						       }
						       
						       # We now need to make something for finch2 to use
                                                       my $add_var = $additive_var;
						       if ($additive_var=~ /NO_ADDITIVE/){
							   $add_var="";
						       }
						       
						       my $stat2= "select distinct bb.name
from beckman_box bb
where bb.name = ?";
						       my $sth2 = $dbh->prepare($stat2) || die "ERROR:$DBI::errstr";
						       $sth2->bind_param(1, $plate_var);
						       $sth2->execute || die "ERROR:$DBI::errstr";
						       my $check = $sth2->fetchrow();
						       $sth2->finish();
						       if ($check){
							   print "Green light for submission of samples from platename $check\n";
							   my($fbatch_id, $mapplate_id,$ERROR,$CHECK_PROJECT);
							   eval {
							       ($fbatch_id, $mapplate_id,$ERROR,$CHECK_PROJECT) = &finch2_sj_routine::insert_samples($dbh, $who, $id_role,$currproject, $ID_TEAM_FINSERV, $format_var, $plate_var,$chem_var,$it_var,$suff_var,$add_var,$start_no,$end_no,$id2rowcol_96,\%valid_additives,$backwards,$valid_chems,$valid_custom,$valid_additives, $auto, $chem2suff, $old_suff, $TEAM, $currprojectspecies, $currprojectchr, $FSNAME, $session_id);
							   };
							   if ($@){
                                                               &popup ("Warn", ["Problems have occured in submission \n $@, \n the entries have been rolled back in the database."]);
							       $dbh->rollback();
#                                                               if ($quit_total>0){
#                                                                   $proj_name->configure(-state=>'disabled');
#                                                               } else {
#                                                                   $proj_name->configure(-state=>'readonly');
#                                                               }
							       $plate_win->destroy();
							       undef $plate_win;
							   } else {
                                                               print ">>$fbatch_id, $mapplate_id,$ERROR,$CHECK_PROJECT<<\n";
							       if ($fbatch_id && $mapplate_id){
								   $dbh->commit();
                                                                   &popup ("INFO", ["The finish_batch ID is $fbatch_id and the mapplate ID is $mapplate_id. Please make a note of it."]);
								   &reset($plate_e,$chem_e,$addit_e,$iter_e,$start_e,$end_e,$suff_e);
							       }
                                                               if ($ERROR){
                                                                   &popup ("Warn", ["Duplicate entries have been found to exist, either add or increase the iteration."]);    
                                                               }
                                                               if ($CHECK_PROJECT){
                                                                   &popup ("Warn", ["The project $CHECK_PROJECT linked to this dnaplate ID isn't the same as the project you have opened finch2 with. You will need to reopen finch2 with the project in question."]);   
                                                               }
							   }
						       } else {
                                                           &popup ("Warn", ["This platename dosen't exist in the beckman_box table.\n Sorry cannot submit the samples."]);
							   return;    
						       }
						       #   $plate_win->destroy();
						       #   undef $plate_win;
						   }
					       })->pack();
	
	
	# Buttons on the right
	my $plate_ok = $left_frame->Button(
					   -font => $button_f, 
					   -text => 'To Interface',
					   -width => 10,
					   -command => sub {
                                               
                                               # Want no spaces in $plate_var,$chem_var,$additive_var
                                               $plate_var =~ s/\s//g;
                                               $chem_var =~ s/\s//g;
                                               #$additive_var =~ s/\s//g;
                                               $it_var =~ s/\s//g;
					       # We must have a valid entry in each box
					       if ( ($plate_var eq '') || ($chem_var eq '') || ($additive_var eq '')|| ($start_var eq '') || ($end_var eq'') ){
						   &highlight_errors($plate_var,$chem_var,$additive_var,$start_var,$end_var);
						   return;
                                                   
					       } else {
                                                   
						   # Convert any uppercase to lowercase in
						   # $start_var and $end_var
						   $start_var = lc $start_var;
						   $end_var = lc $end_var;
                                                   $it_var = lc $it_var;

                                                   my $length = length $it_var;
                                                   if ((($it_var ne '') && ($it_var !~ /[a-z]/)) || ($length > 1)){
                                                       &popup ("Warn", ["The iteration field should only contain 1 letter."]);
						       return;   
                                                   }
						   
                                                   if ($suff_var=~ /2/g){
                                                       &popup ("Warn", ["Custom primer related suffices are not permitted for submission through this interface."]);
						       return;   
                                                   }
						   
						   # Check 'Start' nb. 384well plate is not yet valid
						   
						   my ($start_row, $start_col);
						   if ($start_var =~ /^([a-h])(\d+)/) {
						       $start_row = $1;
						       $start_col = $2;
						   } else {
						       &well("Start");
						       return();
						   }
						   
						   if ( ($start_col > 12) || ($start_col < 1) ){
						       &well("Start");
						       return();
						   }
						   
						   # Check 'End'
						   my ($end_row, $end_col);
						   if ($end_var =~ /^([a-h])(\d+)/) {
						       $end_row = $1;
						       $end_col = $2;
						   } else {
						       &well("End");
						       return();
						   }
						   if ( ($end_col > 12) || ($end_col < 1) ){
						       &well("End");
						       return();
						   }
						   
						   # Make sure 'Start' comes before 'End'
						   my ($start_no, $end_no);
						   $start_no = $rowcol2id_96->{$start_var};
						   $end_no = $rowcol2id_96->{$end_var};
                                                   
                                                   
						   if ($end_no < $start_no){
                                                       &popup ("Warn", ["Sorry, 'Start' must come before 'End'."]);
						       return;
						   }
                                                   
						   if ($end_no == $start_no){
                                                       &popup ("Warn", ["Sorry, 'Start' must not be equal to 'End'."]);
						       return;
						   }
                                                   
						   # We now need to make something for finch2 to use
                                                   if ($additive_var=~ /NO_ADDITIVE/){
                                                       $additive_var="";
                                                   }
						   &make_list($start_no, $end_no, $chem_var, $suff_var, $additive_var, $it_var);
						   &reset($plate_e,$chem_e,$addit_e,$iter_e,$start_e,$end_e,$suff_e);
						   $plate_win->destroy();
						   undef $plate_win;
					       }
					   })->pack();
	
	my $plate_cancel = $left_frame->Button(
					       -font => $button_f, 
					       -text => 'Close',
					       -width => 10,
					       -command => sub {
						   &reset($plate_e,$chem_e,$addit_e,$iter_e,$start_e,$end_e,$suff_e);
						   
#                                                   if ($quit_total>0){
#                                                       $proj_name->configure(-state=>'disabled');
#                                                   } else {
#                                                       $proj_name->configure(-state=>'readonly');
#                                                   }
						   $plate_win->destroy();
						   undef $plate_win;
					       })->pack();
	
        my $plate_reset = $left_frame->Button(
					      -font => $button_f, 
					      -text => 'Reset',
					      -width => 10,
					      -command => sub {
						  &reset($plate_e,$chem_e,$addit_e,$iter_e,$start_e,$end_e,$suff_e);
                                                  &clear_errors();
					      })->pack();
	
        
    } else {
	warn "Nah ! already active !\n";
    }
    
}

sub get_names {
  
    my $ID;
    my $check = $plate_var;
    if ($plate_var=~ /^(DP)(\d+)\w/){
        $ID = $1;
        $plate_var = $2;
    }
    
    $plate_var=~ s/\s+//g;  
    unless (($plate_var=~ /\D+/g) || ($plate_var eq '')){ 
	my $length = length($plate_var);
	if (($length eq '13') || ($ID)){
            my $hash_return;
            if (!$ID){
                $hash_return = Verifynumber("$plate_var","DP");  
            } else {
                $hash_return = Verifynumber("$check");
            }
            my $process = $hash_return->{Process};
#            print ">>process - $process<<\n";
            if ($process eq 'Good'){
                
                my $dnaplate = $hash_return->{Number};
                
##check to ensure that the dnaplate ID
##is actually related to a transposon job.
                my $stat1 = "select std.description,l.clonename
from dnaplate_map dpm, bb_map bbm, subclone sc, ligation l,fragmentation_band fb, sil_job sj, sil_request sr, siltypedict std
where dpm.id_bbmap = bbm.id_bbmap
and bbm.id_subclone = sc.id_subclone
and sc.id_ligation = l.id_ligation
and l.id_fragband = fb.id_fragband
and fb.id_frag = sj.id_frag
and sj.id_request = sr.id_request
and sr.sil_type = std.id_dict
and sr.sil_type = 1
and dpm.id_map = 1
and dpm.id_dnaplate = ?";
                
                my $sth1 = $dbh->prepare($stat1) || die "ERROR:$DBI::errstr";
                $sth1->execute($dnaplate) || die "ERROR:$DBI::errstr";
                my ($description,$clone) = $sth1->fetchrow();
                $sth1->finish();
		
                if ($description eq ''){
                    $plate_var="";
                    &popup ("Warn", ["This dnaplate ID isn't linked to a SIL request."]);
                    return;
                }
		
                #check that the project name related the the dnaplate
		#is the same as the project
                #you are using to submit your samples.
                my $stat1_1 = "select projectname from clone_project where clonename = ?";
                my $sth1_1 = $dbh->prepare($stat1_1) || die "ERROR:$DBI::errstr";
                $sth1_1->execute($clone) || die "ERROR:$DBI::errstr";
                my $check_project = $sth1_1->fetchrow();
                $sth1_1->finish(); 
                $check_project=~ s/\s+//g;
#		print ">>CURRENT PROJECT $currproject<<>>CHECK PROJECT $check_project<<\n";
                if ($currproject eq $check_project){
                    
                    #Ensure that is is a transposon.
                    if ($description eq 'Transposon'){
                        
########################
                        
                        #get the bbname and format to use in the interface
                        #and determine the start and end point.
                        my $stat2 = "select distinct bb.name,bb.format
from dnaplate_map dpm, bb_map bbm, beckman_box bb
where dpm.id_bbmap = bbm.id_bbmap
and bbm.id_beckmanbox = bb.id_beckmanbox
and dpm.id_dnaplate = ?";
                        
                        my $sth2 = $dbh->prepare($stat2) || die "ERROR:$DBI::errstr";
                        $sth2->execute($dnaplate) || die "ERROR:$DBI::errstr";
                        my ($newvar,$newform) = $sth2->fetchrow();
                        $sth2->finish();
                        $newvar=~ s/\s+//g;
#                    print ">>NEWVAR - $newvar<<\n";
#                    if ($plate_var){
                        if (($newvar) && ($newvar ne '')){
                            $plate_var=~ s/\s+//g;
                            $plate->configure(-textvariable => \$titles{platescan});
                            $plate->update();
                            $plate_e->configure(-bg=>'yellow');
                            $plate_e->delete(0,'end');
                            $plate_e->insert('end',$newvar);
                            $plate_e->configure(-state=>'disabled');
                            $plate_e->update();
                            $format_e->delete(0,'end');
                            $format_e->insert('end',$newform);
                            $format_e->configure(-state=>'disabled');
                            $format_e->update();
                            if (($newform eq '96') || ($newform eq '384')){
                                $start_e->insert('end',"a1");
                                $end_e->insert('end',"h12");
                            }
                            
                        } else {
                            $plate_var="";
                            return;
                        }
                        
                    } else {
                        $plate_var="";
                        &popup ("Warn", ["This dnaplate ID isn't a Transposon."]);
                        return;    
                    }
                    
                } else {

                    $plate_var="";
                    &popup ("Warn", ["The project $check_project linked to this dnaplate ID isn't the same as the project you have opened finch2 with. You will need to reopen with the project in question."]);
                    return; 
                }   
             
            } else {
                
                $plate_var="";
                &popup ("Warn", ["This barcode/ID isn't a dnaplate ID."]);
                return;    
            }
	}
    }
    
}


sub get_chem {

    if ($chem_return=~ /^\d+/g){
        $suff_var=$suffix_return;
        $suff_e->configure();
        $suff_e->update();
        $chem_var=$chem_return;
        $chem_e->configure();
        $chem_e->update();	
	$plate_win->grab();
    } 
    
}

sub make_list {
    my($start_no, $end_no, $chem_var, $suff_var, $additive_var, $it_var) = @_;
    my @platedata;
    foreach my $next ($start_no .. $end_no){
	# convert $next to rowcol
	my $rowcol = $id2rowcol_96->{$next};
	push @platedata, "$plate_var$rowcol";
    }
    
    &$return_code(\@platedata,$chem_var, $suff_var, $additive_var, $it_var);
}


sub well {
    my ($problem) = @_;
    
    &popup ("Warn", ["Sorry, $problem must be in rowcolumn format (eg. a12 - p24)"]);
    
}

sub reset {
    my ($plate_e,$chem_e,$addit_e,$iter_e,$start_e,$end_e,$suff_e) = @_;
    
    if ($plate_var ne ''){
	$plate->configure(-textvariable => \$titles{plate});
	$plate->update();	
	$plate_e->configure(-state=>'normal');
        $plate_e->configure(-bg => 'grey85');
        $plate_e->delete(0,'end');
        $plate_e->update();
	$plate_var=''
    }
    if ($format_var ne ''){
	$format_e->configure(-bg => 'grey85',-state=>'normal');
        $format_e->update();
        $format_var='';
    }
    if ($chem_var ne ''){
        $chem_var='';
    }
    $chem_e->configure(-bg => 'grey85');
    $chem_e->update();

    if ($additive_var ne ''){
        $additive_var='BDT:dGTP4:1';
    }
    if ($it_var ne ''){
        $it_var='';
    }
    if ($start_var ne ''){
        $start_var='';
    }
    if ($end_var ne ''){
        $end_var='';
    }
    if ($suff_var ne ''){
        $suff_var='';
    }
    $suff_e->configure(-bg => 'grey85');
    $suff_e->update();

}

sub highlight_errors {
    my($plate_var,$chem_var,$additive_var,$start_var,$end_var)=@_;

    if ($plate_var eq ''){
	$plate_e->configure(-bg => 'red');
	$plate_e->update();
    }
    if ($chem_var eq ''){
	$suff_e->configure(-bg => 'red');
	$suff_e->update();
	$chem_e->configure(-bg => 'red');
	$chem_e->update();
    }
    if ($start_var eq ''){
	$start_e->configure(-bg => 'red');
	$start_e->update();
    }
    if ($end_var eq ''){
	$end_e->configure(-bg => 'red');
	$end_e->update();
    }
}

sub clear_errors {
    
    $plate_e->configure(-bg => 'grey85');
    $plate_e->update();
    $suff_e->configure(-bg => 'grey85');
    $suff_e->update();
    $chem_e->configure(-bg => 'grey85');
    $chem_e->update();
    $start_e->configure(-bg => 'grey85');
    $start_e->update();
    $end_e->configure(-bg => 'grey85');
    $end_e->update();
}

sub popup {
    my ($title,  $mesgref) = @_;
    my $mesg = join ("\n", @$mesgref);
    my $dialog = $plate_win->Dialog (
				      -font => "$button_f",
				      -title => "$title",
				      -text => "$mesg",
				      -default_button => '1',
				      -buttons => ['OK']);
    $dialog->Show();
}

1;








