/* This file provides an interface for library Ciphers.

   Names defined:
      CaesarCipher(), encodes/decodes using Caesar cipher
------------------------------------------------------------------*/

#include "Ciphers.h"

/*-----------------------------------------------------------------
   This function encodes/decodes a character string with the Caesar
   cipher, assuming ASCII codes for character representation.   It
   uses the function isprint() from <ctype.h> to determine if a
   character is an ASCII printable character.

   Receive: A, a character array
            k, an integer, assumed to be in the range -94 to 94
   Return:  A, with each char changed to the char k positions away
------------------------------------------------------------------*/

#include <ctype.h>
#include "Strings.h"

void CaesarCipher(Strings& A, int k)
{
   const int
      FirstPrintableChar = 32,       // printable range is
      NumPrintableChars = 95;        // 32 through 126;

   while (k < 0)                    // if k is negative, % won't work
      k += NumPrintableChars;       //   get it in the range 0 to 94

   int
      LengthA = A.Length();

   for (int i = 0; i < LengthA; i++) // for each char in the string:
      if (isprint(A[i]))             //   if it's in 32-126,
         A[i] =
          ((((A[i] - FirstPrintableChar) //   scale into 0-94
             + k)                        //   add the offset
             % NumPrintableChars)        //   wrap-around, and
             + FirstPrintableChar);      //   scale back into 32-126
}

