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

void encrypt_file(const char *input_filename, const char *output_filename, unsigned short key, unsigned char perm[8], unsigned char subst[16]) {
    FILE *in = fopen(input_filename, "rb");
    FILE *out = fopen(output_filename, "wb");
    if (!in || !out) {
        perror("Erreur ouverture fichier");
        exit(EXIT_FAILURE);
    }

    unsigned char byte;
    while (fread(&byte, 1, 1, in) == 1) {
        unsigned char encrypted = encrypt(byte, key, perm, subst);
        fwrite(&encrypted, 1, 1, out);
    }

    fclose(in);
    fclose(out);
}

int main(int argc, char *argv[]) {
    if (argc != 6) {
        printf("Usage: %s clé.txt subst.txt perm.txt fichier_clair fichier_chiffre\n", argv[0]);
        return EXIT_FAILURE;
    }

    unsigned short key;
    unsigned char subst[16];
    unsigned char perm[8];

    read_key(argv[1], &key);
    read_subst(argv[2], subst);
    read_perm(argv[3], perm);

    encrypt_file(argv[4], argv[5], key, perm, subst);

    printf("Chiffrement terminé : %s → %s\n", argv[4], argv[5]);
    return EXIT_SUCCESS;
}