#!/usr/bin/perl -w
use strict ;
my $string ;

die "\nERROR : Missing expected word argument\n\n" unless @ARGV ;
if ( -r "$ARGV[0]" ) {
    print "Found file : $ARGV[0].  Reading contents ...\n" ;
    $string = `cat $ARGV[0]` ;
    $string =~ s/\n//g ;
} else {
    $string = "@ARGV" ;
}
print "\nLooking for repeated substrings of : $string\n" ;
my $substr = repeated_substring($string) ;
print "\nLongest substring is '$substr'\n\n" ;

sub repeated_substring {
    my $string = "@_" ;
    my ($strlen, $i, $len, $limit, $sub) ;
    $strlen = length($string) ;
    for ( $len=int($strlen/2) ; $len>=2 ; $len-- ) {
	my %repeated ;
	$limit = $strlen - $len ;
	for $i ( 0 .. $limit ) {
	    next if ($i < $len and $i > $limit - $len) ; ## Skip substrings of length $len that can't be matched
	    $sub = substr($string, $i, $len) ;
	    return $sub if (defined($repeated{$sub}) and ($i - $repeated{$sub} >= $len)) ; ## Only return non-overlaping substr
	    $repeated{$sub} = $i ;
	}
    }
}
