// Affine Cipher

// This code was written by Tyler Akins and is placed in the public domain.
// It would be nice if this header remained intact.  http://rumkin.com

// Requires util.js


// Perform a Affine transformation on the text
// encdec = -1 for decode, 1 for encode (kinda silly, but kept it like this
//    to be the same as the other encoders)
// text = the text to encode/decode
// inc = how far to shift the letters.
// key = the key to alter the alphabet
// alphabet = The alphabet to use if not A-Z
function Affine(encdec, text, mult, inc, key, alphabet)
{
   var s = "";
   
   if (typeof(alphabet) != 'string')
      alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
   
   mult = mult * 1;
   inc = inc * 1;
   
   if (encdec < 0) {
      var i;
      inc = alphabet.length - inc;
      for (i = 1; mult * i % 26 != 1; i += 2) {
      }
      mult = i;
   }
   
   key = MakeKeyedAlphabet(key, alphabet);
   
   for (var i = 0; i < text.length; i++)
   {
      var b = text.charAt(i);
      var idx;
      if ((idx = alphabet.indexOf(b)) >= 0)
      {
         idx = (mult * idx + inc) % alphabet.length;
	 b = key.charAt(idx);
      }
      else if ((idx = alphabet.indexOf(b.toUpperCase())) >= 0)
      {
         idx = (mult * idx + inc) % alphabet.length;
	 b = key.charAt(idx).toLowerCase();
      }
      s += b;
   }
   return s;
}

document.Affine_Loaded = 1;
