/* Complex ASCII Rotation

   This program takes as input a password and
an ASCII file.  From the password a rotation
queue is derived.  Then the incomming file is
processed using the rotation queue to rotate
each character differently then those to it's
left and right.  The end result is an output
file with the rotated text.

The program also reverses the process and will
produce the original text out of the rotated
file.

*/

#define  ROTATE     1
#define  UNROTATE   0

#include <stdio_h>

/*  Global Array for holding Rotation Queue */
int rot_array[30];

main ()
{

   int c, i, fd1, fd2, rot_mark, pass_len, rot;
   char *password;


   printf("Enter the Input File : ");
   fd1 = open_file("r");

   printf("Enter the Output File : ");
   fd2 = open_file("w");

   printf("Enter a Password : ");
   gets(password);
   pass_len = strlen(password);

/* generate the rotation array from the password */
   for ( i=1; i<=pass_len; i++)
      rot_array[i] = password[i] % 7;

   printf("Rotate or Unrotate (U/R) : ");
   c = getchar();
   putchar(c);
   printf("\n");
   if ( c == 'R' || c == 'r' )
      rot = ROTATE;
   else
      rot = UNROTATE;

/* Start of the main part of the program */
   rot_mark = 1;

   while (( c=getc(fd1)) != EOF)
   {
      if ( !isprint(c) )
         putc(c,fd2);
      else {
         if ( rot == ROTATE )
            c = c + rot_array[rot_mark];
         else
            c = c - rot_array[rot_mark];
         putc(c,fd2);
         rot_mark++;
         if ( rot_mark > pass_len )
            rot_mark = 1;
      }
   }
   printf("\n     Done!\n\n");
}

/*  This procedure gets a file name and opens it.
if it fails, it aborts the program.
It takes three values "r", "w", "a"
  for Read, Write, Append.

  Usage:   file_pointer = open_file("r");
 */
open_file(rwa)
  char *rwa;
{

   char filename[30];
   int  fd;

   gets(filename);
   fd = fopen(filename, rwa);
   if ( fd == NULL) {
      printf("\n   Error Opening File! \n");
      abort(-1);
   }

   return fd;
}


