/********************************************************/
/*	暗号理論の基礎	第１章	典型的な暗号法		*/
/*	１．シフト暗号					*/
/*	name: KIHA		filename: shift.c	*/
/********************************************************/
/*		入力仕様				*/
/*	暗号化：実行，平文(in)，暗号文(out)		*/
/*	復号化：実行，暗号文(in)，平文(out)		*/
/********************************************************/

#include<stdio.h>
#include<stdlib.h>


int main(int argc, char **argv)
{
	FILE *fp1, *fp2;
	char select;		/* 暗号化か復号化かの選択に使う */
	int key;		/* 鍵の値 */
	char plaintext;		/* 平文の文字 */
	char ciphertext;	/* 暗号文の文字 */


	/* ファイルオープン */
	if((fp1 = fopen(argv[1], "r"))==NULL){
		printf("入力ファイルが見つかりません\n");
		exit(1);
	}
	if((fp2 = fopen(argv[2], "w"))==NULL){
		printf("出力ファイルが見つかりません\n");
		exit(1);
	}

	/* 機能の選択 */
	while(1){
		printf("シフト暗号(Shift Cipher)\n");
		printf("暗号化 -> e，復号化 -> d\n");
		scanf("%c", &select);
		if(select == 'e' || select == 'd'){
			break;
		}else{
			printf("入力値が不正です\n");
		}
	}

	/* 鍵の入力 */
	while(1){
		printf("鍵を入力して下さい(0-25) -> ");
		scanf("%d", &key);
		if(key >=0 && key <= 25){
			break;
		}else{
			printf("入力値が不正です\n");
		}
	}

	/* 各機能毎に処理 */
	if(select == 'e'){		/* 暗号化の処理 */
		while(fscanf(fp1, "%c", &plaintext)==1){
			if(plaintext >= 'a' && plaintext <= 'z'){	/* 英子文字 */
				if(plaintext + key > 'z'){		/* はみ出た分は調整 */
					ciphertext = plaintext + key - 26;
				}else {
					ciphertext = plaintext + key;
				}
				fprintf(fp2, "%c", ciphertext);
			}else if(plaintext >= 'A' && plaintext <= 'Z'){	/* 英大文字 */
				if(plaintext + key > 'Z'){		/* はみ出た分は調整 */
					ciphertext = plaintext + key - 26;
				}else {
					ciphertext = plaintext + key;
				}
				fprintf(fp2, "%c", ciphertext);
			}else{						/* その他 */
				fprintf(fp2, "%c", plaintext);
			}
		}
	}else if(select == 'd'){	/* 復号化の処理 */
		while(fscanf(fp1, "%c", &ciphertext)==1){
			if(ciphertext >= 'a' && ciphertext <= 'z'){	/* 英子文字 */
				if(ciphertext - key < 'a'){		/* はみ出た分は調整 */
					plaintext = ciphertext - key + 26;
				}else{
					plaintext = ciphertext - key;
				}
				fprintf(fp2, "%c", plaintext);
			}else if(ciphertext >= 'A' && ciphertext <= 'Z'){ /* 英大文字 */
				if(ciphertext - key < 'A'){		/* はみ出た分は調整 */
					plaintext = ciphertext - key + 26;
				}else{
					plaintext = ciphertext - key;
				}
				fprintf(fp2, "%c", plaintext);
			}else{						/* その他 */
				fprintf(fp2, "%c", ciphertext);
			}
		}
	}

	fclose(fp1);
	fclose(fp2);
	return 0;
}
