#First Last Scramble (fls.pl)            dave.cronin.2015033
#
# Scrambles the letters in between the first and last letters of a word.
# The brain will reassemble the letters subconsciously to make the words
# readable.
#
# How to use.
#
# 1. Create a flat text file and save it to some filename.
#
# 2. perl fls.pl < filename [ > newfilename ]
#
# If the newfilename is not randomized enough, rerun step 2
# as many times as neccessary.

my @Wlist,$iResult="";
while ( <STDIN> ) {
 chomp;
 @Wlist = split /\s/,$_;
 foreach $i (@Wlist) { $iResult .= flword($i)." "; }
 $iResult .= "\n";
}
print "$iResult\n";
exit 0;

sub flword {
 # This function scrambles the letters between the first and last letters of a word.
 # @wrd - array of letters representing the word.
 # @relms - element references between first and last letter.
 # $lc = lowest character element between first and last letter.
 # $hc = highest chareacter element between first and last letter.
 # $range = number of letter between first and last letter.
 # $result = reassembled word.
 # $h,$i,$j,$x = working storage variables.
 #
 # print flword("butter")."\n";
 # "utte" will be in a randomized between "b" and "r".
 #
 my $myWrd=$_[0];
 my @wrd = split //,$myWrd;
 my @relms={};
 my $lc=0,$h,$i,$j,$x,$z1,$z2,$z3,$result="";
 my $hc=$#wrd;
 while ($wrd[$hc] !~ /\w{1}/ && $hc > $lc) {$hc--;}
 $lc++; $hc--; $range=$hc-$lc+1;
 if ($range > 1) {  # need at least a 4-letter word or more
  for($i=$lc;$i<=$hc;$i++){$relms[$i]=$i;}
  for($i=$lc;$i<=$hc;$i++){
   $z1="";
   for($z3=0;$z3<=$#wrd;$z3++){$z1.=$wrd[$z3];}
   $z2=$z1;
   while ($z1 eq $z2) {
    for($j=1;$j<=26;$j++){
     $x=int(rand($range))+1;
     $h=$wrd[$relms[$i]];
     $wrd[$relms[$i]]=$wrd[$relms[$x]];
     $wrd[$relms[$x]]=$h;
    }
    $z2=""; for($z3=0;$z3<=$#wrd;$z3++){$z2.=$wrd[$z3];}  # ensure random letters.
   }
   last if ($z1 ne $z2);
  }
  foreach $i (@wrd){$result .= $i;}
 } else {
  $result = $myWrd;   # just return what was passed.  Word is less than 4 letters.
 }
 return $result;
}