#!/usr/local/bin/perl 
#######################################################################
# This software has been created by Genome Research Limited (GRL).    # 
# GRL hereby grants permission to use, copy, modify and distribute    # 
# this software and its documentation for non-commercial purposes     # 
# without fee at the user's own risk on the basis set out below.      #
# GRL neither undertakes nor accepts any duty whether contractual or  # 
# otherwise in connection with the software, its use or the use of    # 
# any derivative, and makes no representations or warranties, express #
# or implied, concerning the software, its suitability, fitness for   #
# a particular purpose or non-infringement.                           #
# In no event shall the authors of the software or GRL be responsible # 
# or liable for any loss or damage whatsoever arising in any way      # 
# directly or indirectly out of the use of this software or its       # 
# derivatives, even if advised of the possibility of such damage.     #
# Our software can be freely distributed under the conditions set out # 
# above, and must contain this copyright notice.                      #
#######################################################################


push(@INC,"$ENV{BADGER}/bin");
unshift(@INC,split(/:/,"$ENV{'INC_PATH'}"));


print @INC , "\n" ;
use Tk;
use Tk::Dialog;
use Tk::ErrorDialog;
require Qplot;
require ListPick;
require ByTempl;
require assem_qual;
require InfoWin;
require FlashWidget;
require AniCursor;

#################################################################################################
# CAF support
require "badgerGetOpt.pl";
require "exectools.pl";
require "caftools.pl";

#################################################################################################
use strict;
#################################################################################################
# Global Data

my %ContigObjs;
my %Good;			# Good Reads
my %GoodObjs;			# Drawn Good Read ids and names
my %GoodHid;			# Original config for GoodObjs.
my %Bad;			# Bad Reads
my %BadObjs;
my %BadHid;
my %Uglys;			# Lone Reads
my %UglyObjs;
my %UglyHid;
my $limit = 3000;     # separation limit


#################################################################################################
#################################################################################################
## mainwindow 'n stuff 

my $MW = MainWindow->new; 
my $c;
$MW->title('Deviant : Quality by Read Pairs');
$MW->iconname('Deviant');
my $FONT = '8x13';
my $FONTs = '6x10';

$MW->wm("minsize",  100, 100);


#################################################################################################
## Menus

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

## File Menu

my $menuBar_file = $menuBar->Menubutton(
    -text      => 'File',
    -underline => 0,
);
#$menuBar_file->command(
#    -label     => 'Open',
#    -underline => 0,
#    -command   => \&Open,
#);
$menuBar_file->command(
    -label     => 'Dump',
    -underline => 0,
    -command   => \&Dump,
);
$menuBar_file->separator;
$menuBar_file->command(
    -label     => 'Quit',
    -underline => 0,
    -command   => \&exit,
);
$menuBar_file->pack(-side => 'left');

## Edit menu ..

my $menuBar_edit=$menuBar->Menubutton(
    -text     => 'Edit',
    -underline => 0,
);
$menuBar_edit->command(
    -label     => 'Find Template...',
    -underline => 0,
    -command   => \&FindTemplate,
);
$menuBar_edit->pack(-side => 'left');
## View Menu

my $menuBar_view=$menuBar->Menubutton(
    -text     => 'View',
    -underline => 0,
#    -command   => [\&view_widget_code, __FILE__],
);

$menuBar_view->separator;

############### cascades ###################

my $menuVis = 'Visible Plots';
$menuBar_view->cascade(-label => $menuVis,-underline => 0);
my $cm = $menuBar_view->cget(-menu);
my $cc = $cm->Menu;
my @Show = (1,1,1,1);
my $lasty;

$menuBar_view->entryconfigure($menuVis,-menu => $cc);

$cc->checkbutton(-label=> 'Quality',-variable => \$Show[0],-command => \&Show);
$cc->checkbutton(-label=> 'Good Read Pairs',-variable => \$Show[1],-command => \&Draw_Reads);
$cc->checkbutton(-label=> 'Bad Read Pairs',-variable => \$Show[2],-command => \&Draw_Reads);
$cc->checkbutton(-label=> 'Bad / Lone Reads',-variable => \$Show[3],-command => \& Draw_Reads);

$menuBar_view->pack(-side => 'left');

