#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cipher.h"

// read a file into a buffer
char* readFile(char* fname) {
    // from https://stackoverflow.com/questions/174531/how-to-read-the-content-of-a-file-to-a-string-in-c
    char * buffer = 0;
    long length;
    FILE * f = fopen (fname, "rb");

    if (f) {
        fseek (f, 0, SEEK_END);
        length = ftell (f);
        fseek (f, 0, SEEK_SET);
        buffer = malloc(length+1);
        if (buffer) {
            fread (buffer, 1, length, f);
        }
        fclose (f);
        buffer[length] = 0;
        return buffer;
    } else {
        fprintf(stderr,"File read error.\n");
        exit(-2);
    }
}

// read in file and pad
int main(int argc, char** argv) {
    if (argc != 3) {
        fprintf(stderr,"Requires message file and pad file arguments.");
    } else {
        char* msg = readFile(argv[1]);
        char* pad = readFile(argv[2]);
        char* result;
#ifdef DECIPHER
        result = decipher(msg,pad);
#else
        result = encipher(msg,pad);
#endif
        printf("%s\n",result);
    }
}