# 
# Benjamin warned me (no pun intended) that my code spews some warnings if you
# test it with -w.  These warnings are just that, they don't affect the outcome of
# the results, but since it doesn't look very clean, I have updated my code to
# remove the warnings.
# 
# This results in a slight decrease in speed, since I have to add another test to
# one of my conditionals, but the overall performance is still good.
# 
# for those who don't care about warnings, just turn them off with
#   no warnings qw(substr uninitialized);
# For those who do, use the code below instead.

use warnings;
use strict;

sub repeated_substring {
  my $size = length $_[0];
  my $maxsize = int ($size / 2);
  my ($f_index, $f_offset) = (0,0);

OUTER:
  for (my $index=0; $index < $size; $index++) {

    # The big optimizer 
    # (added a bounds check to keep us from going beyond the end of the data)
    if ($f_offset > 20 && $index + $f_offset <= $size) {
      for (my $t_index = $index + $f_offset - 15; $t_index >= $index; $t_index =
$t_index - 15) {
        if (index($_[0], substr($_[0], $t_index, $index+$f_offset-$t_index),
$index+$f_offset) == -1) {
          $index = $t_index;
          next OUTER;
        }
      }
    }

    for (my $offset=$f_offset+1; $offset <= $maxsize && $index + $offset <=
$size; $offset++) {
      if (index($_[0], substr($_[0], $index, $offset), $index+$offset) >= 0) {
        $f_index  = $index;
        $f_offset = $offset;
      } else {
        last;
      }
    }
  }
  return substr($_[0], $f_index, $f_offset);
}