my $menuBar_Prefs=$menuBar->Menubutton(
     -text     => 'Preferences',
    -underline => 0,
 #   -command   => [\&SetLimit, __FILE__],
);
$menuBar_Prefs->command(
    -label     => 'Separation...',
    -underline => 0,
    -command   => \&GetLimit,
);
$menuBar_Prefs->separator;
$menuBar_Prefs->pack(-side => 'left');

###################################################################################################
## Canvas stuff .. (created in sub )
##
## 1000 width by 500 height....
## window view is 800 by 300 ...
my $MW_vscroll;
my $MW_hscroll; 

# Two arrays of data series ... only.. 

my @F;
my %D = (0,0);      
my %C = (0,0);


#################################################################################################
# Command-line

my $prog = "deviant";
my $vers="1.0";
my $usage= "Usage: $prog -caf CAFFILE -maxsep 3000";
my $caffile="";
my $gapfile="";
my $version="";
my $gap="";
my $templatesfile="";

my $opts = {
	"-gap" => { 
	    "type" => "text",
	    "var" => \$gapfile,
	    "help" => "GAP database name",
	},	
	"-version" => { 
	    "type" => "text",
	    "var" => \$version,
	    "help" => "GAP version",
	    "def" => "0",
	},	
	"-caf" => { 
	    "type" => "text",
	    "var" => \$caffile,
	    "help" => "CAF database name",
	},	
	"-templates" => { 
	    "type" => "text",
	    "var" => \$templatesfile,
	    "help" => "Templates file name",
	},	
	"-maxsep" => {
	    "type" => int,
	    "var" => \$limit,
	    "def" => 3000,
	    "help" => "Max separation between reads off same template",
	},
    };


&badgerGetOpt($prog,$usage,$opts) && die "Quit\n";

#################################################################################################
# deal with CAF issues

if ( $gapfile ) {
    $gap = $gapfile . "." . $version;
    die  "$gap: no such File\n" if ( ! -f $gap );   
    $caffile = $gap . ".caf." . $$;
    &execute( "gap2caf -project $gapfile -version $version -ace $caffile", $caffile );
}

if ( $caffile ) {
# we have a caf file to parse

    die "$caffile: no such File\n" if ( ! -f $caffile );   
    $templatesfile = "$caffile.templates.$$";
    &execute( "templates < $caffile > $templatesfile", $templatesfile );
}

if ( $templatesfile )
{
    &Open( $templatesfile, $limit );
}
else
{
    die "No file\n";
}

system("/bin/rm *.$$");


###################################################################################################
## Subs
sub Deviant{

    my $assmax;

    $assmax = &ByTempl::Get_Assem_Max;
    &Draw_Reads;
    &Draw_Contig($assmax); 
    &Draw_Quality(1);
}   
###################################################################################################
sub Show{

    if(!$Show[0])
    {
	&Qplot::Hide("*");
    }else {
	&Qplot::UnHide("*");
    }

}
###################################################################################################
sub FindTemplate{
 
    my $picked;
    my @flash;
    my @list = sort &ByTempl::Get_Templ_Array;
    my $picked = &ListPick::ListPick($MW,'Pick the template you wish to highlight ',@list);
    
 #  &Qplot::Hide("*");  
    &AniCursor::StartCursor($MW,$c);
    foreach (keys(%GoodObjs)){ if ($GoodObjs{$_} eq $picked){push(@flash,$_);}} 
    foreach (keys(%BadObjs)){push(@flash,$_) if ($BadObjs{$_} eq $picked); }
    foreach (keys(%UglyObjs)){push(@flash,$_) if ($UglyObjs{$_} eq $picked);} 
    &AniCursor::StopCursor;
    &FlashWidget::StartFlashing($MW,$c,@flash);
    
    undef(@flash);
}
###################################################################################################
sub Open{

    my $assmax;
    my @assData;
    my ($tplates, $lim) = @_;
 
    # read in the initial data ..
   
    &ByTempl::Read_Templ($tplates,$lim);
    &Deviant;
}
###################################################################################################

###################################################################################################
sub Draw_Quality{

   my ($getdata) = @_;
   my $assmax = &ByTempl::Get_Assem_Max;
   my @assData = &ByTempl::Get_Assem;
   # $c = &ClearWin;
   &Draw_Contig($assmax); 

   if($Show[0])
   {
       if($getdata)
       {
	   &assem_qual::Quality($assmax,@assData);  # takes to long
	   
	   %D = &assem_qual::Get_Good;
	   %C = &assem_qual::Get_Bad;
       }
    &Qplot::Set_sa(%D); # good
    &Qplot::Set_sb(%C); # bad 
    &Qplot::Plot_series($c,1550,220);
    }
    
}

