/*
Written by James Hallam, http://web.jameshallam.info
with some help from Jeanne-Kamikaze
If you're not me, you're not even allowed to LOOK at this code :P
*/

#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define MAXSIZE 10000
#define MAXINPUT 100

char ciphertext[MAXSIZE];
char worktext[MAXSIZE];
char replacement[26]; // Array of letters to substitute in
int i; // Temporary counting int

int main(int argc, char *argv[])
{
	char ch;
	char in, out;
	char input[MAXINPUT];
	
	for(i=0;i<26;i++)
	{
		replacement[i] = (i + 'A'); // Fill in the array with A-Z
	}
	
	printf("Ciphertext, please:\n");
	for(i=0;(ch=getchar()) != EOF;i++)
	{
		ciphertext[i] = toupper(ch); // Read in the ciphertext
	}
	
	decipher();
	
	for(;;)
	{	
		in=0;
		out=0;
		printf("> ");
	//	scanf("%c=%c", &in, &out);
		fgets(input, MAXINPUT, stdin);// We want something like "A=b" or "b c"
		in=input[0];
		out=input[2];
		
		if(isalpha(in) && isalpha(out) && (input[1] == '=' || input[1] == ' ')) // Check that the input is how we want
		{
			replacement[(toupper(in) - 'A')] = tolower(out); // Modify the replacement array. Notice the subtraction of 'A' - A becomes 0, B becomes 1, C becomes 2 etc.
			
			for(i=0;i < strlen(ciphertext); i++)
			{
				if (ciphertext[i] >= 'A' && ciphertext[i] <= 'Z') //Make sure it's a valid letter
				{
					worktext[i] = replacement[((ciphertext[i]) - 'A')]; //The core of it all!
				}
				else
				{
					worktext[i] = ciphertext[i]; // If the character isn't a letter, just copy it directly
					//worktext[i] = ' '; // If the character isn't a letter, replace it with a blank space
				}
			}	
	
			system("clear"); // Ooh... dirty!
			printf("%s\n", ciphertext);
			printf("----------------------\n");
			printf("%s\n", worktext);
			for(i=0;i<26;i++)
			{
				printf("%c=%c  ", (i + 'A'), replacement[i]); // Print current substitution/replacement array
			}
			printf("\n");
		}
		else { printf("SYNTAX ERROR\n"); }
	}
	
	return 0;
}

