################################################################
# coinc.pl : Friedmans index of coincidence                    #
#    Input from STDIN : ciphertext (or any text if you like)   #
#    Output to STDOUT : Coincidence indices of ciphertext with #
#                         itself, cyclically shifted by 1, 2,  #
#                         3, ... characters.                   #
#                       Global coincidence index of ciphertext.#
# Theory and application: Look at any book in classical        #
#   cryptology, chapter on polyalphabetic substitution.        #
#--------------------------------------------------------------#
# Klaus Pommerening 12. Juni 1997, 6. Dezember 1999            #
#                                                              #
# This program is freeware. Use it as you like.                #
# Usual disclaimers apply.                                     #
################################################################


require "auxcrypt.pl";

$text = &gettext;                   # Get text as list
@textlist = split(//,$text);        #   of characters in A..Z.
$r = length($text);
print "Length of text: $r\n";

for ($i = 1; $i < $r; $i++) {$cnt[$i] = 0;}
$sum = 0;                    # Initialise counters and sum.

for ($i = 0; $i < $r-1; $i++) {
  for ($j = $i+1; $j < $r; $j++) {
    if ($textlist[$i] eq $textlist[$j]) {
      $cnt[$j-$i]++;         # Count coincidence
      $cnt[$r-$j+$i]++;      # both ways.
      } # if
    } # for $j
  } # for $i

for ($i = 1; $i < $r; $i++) {
  $kappa[$i] = $cnt[$i]/$r;  # IC of text with shifted text.
  print "kappa[$i] = $kappa[$i]\n";
  }
for ($i = 1; $i < $r; $i++) {$sum += $kappa[$i];}
$kbar = $sum/($r-1);
print "Kappa of text = $kbar\n";