##################################################################################################
sub Dump{
  my @Data = &ByTempl::Get_Assem;


}
###################################################################################################
sub Draw_Reads{
  
    my $y =300;
    my $oy = 300;
    my @Data = &ByTempl::Get_Assem;
    my $assmax = &ByTempl::Get_Assem_Max;
    my @ids;

     $c = &ClearWin;
     &Draw_Contig($assmax);

    &AniCursor::StartCursor($MW,$c);
    if($Show[1])
    {
	$y = &Draw_good($y,@Data);
	@ids = &Draw_keylabel($oy,$y,"Good Read Pairs","green");
        foreach (@ids){$GoodObjs{$_} = 'label';}
	$oy = $y+20;
    }
    if($Show[2])
    {
	$y = &Draw_bad($oy,@Data);
	@ids = &Draw_keylabel($oy,$y,"Bad Read Pairs","red");
        foreach (@ids){$BadObjs{$_} = 'label';}
	$oy = $y+20;
    }
    if($Show[3])
    {
	$y = &Draw_ugly($oy,@Data);
	@ids = &Draw_keylabel($oy,$y,"Lone Reads","blue");
        foreach (@ids){$UglyObjs{$_} = 'label';}
    }	
    &AniCursor::StopCursor($MW,$c);			 
}
##########################################################################################################
sub Draw_keylabel{

 my ($y1,$y2,$text,$col) = @_;
 my $len = length($text);
 my $start = int(abs($y2 - $y1)/10)+$y1;
 my $i;
 my $scalfact = ($start+($len *8));
 my @ids;

 $ids[0] = $c->create('line', 30, $y1, 30,$y2, -width => 2,-fill => $col);
 $ids[1] = $c->create('line', 30, $y1, 35,$y1, -width => 2,-fill => $col);
 $ids[2] = $c->create('line', 30, $y2, 35,$y2, -width => 2,-fill => $col);

 if($scalfact <= $y2)
 {
    for($i=0; $i<$len; $i++)
    {
     $ids[3+$i] = $c->create('text',10,$start + (8 * $i),-text => substr($text,$i,1), -font => $FONTs, -fill => 'blue');
     }
  }
 @ids;
}
##########################################################################################################
sub read_info{
    my ($c,$data) = @_;
    my @j = @{$data};
    my $left;
    my $right;
    my $fwd =0;
    my @vals;
    my $out;
    my $size;

    &InfoWin::Create_InfoWin;
    &InfoWin::ClearWin;
    my $canv = &InfoWin::GetInfoCanv;

    if($j[5] < $j[6]){$left = 50;$right = 150;}else{$left = 150;$right=50;}
  #  &FlashWidget::StopFlashing;
    &InfoWin::AddStuff (&InfoWin::InfoFR_box($canv,$left,20,$right,50,$j[7],$j[8],$j[9]));
    $out = $j[0];
    &InfoWin::AddStuff ($canv->create('text', 30, 10, -text =>$out, -font => $FONT,-fill => 'red'));
    $out = $j[11];
    &InfoWin::AddStuff ($canv->create('text', 90, 10, -text =>$out, -font => $FONTs,-fill => 'black'));
    $out = $j[10];
    &InfoWin::AddStuff ($canv->create('text', 160, 10, -text =>$out, -font => $FONT,-fill => 'black'));
    $out = "fwd =>>\tfwd <<=\trev =>>\trev <<=";
    &InfoWin::AddStuff ($canv->create('text', 80, 60, -text =>$out, -font => $FONTs,-fill => 'black'));
    $out = "$j[1]\t$j[2]\t$j[3]\t$j[4]";
    &InfoWin::AddStuff ($canv->create('text', 80, 70, -text =>$out, -font => $FONTs,-fill => 'dark green'));
    $out = "Size = $j[12] bp";
     &InfoWin::AddStuff ($canv->create('text',40, 90, -text =>$out, -font => $FONTs,-fill => 'dark green'));
    $canv->pack;
}
##########################################################################################################

