#!/usr/bin/perl -w

use strict;

my $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
my $show_stats = 1;

sub decode
  {
  my $l_i;
  my $l_j;
  my $l_rd;		# Iteration count
  my $l_shift;		# Offset into the alphabet (stage II decryption)
  my $l_inmsg;		# Buffer for ciphertext
  my $l_outmsg;		# Buffer for cleartext
  my $l_textlen;	# Length of ciphertext

  $l_inmsg = $_[0];
  $l_outmsg = '';
  $l_textlen = length($l_inmsg);
  for($l_i = 0; $l_i < $l_textlen; $l_i++)
    {
    $l_outmsg .= ' ';
    }

  $l_rd = $_[1];
  $l_shift = $_[2];

  if($show_stats == 1)
    {  
    print "Initial data:\n";
    print "Ciphertext length: $l_textlen\n";
    print "Iterations: $l_rd\n";
    print "Offset into translation table: $l_shift\n";
    print "=================================================\n";
    }
  
# Stage I decode: Unwind the ciphertext
  for($l_i = $l_rd; $l_i > 0; $l_i--)
    {
    for($l_j = 0; $l_j < int(($l_textlen + 1) / 2); $l_j++)
      {
      substr($l_outmsg,$l_j * 2,1,substr($l_inmsg,$l_j,1));
      substr($l_outmsg,$l_j * 2 + 1,1,substr($l_inmsg,$l_textlen - $l_j - 1,1)) if($l_j * 2 + 1 <= $l_textlen);
      }

    $l_inmsg = $l_outmsg;
    }

# Stage II decode: Transpose the alphabet where necessary
  if($l_shift > 0)
    {
    for($l_i = 0; $l_i < length($l_outmsg); $l_i++)
      {
      substr($l_outmsg,$l_i,1,substr($alphabet,(ord(substr($l_outmsg,$l_i,1)) - 39 - $l_shift) % 26,1)) if(index($alphabet,substr($l_outmsg,$l_i,1)) != -1);
      }
    }

  $l_outmsg =~ tr/-/ /;

  return $l_outmsg;
  }

my $ciphertext;
my $cipherid;
my $cleartext;

my $m;
my $n;

print 'Please provide the ciphertext: ';
$ciphertext = <STDIN>;
chop($ciphertext);
print 'Please provide the key: ';
$cipherid = <STDIN>;
chop($cipherid);

print "\n\n";

if($cipherid =~ /^!#RD([0-9]{1,})SB([0-9]{1,})\/\/$/)
  {
  if($1 <= 0 || $2 < 0 || $2 > 25)
    {
    print "Invalid encryption key!\n";
    print "m must be a nonzero positive integer, and n must be in the range\nfrom 0 to 25!";
    }
  else
    {
    $cleartext = decode($ciphertext,$1,$2);
    print "Cleartext: $cleartext\n";
    }
  }
else
  {
  print "That\'s not a valid key!\nThe key must be in the form\n";
  print "!#RD<m>SB<n>//\n";
  print "m and n are positive integers.\n";
  }
