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

char cipher(char c, char K);
char decipher(char c, char K);

int main(int argc, char **argv){
	int i=0, decrypt=0, lenk;
    char c;
    char *k;
    FILE *fin;
    FILE *fout;
    if (argc<4) return -1;
    fin=fopen(argv[1], "r");
    fout=fopen(argv[2], "w");
    k=argv[3];
    lenk=strlen(k);
    if (!fin || !fout) return -1;
    if (argc>4 && strcmp(argv[4],"decipher")==0) decrypt=1; 
    if (decrypt) printf("decrypting with key %s\n", k);

    fscanf(fin, "%c", &c);
    while(!feof(fin)){
        char K = k[i%lenk]-'a';
        i++;
        if (c>='A' && c<='Z') c=c-'A'+'a';
        if (c>='a' && c<='z') 
            if (decrypt) c=decipher(c, K);
            else c=cipher(c, K);
        fprintf(fout, "%c", c);
        fscanf(fin, "%c", &c);
    }
    close(fin);
    close(fout);
    return 0;
}

char cipher(char c, char K){
	return (c-'a'+K)%('z'-'a'+1)+'a';
}

char decipher(char c, char K){
	return (c-'a'-K+26)%('z'-'a'+1)+'a';
}