sub Draw_good {
    my ($y, @Data) =@_;
    my $line;
    my @rows;
    my $left;
    my $right;
    my $lastright = 50;
    my $xmax;
    my @arr;
    my $slot;
    my $l;
    my $r;
    my $l1;
    my $r1;
    my $maxy =0;
    my $sy;
    my $lpr;
    my $rpr;
   

    @Data = reverse sort by_rs2 @Data;
    @arr = @{$Data[0]};
    
    if($arr[11] < $arr[12]){$xmax = $arr[12];}else{$xmax = $arr[11];}
 
    @Data = sort by_ls1 @Data;
    &Qplot::Set_xxt_yxt(1550,220);
    
    
    foreach $line (@Data)
    {
     if(($$line[7] == 1) && ($$line[6] ==1) && ($$line[5] == 1) && ($$line[8] == 0))      # in limit
      {
     
 
       $left = &Qplot::dmapx($$line[9],$xmax,0);
       $l1 = &Qplot::dmapx($$line[10],$xmax,0);
       $right = &Qplot::dmapx($$line[11],$xmax,0);
       $r1 = &Qplot::dmapx($$line[12],$xmax,0);
 
       my (@Data) =@_;
   
       if (($slot = &Slot_fit($left,@rows)) != -1)
          {
	   $rows[$slot] = $right;
	   $sy= $y + ($slot * 10);
          }else {
	         push(@rows,$right);
	         $sy = $y + (($#rows) * 10);
                 }
      my $fwd =0;

      if($$line[15] eq "forward"){$fwd = 1;}
      $GoodObjs{$c->create('line', $left, $sy, $right,$sy, -width => 2,-fill => 'dark green')} = $$line[0];
      my $id;
      my @Linfo;
      my @Rinfo;

      $id = &FRead_box($left,$sy-3,$l1,$sy+3,$fwd,$c,$$line[5],$$line[8]);
      $GoodObjs{$id} = $$line[0];
      push (@Linfo,$$line[0],$$line[1],$$line[2],$$line[3],$$line[4],
                   $left,$l1,$fwd,$$line[5],$$line[8],$$line[13],$$line[15],int(abs($$line[9]-$$line[10]))); 
      $c->bind($id,'<Any-Enter>'=>[\&read_info,\@Linfo]);
 
      if($$line[16] eq "forward"){$fwd = 1;}else{$fwd =0;}
 
      $id = &FRead_box($right,$sy-3,$r1,$sy+3,$fwd,$c,$$line[5],$$line[8]);
      $GoodObjs{$id} = $$line[0];
      push (@Rinfo,$$line[0],$$line[1],$$line[2],$$line[3],$$line[4],
                    $right,$r1,$fwd,$$line[5],$$line[8],$$line[14],$$line[16],int(abs($$line[9]-$$line[10]))); 
      $c->bind($id,'<Any-Enter>'=>[\&read_info,\@Rinfo]);
      if ($maxy < $sy){$maxy = $sy;}
      }
    
    } 
 $lasty = $maxy;    
 $maxy;
}

#####################################################################################################
sub Draw_bad {
    my ($y, @Data) =@_;
    my $line;
    my @rows;
    my $left;
    my $right;
    my $lastright = 50;
    my $xmax;
    my @arr;
    my $slot;
    my $maxy;
    my $sy;
    my $l1;
    my $r1;  

    @Data = reverse sort by_rs2 @Data;
    @arr = @{$Data[0]};
    
    if($arr[11] < $arr[12]){$xmax = $arr[12];}else{$xmax = $arr[11];}
 
    @Data = sort by_ls1 @Data;
    &Qplot::Set_xxt_yxt(1550,220);
    
    
    foreach $line (@Data)
    {
     if(($$line[5] == 1) && (($$line[6] == 0) || ($$line[7] == 0)))      # in limit
      {
     
       $left = &Qplot::dmapx($$line[9],$xmax,0);
       $l1 = &Qplot::dmapx($$line[10],$xmax,0);
       $right = &Qplot::dmapx($$line[11],$xmax,0);
       $r1 = &Qplot::dmapx($$line[12],$xmax,0);
 
       my (@Data) =@_;
   
       if (($slot = &Slot_fit($left,@rows)) != -1)
          {
	   $rows[$slot] = $right;
	   $sy = $y + ($slot * 10);
          }else {
	         push(@rows,$right);
	         $sy = $y + (($#rows) * 10);
                 }
      my $fwd =0;
      my $id;
      my @Linfo;
      my @Rinfo;

      if($$line[15] eq "forward"){$fwd = 1;}
       $BadObjs{$c->create('line', $left, $sy, $right,$sy, -width => 2,-fill => 'dark red')} = $$line[0];
      
     
       $BadObjs{$id = &FRead_box($left,$sy-3,$l1,$sy+3,$fwd,$c,$$line[5],$$line[8])} = $$line[0];
      push (@Linfo,$$line[0],$$line[1],$$line[2],$$line[3],$$line[4],
                   $left,$l1,$fwd,$$line[5],$$line[8],$$line[13],$$line[15],int(abs($$line[9]-$$line[10]))); 
      $c->bind($id,'<Any-Enter>'=>[\&read_info,\@Linfo]);

      if($$line[16] eq "forward"){$fwd = 1;}else{$fwd =0;}
       $BadObjs{ $id = &FRead_box($right,$sy-3,$r1,$sy+3,$fwd,$c,$$line[5],$$line[8])} = $$line[0];
       push (@Rinfo,$$line[0],$$line[1],$$line[2],$$line[3],$$line[4],
	     $right,$r1,$fwd,$$line[5],$$line[8],$$line[14],$$line[16],int(abs($$line[9]-$$line[10]))); 
       $c->bind($id,'<Any-Enter>'=>[\&read_info,\@Rinfo]);
       if(defined($sy)){if ($maxy < $sy){$maxy = $sy;}}
      }
    }    
   
 $maxy;
}
######################################################################################################
sub Draw_ugly {
    my ($y, @Data) =@_;
    my $line;
    my @rows;
    my $left;
    my $right;
    my $lastright = 50;
    my $xmax;
    my @arr;
    my $slot;
    my $maxy;
    my $sy;
    my $r;
    my $r1;  
    my $l1;
    my $maxy =0;

    @Data = reverse sort by_rs2 @Data;
    @arr = @{$Data[0]};
    
    if($arr[11] < $arr[12]){$xmax = $arr[12];}else{$xmax = $arr[11];}
 
    @Data = sort by_ls1 @Data;
    &Qplot::Set_xxt_yxt(1550,220);
    
    
    foreach $line (@Data)
    {
     if(($$line[5] == 0) && (($$line[6] == 0) || ($$line[7] ==0) || ($$line[8] ==0)))      # in limit
      {
     
       $left = &Qplot::dmapx($$line[9],$xmax,0);
       $l1 = &Qplot::dmapx($$line[10],$xmax,0);
       $right = &Qplot::dmapx($$line[11],$xmax,0);
       $r1 = &Qplot::dmapx($$line[12],$xmax,0);
 
       my (@Data) =@_;
   
       if (($slot = &Slot_fit($left,@rows)) != -1)
          {
	   $rows[$slot] = $right;
	   $sy= $y + ($slot * 10);
          }else {
	         push(@rows,$right);
	         $sy = $y + (($#rows) * 10);
                 }
      my $fwd =0;
      my $id;
      my @Sinfo;

     # $c->create('line', $left, $sy, $right,$sy, -width => 2,-fill => 'dark red');
      
      if($$line[15] eq "forward"){$fwd = 1;}
       $UglyObjs {$id = &FRead_box($left,$sy-3,$l1,$sy+3,$fwd,$c,$$line[5],$$line[8])} = $$line[0];
      push (@Sinfo,$$line[0],$$line[1],$$line[2],$$line[3],$$line[4],
	     $right,$r1,$fwd,$$line[5],$$line[8],$$line[14],$$line[16],int(abs($$line[9]-$$line[10])));
      $c->bind($id,'<Any-Enter>'=>[\&read_info,\@Sinfo]);
      if ($maxy < $sy){$maxy = $sy;}
      }
    }    
    $lasty = $maxy;
 $maxy;
}
#####################################################################################################
sub FRead_box {

my ($x1,$y1,$x2,$y2,$fwd,$canv,$hfr,$bad) = @_; 

my $col;
my $h = int((abs($x1-$x2))/2);
my $circ;
my $bid;

if ($x1 < $x2){$h += $x1;$circ = $x1-5;}else{$h += $x2;$circ = $x1+5;}
if(!$fwd){$col = 'yellow';}else{$col = 'blue';}

$bid= $canv->create('polygon',$x1,$y1,$h,$y1,$x2,$y1+3,$h,$y2,$x1,$y2,$x1,$y1,
                  -width=>1,-outline=>'black',-fill=> $col);
    

if($bad)     # internally inconsistent....
 {
  $canv->create('oval',$x1,$y1-1,$circ,$y2+1,-width=> 1,-outline => 'black',-fill=> 'black'); 
  }
$bid;
}
#####################################################################################################
sub Slot_fit{
    my ($l,@slots) = @_;
    my $fits = -1;
    my $slot =0;
    my $r;

   foreach $r (@slots)
   {
       if($l > ($r + 20)){$fits = $slot;last;}
       $slot++;       
   }
    $fits;
}
######################################################################################################
sub by_ls1{
    $$a[9]<=>$$b[9];
}
sub by_rs2 {
    $$a[12]<=>$$b[12];
}
############################################################################################################
sub Draw_Contig{
  
   my ($end) = @_;
   my $line;
   my %cord ;
   my $y = 280;
   my @Assem = &ByTempl::Get_ContigOrd;
   my $x;
   my $x2;
   my $name;
   my $oname = "";
   my $x3;
   my $num;
   &Qplot::Set_xxt_yxt(1550,220);
   $x = Qplot::dmapx(1,$end,0);
   %cord = &ByTempl::Calc_offsets(@Assem);
   

   foreach $line (@Assem)
   {
    
    $name = $cord{$line};
    $num = ($name =~ /Contig(\dt)/);
    $x2 = Qplot::dmapx($name,$end,0);
  
    $c->create('line', $x, $y, $x2, $y, -width => 2,-fill => 'blue');
    $x3 = int(($x2-$x)/3) + $x;	# 
    if($x3 > length($oname) * 8){
    $c->create('text', $x3, $y-5, -text => $oname, -font => $FONTs,-fill => 'red');
    }
    $c->create('line', $x, $y-5, $x, $y+5, -width => 2,-fill => 'blue');
    $x = $x2;
    $oname = $line;   
   }
    $x2 = Qplot::dmapx($end,$end,0);
    $c->create('line', $x, $y, $x2, $y, -width => 1,-fill => 'blue');

}
###################################################################################################
sub SetLimit{
    my ($lim) =@_;

   my @assData;
   # read in the initial data ..
   

   my $assmax = &ByTempl::Get_Assem_Max;
   @assData = &ByTempl::Get_Assem;
   &ByTempl::ChangeLimit($lim,\@assData);

   &Deviant;
   
}
###################################################################################################
sub ClearWin{

    if($c){$c->destroy;undef($c);}
    my $c = $MW->Canvas(
			-width        => 800,
			-height       => 300,
			-relief       => 'sunken',
			-bd           => 2,
			-scrollregion => ['-0c', '-0c', '50c', '50c'],
			);
    $c->configure(-background => 'light grey');
    if($MW_vscroll) {$MW_vscroll->destroy;}
    if($MW_hscroll) {$MW_hscroll->destroy;}
    $MW_vscroll = $MW->Scrollbar(-command => [$c => 'yview']);
    $MW_hscroll = $MW->Scrollbar(-command =>  [$c => 'xview'], -orient => 'horiz');
    $c->configure(-xscrollcommand => [$MW_hscroll => 'set'], # 
		  -yscrollcommand => [$MW_vscroll => 'set']); # 
    $MW_vscroll->pack(-side => 'right', -fill => 'y'); # 
    $MW_hscroll->pack(-side => 'bottom', -fill => 'x');	# 
    $c->pack(-expand => 'yes', -fill => 'both'); # 
   # my($bg, $i, $j, $x, $y) = ($c->configure(-background))[4];
    $c;
}				# 

sub CreateWin{


}

sub GetLimit{


    my $ELIM = $MW->Toplevel;
    my $e = $ELIM;

    $e->title('Read Separation -><-');
    my $w_OK = $e->Frame;
    $w_OK->pack(qw(-side bottom -fill x -pady 2m));
    my $lim = $e->Entry(-relief=> 'sunken',-textvariable => \$limit);
    $lim->pack;
    
    my $OK = $w_OK->Button(-text =>'OK',-command=> [\&LimOK,$e,$limit],);
    $OK->pack(qw(-side left -expand 1));  
  
}
sub LimOK{
    my ($OK,$lim) =@_;
    $OK->destroy;
    if($lim != $limit)
     {
      # recalc ..
	 &SetLimit($limit);
     }
   
  
}
###################################################################################################
## Main Loop 

Tk::MainLoop;


