################################################################
# Rotor.pl : Single rotor cipher over the alphabet [A..Z]      #
#    Input from STDIN : plaintext                              #
#    Output to STDOUT : ciphertext                             #
#    Keys from command line:                                   #
#      key determines the primary alphabet by &makeperm,       #
#      pos determines start position of rotor.                 #
#--------------------------------------------------------------#
# Klaus Pommerening 10. September 1999, 18. Dezember 1999.     #
#                                                              #
# This program is freeware. Use it as you like.                #
# Usual disclaimers apply.                                     #
################################################################

require "auxcrypt.pl";              # Use standard alphabet,
                                    #   &gettext, &makeperm.
$key = $ARGV[0];                    # Get keys from command line.
$pos = $ARGV[1];                    # Set rotor to start position.
$permut = &makeperm($key);          # Make permutation from key.
@prim = split(//,$permut);          # Primary alphabet for rotor.

$plaintext = &gettext;              # Get plaintext from standard
                                    #   input,
@plainlist = split(//,$plaintext);  # split as list of characters.

foreach $char (@plainlist) {        # Take plaintext letter,
  $ciph = &rotor($char, $pos);      # feed rotor,
  print $ciph;                      # print ciphertext letter.
  $pos++; if ($pos > 25) {$pos -=26;} # Move rotor by 1 position.
  }
print "\n";

################################################################
# Subroutine rotor                                             #
#   Encrypt single letter by rotor in actual position.         #
#   Input parameters:                                          #
#     Plaintext letter in [A..Z],                              #
#     Rotor position in [0..25]                                #
################################################################
sub rotor {
  $a = $_[0];                           # Input letter.
  $i = $_[1];                           # Rotor position.
  $h = $sa{$a} - $i; if ($h < 0) {$h += 26;} # Preparotory shift
                                        #   for input contact.
  $k = $sa{$prim[$h]};                  # Index of cipher letter
                                        #   in primary alphabet.
  $l = $k + $i; if ($l > 25) {$l -=26;} # Final shift for output
                                        #   contact.
  return $alphabet[$l];                 # Output letter.
}
