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

int main(int argc, char **argv)
{
	int res;
	FILE *f_bin, *f_hi, *f_lo;
	int bytes;
	
	if (argc<4) {
		printf("Usage: ./bin2hilo bin_file hi_file low_file\n");
		return -1;
	}

	/* Open files */
	f_bin = fopen(argv[1], "r");
	if (f_bin==NULL) { 
		perror("fopen bin_file");
		return -1;
	}
	
	f_hi = fopen(argv[2], "w");
	if (f_hi==NULL) {
		perror("fopen hi_file");
		fclose(f_bin);
		return -1;
	}
	f_lo = fopen(argv[3], "w");
	if (f_lo==NULL) {
		perror("fopen low_file");
		fclose(f_hi);
		fclose(f_bin);
		return -1;
	}

	/* Split high and low order bytes */
	bytes=0;
	while(1)
	{
		unsigned char buf[2];
		res = fread(buf ,2,1,f_bin);
		if (feof(f_bin)) { break; }
		if (res!=1) { break; }
		fwrite(&buf[0], 1, 1, f_hi);
		fwrite(&buf[1], 1, 1, f_lo);
		bytes++;
	}

	printf("wrote 2 %d Bytes (%d Kb) files\n", bytes, bytes/1024);

	/* Final cleanup */
	fclose(f_lo);
	fclose(f_hi);
	fclose(f_bin);
	
	return 0;
}


