#!/usr/bin/perl -w
################################################################
# runkey.pl : Running key cipher over the alphabet [A..Z]      #
#--------------------------------------------------------------#
# Transliteration of special characters according to English   #
#   rules                                                      #
# For special characters of other languages use preptext.pl    #
#   first.                                                     #
#--------------------------------------------------------------#
# Klaus Pommerening 2014-May-08, 2014-Jun-12                   #
#                                                              #
# This program is freeware. Use it as you like.                #
# Usual disclaimers apply.                                     #
################################################################

require "auxcrypt.pl";     # Use standard alphabet
                           #   as global variables $alphabet,
                           #   @alphabet, and %sa.
                           # Use procedures &to26eng,
                           #   &gettext, &makeperm, &puttext.

open(IN,"key.txt");           # Read keys.
chomp(@klist = <IN>);         # Read input line by line,
                              #   chop trailing CR.
foreach $line (@klist) {      # Change each line
  $line = &to26eng($line); }  #   to Alphabet [A..Z].
$key = join("",@klist);       # Join lines as 1 string.
close(IN);
$keylength = length($key);
# print "Key length = ", $keylength, "\n";
# print "Key = ", $key, "\n";
@keylist = split(//,$key);    # split as list of characters.

$plaintext = &gettext;                # Get plaintext from standard
                                      #   input,
$plength = length($plaintext);
@plainlist = split(//,$plaintext);    # split as list of characters.

$ciphertext = "";

$pos = 0;
for ($i = 0; $i < $plength; $i++) {
  $k = $sa{$plainlist[$i]};
  $l = $sa{$keylist[$pos]};
  $m = $k + $l; if ($m > 25) {$m -=26;}
# print $k, " + ", $l, " = ", $m, "\n";
  $ciphertext .= $alphabet[$m];                  # Append result to ciphertext
  $pos++; if ($pos >= $keylength) {$pos -= $keylength;}
  }
print "Cipher: ", $ciphertext, "\n";
