#!/usr/bin/perl5

use strict;
use Tk;
require Tk::FileSelect;
require Tk::Dialog;

my $fname = $ENV{'HOME'};
my $main = new MainWindow(-title => 'Search a file');
$main->Label(-text => 'Search file')->pack;

my $whatframe=$main->Frame;
$whatframe->pack;
$whatframe->Label(-text => 'Search string')->pack(-side => 'left');
my $what = $whatframe->Entry(-width => 15);
$what->pack(-side => 'right');

my $fileframe=$main->Frame;
$fileframe->pack;
my $filename = $fileframe->Entry(-width => 40, -textvariable => \$fname);
$filename->pack(-side => 'left');
$fileframe->Button(-text => 'Browse...',
	      -command => sub{$fname=do_browse($fname);}
		  )->pack(-side => 'right');
$main->Button(-text => 'Search', 
	      -command => sub{do_search($fname, $what->get)}
	     )->pack;
MainLoop;

sub bad_file {
  my ($sel) = @_;
  $sel="Your selection" unless $sel;
  my $dialog=$main->Dialog(-title => 'Not a text file',
			   -text => "$sel is not a Text File");
  $dialog->Show;
}

sub do_browse {
  my ($dir) = @_;

  my $fs=$main->FileSelect;
  my $new=$fs->Show;
  if (-T $new) {
    $dir=$new;
  } else {
    bad_file($new);
  }
  return $dir;
}


sub do_search {
  my ($f, $w) = @_;

  unless (-T $f) {
    bad_file($f);
    return;
  }

  open (FILE,$f);
  my $line;
  my $tmp;
  my @found=();

  for ($line=1; !eof(FILE); $line++) {
    $tmp=<FILE>;
    chomp $tmp;
    push @found, "Line $line: $tmp" if $tmp=~/$w/;
  }

  my $dialog=$main->DialogBox(-title => 'Search results');
  my $frame=$dialog->add('Frame');
  $frame->pack(-fill => 'both', -expand => 1);
  $frame->Label(-text => "Searching for \"$w\" in $f:")->pack;
  
  my $listbox = $frame->Scrolled('Listbox');
  $listbox->pack(-fill => 'both', -expand => 1);
  $listbox->insert('end',@found);
  
  $dialog->Show;
  close FILE;
}
