#!/usr/bin/perl -w
################################################################
# 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.                   #
#                         (= autocoincidence sprectrum)        #
#                       Global coincidence index of ciphertext.#
#--------------------------------------------------------------#
# Transliteration of special characters according to English   #
#   rules                                                      #
# For special characters of other languages use preptext.pl    #
#   first.                                                     #
#--------------------------------------------------------------#
# Klaus Pommerening 1997-Jun-12, 1999-Dec-06                   #
#                                                              #
# 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";
