##
# Copyright (c) 2008 Health Market Science, Inc
##
package _TMP;
use strict;
use warnings;
our $CVS_ID = '$Id: emacs-utils.el,v 1.82 2008/07/11 13:35:40 kburton Exp $'; #'
our $VERSION = ( qw$Revision: 1.82 $ )[1];

sub run {
  my($self) = @_;

  unless (@ARGV) {
    die "Error, you must supply one or more file names: $0 file1.txt [file2.txt [...]]\n";
  }

  my($longest,$foundFile) = ('','');

  foreach my $file (@ARGV) {
    unless (-e $file) {
      die "Error, file: '$file' does not exist.\n";
    }
    print "searching $file...\n";
    my $long = $self->cleanString($self->findLongestInFile($file));
    print "$file => (",length($long),") $long\n";
    if (length $long > length $longest) {
      $longest = $long;
      $foundFile = $file;
    }
  }  
  print "Longest overall:\n";
  print "  $foundFile (",length $longest,") '$longest'\n";
}

sub findLongestInFile {
  my($self,$file) = @_;
  my $data = $self->readFile($file);
  my $longest = '';
  my $cleanLongest = '';
  # _I_nefficient by any stretch of the imagination
  for (my $ii = 0; $ii < length $data; ++$ii ) {
    for (my $jj = $ii; $jj < length $data; ++$jj ) {
      my $sub = substr $data, $ii, $jj - $ii;
      next unless length $sub > 1;
      my $cleanSub = $self->stripString($sub);
      print "found a palindrome in $file => '",$self->cleanString($sub),"'\n" if $self->isPal($sub);
      # 8min #if ( $self->isPal($sub) && $self->isLonger($sub,$longest) ) {
      if ( length $cleanSub > length $cleanLongest && $self->isPal($sub) ) { # && $self->isLonger($sub,$longest) ) {
        $longest = $sub;
        $cleanLongest = $cleanSub;
      }
    }
  }
  return $longest;
}

sub stripString {
  my($self,$instr) = @_;
  my $str = uc $instr;
  $str =~ s/[^A-Za-z]+//msg;
  return $str;
}

sub cleanString {
  my($self,$instr) = @_;
  my $str = uc $instr;
  $str =~ s/^[^A-Za-z]+//msg;
  $str =~ s/[^A-Za-z]+$//msg;
  return $str;
}

sub isLonger {
  my($self,$left,$right) = @_;
  return length $self->stripString($left) > length $self->stripString($right);
}

sub isPal {
  my($self,$instr) = @_;
  my $str = $self->stripString($instr);
  return undef unless length($str) > 1;
  return $str eq $self->reverseString($str);
}

sub openFile {
  my($self,$fname,$mode) = @_;
  $mode ||= '<';
  my $fh;
  unless (open $fh, $mode, $fname) {
    die "Error opening file:$fname mode:$mode : $!\n";
  }
  return $fh;
}

sub readFile {
  my($self,$file) = @_;

  local $/ = undef;
  my $fh = $self->openFile($file);
  my $data = <$fh>;
  return $data;
}

sub reverseString {
  my($self,$str) = @_;
  return join( '', reverse( split //, $str ));
}



1;

_TMP->run;
