#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include "./lib/spn.h"

void randomize (unsigned char arr[], int n) 
{ 
	unsigned char tmp;
	for (int i = n - 1; i > 0; i--) 
	{ 
		// Pick a random index from 0 to i 
		int j = rand() % (i + 1); 

		// Swap arr[i] with the element 
		// at random index 
		//        swap(&arr[i], &arr[j]); 
		tmp = arr[i];
		arr[i] = arr[j];
		arr[j] = tmp;
	} 
} 


int main(int argc, char *argv[])
{
	int fd_in,fd_out;
	unsigned int key;
	unsigned char perm[8] = {0,1,2,3,4,5,6,7};
	unsigned char subst[16] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};

	unsigned char inv_perm[8]; 
	unsigned char inv_subst[16];

	unsigned char buf;

	assert(argc == 4);

	srand(0);	

	randomize(perm,8);
	randomize(subst,16);
	calc_inv_perm(perm,inv_perm);
	calc_inv_subst(subst,inv_subst);



	fd_in = open(argv[1],O_RDONLY);
	fd_out = open(argv[2],O_WRONLY|O_TRUNC|O_CREAT,0600);
	key = (unsigned int)strtol(argv[3],NULL,0);


	while(1){
		ssize_t nb = read(fd_in, &buf, 1);
		if (nb <=0)
			break;
		buf = decrypt(buf, key, inv_perm, inv_subst);
		write(fd_out, &buf, 1);	
	}
	close(fd_in);
	close(fd_out);

	return 0;
}
