
#BEGIN {
#    push @INC, "/usr/local/badger/bin";
#}

require Exporter;

use     strict;
use     WrapDBI;
use     File::Basename;
use     Carp;

package DNAPreps;

#use     Tk::Widget;
#require Tk::Toplevel;
#use     Tk::Table;

use     Data::Dumper;

my $dbuser        = 'dev2';    # for testing purposes only

@DNAPreps::ISA    = qw(Exporter);
#@DNAPreps::EXPORT = qw(DNAPreps);

package LemurGetJobs;


##########################################
# CONSTANTS
# i use emacs - leave space aftre '/' char
##########################################

*MAIN::NUM_ROWS    = \10;         # make this 15??? 12 is usual for a day...
*MAIN::BITMAP_DIR  = \ "$ENV{'BADGER'}/lib/finch/bitmaps";

##########################################
# GLOBALS
# to this namespace i hope...
##########################################

my $cursor = 0;          # first cell in array displayed in table of labels
#my @assignTo;           # -variable to each Assign To BrowseEntry. First Index
                         # start at ONE

my $instanceCount;


################################################################################
# create Make Work window.
################################################################################

sub new {

    my ($type, $parentWindow, $dbUser, $session_id) = @_;
    my (@dummy);
    my ($table);


    my $realUserName = getpwuid($<);

    my $self = {
	dbUser       => $dbUser,
	session_id   => $session_id,
	realUserName => "$realUserName",
    };

    bless($self, $type);

    # INSTANCE COUNT STUFF. Bodge to get around global variables being shared
    # amoung several windows. DESTROY decrements $instanceCount.

    ++$instanceCount;

    if( $instanceCount > 1 ) {
	warn "\nThere is already a Select Job window active\n";
	return undef;
    }

    my ($dbh);
    my ($ref_rows);

    $self->setupHashTables();  # setup operatorHash, etc..

    $self->{date} =  (localtime)[3]."/".
	            ((localtime)[4] + 1)."/".
	            ((localtime)[5] + 1900);

    $self->{mw} = $parentWindow->Toplevel();
    my $mw      = $self->{mw};

    $mw->title('Select Jobs');
    $mw->Label(font    => '*-times-bold-r-normal--*-180-*-*-p-*-*-*',
	       text    => "Select jobs to do",
	       height  => 2,
	       width   => 40)->pack(-side => 'top');

    # mf : masterFrame , which contains;
    #   tf : Table Frame 
    #   upDownFrame
    
    my $mf = $mw->Frame(-relief => 'raised',);
    my $tf = $mf->Frame(-relief => 'raised',);

    $self->createTableFrame($tf);

    $tf->pack(-side => 'right');

    #
    # create buttons on the bottom of the window
    #

    my ($upButton, $downButton, $makeWorkButton);
    my ($upDownFrame);


    $upDownFrame = $mf->Frame();

    # Make an 'up-button';
    $mw->Bitmap('up',
		-file     => "$MAIN::BITMAP_DIR/uarrw.xbm",
		-maskfile => "$MAIN::BITMAP_DIR/uarrw.xbm"
	       );

    $upButton = $upDownFrame->Button(-image   => 'up',
				     -command => sub { $self->pressedUp; }); 
    $upButton->pack(-side => 'top');

    # Make an 'down-button';
    $mw->Bitmap('down',
		-file     => "$MAIN::BITMAP_DIR/darrw.xbm",
	       	-maskfile => "$MAIN::BITMAP_DIR/darrw.xbm"
		);
    
    $downButton = $upDownFrame->Button(-image   => 'down',
			               -command => sub { $self->pressedDown; });
    $downButton->pack(-side => 'bottom');

    $upDownFrame->pack(-side => 'left');
    $mf->pack(-side => 'top');

    # Generate Work and Cancel button

    my $buttonFrame; 
    my $cancelButton;
    my $dummyLabel;
    my $instanceButton;

    $buttonFrame    = $mw->Frame(-relief => 'raised',);

    $makeWorkButton = $buttonFrame->Button(-text    => 'Print Jobs',
					   -width   => 12,
					   -command => sub{
					       $self->pressedMakeWork;
					   });
#    $instanceButton = $buttonFrame->Button(-text    => 'Instance Count',
#					   -width   => 12,
#					   -command => sub{
#					       warn "$instanceCount\n";
#					   });

    $cancelButton   = $buttonFrame->Button(-text    => 'Finish',
					   -width   => 12,
					   -command => sub {
					       $mw->destroy;
					   });

    $dummyLabel     = $buttonFrame->Label( -width   => 54);

    $dummyLabel->grid    (-row => 0, -column => 2);
    $makeWorkButton->grid(-row => 1, -column => 1);
#    $instanceButton->grid(-row => 1, -column => 2);
    $cancelButton->grid  (-row => 1, -column => 3);

    $buttonFrame->pack(-side => 'bottom');

    # All gadgets have been created

    # Get SIL_REQUEST's that are new.

    my $refClonesLigated;

    eval {
	$dbh = WrapDBI->connect($self->{dbUser}, {RaiseError => 1});
	expire("Could not connect to database") if !defined $dbh;
	$dbh->{AutoCommit} = 0;

	$ref_rows = $dbh->fetch_all("
            select sr.ID_REQUEST, p.FORENAME, p.SURNAME, std.DESCRIPTION,
                   sds.CLONENAME,
                   c.SPECIESNAME, cd.Description
            from   SIL_REQUEST      sr, SILREQUEST_STATUS srs,
                   SILTYPEDICT      std,
                   SIL_DNASOURCE    sds,
                   CLONE            c,
                   TEAM_PERSON_ROLE tpr,
                   PERSON           p,
                   CHROMOSOMEDICT   cd
            where  srs.ID_REQUEST  = sr.ID_REQUEST
            and    srs.STATUS      = 1
            and    srs.ISCURRENT   = 1
            and    sr.SIL_TYPE     = std.ID_DICT
            and    sds.ID_SOURCE   = sr.ID_SOURCE
            and    sds.CLONENAME   = c.CLONENAME
            and    sr.REQUESTED_BY = tpr.ID_ROLE
            and    tpr.ID_PERSON   = p.ID_PERSON
            and    c.CHROMOSOME    = cd.ID_DICT
            order by sr.ID_REQUEST
            ");
    };

    $self->showError("$@\n") if ($@);

    $dbh->disconnect if $dbh;

    # For each Job Request, store its details

    my ($id_request, $requested_by, $SIL_type,
        $cloneName,
	$speciesName, $chromosome);
    my ($i);

    my $x = 0;
    my $row;

    foreach $row (@$ref_rows) {

	$id_request    = $row->[0];
	$requested_by  = $row->[1]." ".$row->[2];
        $SIL_type      = $row->[3];
	$cloneName     = $row->[4];
	$speciesName   = $row->[5];
	$chromosome    = $row->[6];

	push( @{$self->{dataStore}->[$x]} , "$id_request"     );
	push( @{$self->{dataStore}->[$x]} , $SIL_type          );
	push( @{$self->{dataStore}->[$x]} , $cloneName        );
	push( @{$self->{dataStore}->[$x]} , $speciesName      );
	push( @{$self->{dataStore}->[$x]} , $requested_by     );
	push( @{$self->{dataStore}->[$x]} , $chromosome       ); 

#	print "id_request   == ", $self->{dataStore}->[$x]->[0], "\n";
#	print "requested_by == ", $self->{dataStore}->[$x]->[1], "\n";
#	print "SIL_type     == ", $self->{dataStore}->[$x]->[2], "\n";
#	print "cloneName    == ", $self->{dataStore}->[$x]->[3], "\n";
#	print "speciesName  == ", $self->{dataStore}->[$x]->[4], "\n";
#	print "chromosome   == ", $self->{dataStore}->[$x]->[5], "\n\n";

	$x++;
    }

    $dbh->disconnect if $dbh;

    ##################################################
    # now sort the dataStore. Squash all DNA Prep Nums
    # into one row of text, so only 1 clone per line
    ##################################################

    my $numRecs;

    unless( defined($self->{dataStore}) ) {
	warn "no records found\n";
    }
    else {
	$numRecs = scalar(@{$self->{dataStore}});
    }

    for(my $x = 0; $x < $numRecs; $x++) {

	for(my $y = $x + 1; $y < $numRecs; $y++) {

	    if($self->{dataStore}->[$x]->[0] eq $self->{dataStore}->[$y]->[0]) {

		$self->{dataStore}->[$x]->[4] .= 
		    ",$self->{dataStore}->[$y]->[4]";

		for(my $z = $y; $z < $numRecs; $z++) {
		    $self->{dataStore}->[$z] = $self->{dataStore}->[$z + 1];
		}

		pop @{$self->{dataStore}};
 
		$numRecs--;
		$y--;       # yes, decrement the loop variable cos squashed
                            # array.
	    }
	}
    }

    # Draw data into widgets.

    my $widgets = $self->{widgets};
    $i = 1;

    foreach $row ( @{$self->{dataStore}}) {

	if( $i <= $MAIN::NUM_ROWS ) {

	    $widgets->[$i][0]->configure(text => "$row->[0]");
	    $widgets->[$i][1]->configure(text => "$row->[1]");
	    $widgets->[$i][2]->configure(text => "$row->[2]");
	    $widgets->[$i][3]->configure(text => "$row->[3]");
	    $widgets->[$i][4]->configure(text => "$row->[4]");

# this used to be a priority thing...

#	    if($row->[5] == 1 ) {
#		$widgets->[$i][0]->configure(fg => 'red');
#		$widgets->[$i][1]->configure(fg => 'red');
#		$widgets->[$i][2]->configure(fg => 'red');
#		$widgets->[$i][3]->configure(fg => 'red');
#		$widgets->[$i][4]->configure(fg => 'red');
#	    }
	}
	else {
	    last;
	}

	$i++;
    }

    # disable BrowseEntry widget for non-populated rows

    for $x ( $i .. $MAIN::NUM_ROWS) {
	$widgets->[$x][5]->configure(-state => 'disabled');
    }

    return $self;
}


################################################################################
# connects to DB and handles any errors. Calls various subroutines to setup
# hash tables with data from dictionaries.
################################################################################

sub setupHashTables {

    my ($self) = @_;
    my ($dbh);

    eval {
	$dbh = WrapDBI->connect($self->{dbUser}, {RaiseError => 1});
	expire("Could not connect to database") if !defined $dbh;
	$dbh->{AutoCommit} = 0;

	$self->getSubcloners($dbh);

    };

    if ($@) {
	if ($DBI::err) {
	    $self->expire("$DBI::errstr: $@ Occured in setupHashtables()");
	} else {
	    $self->expire("$@: Occured in setupHashtables()");
	}
    }

    $dbh->disconnect if $dbh;
}
################################################################################
# setup $self->{operatorHash}
################################################################################

sub getSubcloners {

    my ($self, $dbh) = @_;
    my ($arrayOfArrays, $arrayRef);
    my %operatorHash;

    $arrayOfArrays = $dbh->fetch_all(
         "select PERSON.ID_PERSON, PERSON.FORENAME, PERSON.SURNAME
          from   PERSON, TEAM_PERSON_ROLE
          where  TEAM_PERSON_ROLE.ROLETYPE = 'Subcloning' 
          and    TEAM_PERSON_ROLE.ID_PERSON = PERSON.ID_PERSON "); 
 
    foreach $arrayRef (@$arrayOfArrays) {
	$operatorHash{(@$arrayRef[1]." ".@$arrayRef[2])} = @$arrayRef[0];
    }

    $operatorHash{'<nobody>'} = ''; # if user selected someone, then changed 
                                    # there mind.

    $self->{operatorHash} = \%operatorHash;
}
################################################################################
# 
# When trying to set the BrowseEntry widget to 
#     -variable => \$self->{dataStore}->[$x]->[7]
# it did not work correctly. This maybe due to an old Tk version. I have now
# given up on trying to make it work!
################################################################################

sub createTableFrame {

    my ($self, $tf) = @_;
    my $widgets     = $self->{widgets};
    my ($x, $y);

    # x and y are the wrong way round here - y is on x axis....


    for($x = 0; $x <= $MAIN::NUM_ROWS; $x++) {

	# create 4 label widgets
	for($y = 0; $y < 5; $y++) {

	   $self->{widgets}->[$x][$y] = $tf->Label(-relief => 'sunken',
						   -width  => 16,
						   -bg     => 'lightblue');

	   $self->{widgets}->[$x][$y]->grid(-row => $x+1, -column => $y);
	}

	# Entry gadget - who will do the ligations for this DNA Prep.
        # Make sure create label for column heading only.

	if( $x == 0 ) {
	    $self->{widgets}->[$x][$y] = $tf->Label(-text   => "Make Work",
						    -relief => 'sunken',
						    -width  => 18,
						    -bg     => 'lightblue');
	}
	else {
	    # weirdness here with '-variable => \$assignTo[$x]'. 
	    # See above comment
	    $self->{widgets}->[$x][$y] =
		$tf->BrowseEntry(-width    => 16,
				 -relief   => 'sunken',
				 -state    => 'readonly',
				 -variable => \$self->{assignTo}->[$x],
				 -choices  => 
				     [ sort keys %{$self->{operatorHash}} ],
				 -browsecmd => $self->subby("$x"),
				 );
	}

        $self->{widgets}->[$x][$y]->grid(-row    => $x + 1, 
					 -column => $y);
    }

    # put in column headings

    $self->{widgets}->[0][0]->configure(text => "Request",
					bg   => 'grey');
    $self->{widgets}->[0][1]->configure(text => "Description",
					bg   => 'grey');
    $self->{widgets}->[0][2]->configure(text => "Clone",
					bg   => 'grey');
    $self->{widgets}->[0][3]->configure(text => "Species",
					bg   => 'grey');
    $self->{widgets}->[0][4]->configure(text => "Submitter",
					bg   => 'grey');
    $self->{widgets}->[0][5]->configure(text => "Assign to:",
					bg   => 'grey');
}

#
# Used to clear $self->{assignTo}->[$x] to '' when <nobody> is selected on
# BrowseEntry widget.
#

sub subby {
    my $self = shift;
    my $x    = shift;

    return sub {
	if( $self->{assignTo}->[$x] eq '<nobody>' ) {
	    $self->{assignTo}->[$x] = '';
	}
    }
}
    

################################################################################
# show the last $NUM_ROWS of data above the current 'position'
################################################################################

sub pressedUp {

#    print "\nUp was pressed - cursor == $self->{cursor}\n";
    my ($self)     = @_;
    my $cursorToBe;
    my $lastIndex  = $#{$self->{dataStore}};
    my $widgets    = $self->{widgets};

    if( $self->{cursor} <= 1 ) { 
	return; 
    }

    # Save the data entered before scrolling up

    my $i = 1;
    my $x;

    foreach $x ($self->{cursor} .. $self->{cursor} + $MAIN::NUM_ROWS - 1) {
	last if( ! defined($self->{dataStore}->[$x]) );

	$self->{dataStore}->[$x]->[7] = $self->{assignTo}->[$i];
	$i++;
    }

    # if NUM_ROWS == 1, this won't work.
    if( ($self->{cursor} - $MAIN::NUM_ROWS) <= 1 )  {
	$cursorToBe = 0;
    }
    else {
	$cursorToBe = $self->{cursor} - $MAIN::NUM_ROWS;
    }

#    print "cursor = $self->{cursor},, cursorToBe == $cursorToBe\n";

    $i = 1;

    foreach $x ($cursorToBe .. $self->{cursor} - 1) {

	last if( ! defined($self->{dataStore}->[$x]) );

	$widgets->[$i][0]->configure(text => "$self->{dataStore}->[$x]->[0]");
	$widgets->[$i][1]->configure(text => "$self->{dataStore}->[$x]->[1]");
	$widgets->[$i][2]->configure(text => "$self->{dataStore}->[$x]->[2]");
	$widgets->[$i][3]->configure(text => "$self->{dataStore}->[$x]->[3]");
	$widgets->[$i][4]->configure(text => "$self->{dataStore}->[$x]->[4]");

	if( $self->{dataStore}->[$x]->[5] == 1 ) {
	    $widgets->[$i][0]->configure(fg => 'red');
	    $widgets->[$i][1]->configure(fg => 'red');
	    $widgets->[$i][2]->configure(fg => 'red');
	    $widgets->[$i][3]->configure(fg => 'red');
	    $widgets->[$i][4]->configure(fg => 'red');
	}
	else {
	    $widgets->[$i][0]->configure(fg => 'black');
	    $widgets->[$i][1]->configure(fg => 'black');
	    $widgets->[$i][2]->configure(fg => 'black');
	    $widgets->[$i][3]->configure(fg => 'black');
	    $widgets->[$i][4]->configure(fg => 'black');
	}

	$self->{assignTo}->[$i] = $self->{dataStore}->[$x]->[7];
	$widgets->[$i][5]->configure(-state => 'normal');
	$i++;
    }

    # don't think this code will ever execute, since we are going up there
    # must be data.

    for $x ( $i .. $MAIN::NUM_ROWS) {
	$widgets->[$x][5]->configure(-state => 'disabled');
    }

    $self->{cursor} = $cursorToBe;
}

################################################################################
# show the next $NUM_ROWS of data below the current position
################################################################################

sub pressedDown {

#    print "\nDown was pressed. cursor == $self->{cursor}\n";
    my ($self)    = @_;
    my $lastIndex = $#{$self->{dataStore}};
    my $i         = 1;  # starts at one 'cos BrowseEntry widget starts there.
    my $x         = 0;
    my $widgets   = $self->{widgets};

    if( ($self->{cursor} + $MAIN::NUM_ROWS) < ($lastIndex + 1)) {

	# Save operator names to $self->{dataStore}
    
	foreach $x ($self->{cursor} .. $self->{cursor} + $MAIN::NUM_ROWS - 1) {
	    $self->{dataStore}->[$x]->[7] = $self->{assignTo}->[$i];
	    $i++;
	}

	$self->{cursor} += $MAIN::NUM_ROWS;
#	print "Updated cursor == $self->{cursor} , last index == $lastIndex\n";
    }
    else {
#	print "can't go down - cursor at self->{$cursor}\n";
	return;
    }

    # redisplay the the data from cursor to cursor + NUM_ROWS
    # loop for each member in the dataStore.

    my ($cloneName, $prepNumber, $priority);

    $i = 0;

    foreach $x ($self->{cursor} .. ($self->{cursor} + $MAIN::NUM_ROWS - 1)) {

	++$i;

	if( ! defined($self->{dataStore}->[$x]) ) {
	    $widgets->[$i][0]->configure(text => "");
	    $widgets->[$i][1]->configure(text => "");
	    $widgets->[$i][2]->configure(text => "");
	    $widgets->[$i][3]->configure(text => "");
	    $widgets->[$i][4]->configure(text => "");
	    $widgets->[$i][5]->configure(-state => 'disabled');
	    $self->{assignTo}->[$i] = "";

	    next;
	}

	$widgets->[$i][0]->configure(text => "$self->{dataStore}->[$x]->[0]");
	$widgets->[$i][1]->configure(text => "$self->{dataStore}->[$x]->[1]");
	$widgets->[$i][2]->configure(text => "$self->{dataStore}->[$x]->[2]");
	$widgets->[$i][3]->configure(text => "$self->{dataStore}->[$x]->[3]");
	$widgets->[$i][4]->configure(text => "$self->{dataStore}->[$x]->[4]");

	if( $self->{dataStore}->[$x]->[5] == 1 ) {
	    $widgets->[$i][0]->configure(fg => 'red');
	    $widgets->[$i][1]->configure(fg => 'red');
	    $widgets->[$i][2]->configure(fg => 'red');
	    $widgets->[$i][3]->configure(fg => 'red');
	    $widgets->[$i][4]->configure(fg => 'red');
	}
	else {
	    $widgets->[$i][0]->configure(fg => 'black');
	    $widgets->[$i][1]->configure(fg => 'black');
	    $widgets->[$i][2]->configure(fg => 'black');
	    $widgets->[$i][3]->configure(fg => 'black');
	    $widgets->[$i][4]->configure(fg => 'black');
	}

	$self->{assignTo}->[$i] = $self->{dataStore}->[$x]->[7];
	$widgets->[$i][5]->configure(-state => 'normal');
    }
}


################################################################################
# Connect to DB - wrapper for calling &printWorkSheets()
################################################################################

sub pressedMakeWork {

    my ($self) = @_;
    my $dbh;
    # connect to DB and pass $dbh into printWorkSheets

    eval {
	$dbh = WrapDBI->connect($self->{dbUser}, {RaiseError => 1});
	expire("Could not connect to database") if !defined $dbh;
	$dbh->{AutoCommit} = 0;

	$self->printWorkSheets($dbh);
    };

    if ($@) {
	$self->showError("$@\n");
    }

    $dbh->disconnect if $dbh;
}

################################################################################
# work down the 'Assign To' column and look for a persons name not in the hash
# %alreadyAssigned. If not, look for more occurances and push details of each
# clone/prep number onto @workForPerson.
#
# When the end of the list is found it writes everything stored in 
# @workForPerson to the printer via genscript (to get landscape mode).
#
# It repeats the whole process for the next person.
################################################################################

sub printWorkSheets {

    my ($self, $dbh)     = @_;

    my %alreadyAssigned;
    my $firstIndex     = 0;
    my $printer        = $ENV{'PRINTER'};
    my $workSheetCount = 0;

    # Save operator names to $self->{dataStore}
    
    my ($x, $i);
    $i = 1;

    foreach $x ($self->{cursor} .. $self->{cursor} + $MAIN::NUM_ROWS - 1) {
	$self->{dataStore}->[$x]->[7] = $self->{assignTo}->[$i];
	$i++;
    }

    if( $printer eq '' ) {
        $printer = "d324bw"; # one nearest Matt Jones.
	warn "Using default printer 'd324bw' \n";
    }
    else {
	warn "Using printer '$printer'\n";
    }

    # get clones to fragment. If a person has been assigned to a clone, collect
    # all the others he has been assigned.

    foreach my $jobArray (@{$self->{dataStore}}) {

	my $person = $jobArray->[7];
	my @workForPerson;

my $id_request;           # These variables are used in the
my $requested_by;         # report generated off the Generate Work Sheets button
my $SIL_type;
my $cloneName;
my $speciesName;
my $chromosome;
my @frags;
my ($PCRproductSize,
    $PCRforwardPrimer,
    $PCRreversePrimer,
    $PCRKinase,
    $PCRpurify);

	# if person not already been assigned work already, get all work for 
	# other clones that his name is against.

	my $first = 0;

	if( ($alreadyAssigned{$person} == 0) && ($person ne '') ) {
	    my $rowArray;

	    for(my $x = $firstIndex;
		$x < scalar(@{$self->{dataStore}});
		++$x  ) {

		$rowArray = @{$self->{dataStore}}->[$x];

		if( $person eq @$rowArray->[7] ) {
		    push @workForPerson, $rowArray;
		}
	    }

	    $alreadyAssigned{$person} = 1;
	}

	# print a report for this person if he has work assigned.

	select(WORKSHEET);
#	select(STDOUT);

	++$firstIndex;

#	if( scalar(@workForPerson) > 0 ) {

	unless( scalar(@workForPerson) > 0 ) {
	    next;
	}

	open(WORKSHEET,
#		 "| genscript  -P$printer -b 'Work for: $person\n".
#		 "      Date assigned: $self->{date}'");
		 "| more");

	warn "\n\nWork for: $person\n";

	my $width       = 20;
	my $jobCount    = 0;
	my $jobsPerPage = 3;

	foreach my $work ( @workForPerson ) {

	    my ($consensus_file, $gap_coord, $enzyme_name);

	    $id_request   = $work->[0];
	    $SIL_type     = $work->[1];
	    $cloneName    = $work->[2];
	    $speciesName  = $work->[3];
	    $requested_by = $work->[4];
	    $chromosome   = $work->[5];

	    my $comment   = $dbh->fetch_scalar("
                select REMARK
                from   SIL_REQUEST
                where  ID_REQUEST = $id_request");

	    # linefeed needed?

	    if( $jobCount < $jobsPerPage ) {
		++$jobCount;
	    }
	    else {
		printf WORKSHEET "\f" ;
		$jobCount = 1;
		++$workSheetCount;
	    }

	    if( $jobCount != 1 ) {
		printf "\n";
		printf "----------------------------------------".
		        "---------------------------------------".
			"--------------\n\n" ;
	    }

	    my $arrayOfArrays1 = $dbh->fetch_all("
		    select FWD_PRIMER, REV_PRIMER, EST_PRODUCT_SIZE_KB,
		           GEL_PURIFY, WITH_KINASE
	            from   SIL_PCR
		    where  ID_REQUEST = $id_request");

	    my $arrayRefPCR   = $arrayOfArrays1->[0];

	    if( defined($arrayRefPCR) ) {
		$PCRforwardPrimer = $arrayRefPCR->[0];
		$PCRreversePrimer = $arrayRefPCR->[1];
		$PCRproductSize   = $arrayRefPCR->[2];
		$PCRpurify        = $arrayRefPCR->[3];
		$PCRKinase        = $arrayRefPCR->[4];
	    }

	    my $arrayOfArrays2 = $dbh->fetch_all("
                    select CONSENSUS_FILE, GAP_COORDINATE, ENZYMENAME
                    from   SIL_RESTRICTION
                    where  ID_REQUEST = $id_request");

	    my $arrayRefRestrict  = $arrayOfArrays1->[0];

	    if( defined($arrayRefRestrict) ) {
		$consensus_file = $arrayRefRestrict->[0];
		$gap_coord      = $arrayRefRestrict->[1];
		$enzyme_name    = $arrayRefRestrict->[2];
	    }

	    my $arrayOfArrays3 = $dbh->fetch_all("
                select FROM_BP, TO_BP
                from   SIL_INSERTSIZE
                where  ID_REQUEST = $id_request");

	    my $fragCount = 0;

	    foreach my $row (@{$arrayOfArrays3}) {
		$frags[$fragCount][0] = $row->[0];
		$frags[$fragCount][1] = $row->[1];

		++$fragCount;
	    }

	    printf "\n\n\n";
	    printf "Request   : %-${width}d \n", $id_request   ;
	    printf "Submitter : %-${width}s \n", $requested_by ;
	    printf "Clone     : %-${width}s \n", $cloneName    ;
	    printf "Species   : %-${width}s \n", $speciesName  ;
	    printf "Chromosome: %-${width}s \n", $chromosome   ;
	    printf "SIL Type  : %-${width}s \n", $SIL_type     ;
	    printf "\n", ;

	    if(   defined($arrayRefPCR)
	       && (   $SIL_type ne 'Genome Walk'
		   && $SIL_type ne 'Oligo Screening' )) {

		printf "PCR:\n", ;
		printf "     Est. Product Size: %-${width}d\n", $PCRproductSize;
		printf "     Forward Primer   : %-${width}s\n",
		       $PCRforwardPrimer;
		printf "     Reverse Primer   : %-${width}s\n",
		       $PCRreversePrimer;
		printf "     Kinase           : %-${width}s\n", $PCRKinase;
		printf "     Purify from Gel  : %-${width}s\n", $PCRpurify;
	    }

	    if( defined($arrayRefPCR) && $SIL_type eq 'Genome Walk' ) {
		printf "\n", ;
		printf "Genome Walk:\n", ;
		printf "     Inner Primer: $PCRreversePrimer\n", ;
		printf "     Outer Primer: $PCRforwardPrimer \n",;
		printf "\n", ;
	    }

		
	    if( defined($arrayRefPCR) && $SIL_type eq 'Oligo Screening' ) {
		printf "\n", ;
		printf "Oligo Screening:\n", ;
		printf "     Est. Product Size : %-${width}d\n",$PCRproductSize;
		printf "     Forward Primer: %-${width}s\n",
		                     $PCRforwardPrimer;
		printf "     Reverse Primer: %-${width}s \n",
		                     $PCRreversePrimer;
		printf "\n", ;
	    }

	    if( $SIL_type eq 'Restriction' ) {
		printf "\n", ;
		printf "Restriction:\n", ;
		printf "     Consensus file  : $consensus_file\n", ;
		printf "     Gap Coord       : $gap_coord\n", ;
		printf "     Suggested Enzyme: $enzyme_name\n", ;
		printf "\n", ;
		printf "\n", ;
	    }

	    printf "\n";
	    printf"Fragments:\n";

	    for ( 0..$#frags) {
		printf "    Fragment ".($_ + 1)."  From %-6s   To %-6s\n",
		       $frags[$_][0], $frags[$_][1];
	    }

	    printf "\n";
	    printf "Finishers comment: $comment \n";
	}

	close(WORKSHEET);
    }

    warn "Printing complete\n";
    $self->showInfo("Printing complete. Please collect $workSheetCount ".
		    "work sheet(s) from the printer");
}


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

sub showError {

    my ($self, $message) = @_;
    warn "ERROR: $message\n";

    my $dialog = $self->{mw}->Dialog (
				      title          => "Error",
				      text           => "$message",
				      default_button => '1',
				      buttons        => ['OK']);
    $dialog->Show();
}


################################################################################
# shows an info box.
################################################################################

sub showInfo {

    my ($self, $message) = @_;

    my $dialog = $self->{mw}->Dialog (
				      title          => "Message",
				      text           => "$message",
				      default_button => '1',
				      buttons        => ['OK']);
    $dialog->Show();
}


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

sub expire($) {

    my ($self, $errorMsg,$dbh) = @_;

    $dbh->disconnect if $dbh; 
    warn "ERROR: $errorMsg\n";
    die;
}


################################################################################
# The report generated for each Sub cloner.
################################################################################

format WORKSHEET_TOP =
#format STDOUT_TOP =
.

format WORKSHEET =
#format STDOUT = 
.


################################################################################
# DESTROY !!!
################################################################################

DESTROY {
    my $self = shift;
    warn "Wrong type passed to SelectJobs->DESTROY '$self'" unless ref $self;
    --$instanceCount;
}


1;



