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

#include "rle.h"

unsigned char 	*infile,*outfile; 
unsigned char 	*iadrmax;
unsigned char 		*outfileorg,*infileorg;

int main(int argc, char *argv[])
{
	long packlen,sizeof_file;
	FILE *rh,*wh;
	char *openfile,*savefile;
	struct RLE16_s RLE16;
	
	openfile = argv[1];
	savefile = argv[2];

	/**** open ****/

	rh = fopen(openfile,"rb");
	if(rh==NULL)
	{
		printf("cant open %s\n",openfile);
		return -1;
	}
	
	/**** get len ****/
	
	fseek(rh,0,SEEK_END);
	sizeof_file = ftell(rh);
	if(sizeof_file==0)
	{
		printf("file have zero-size\n");
		fclose(rh);
		return -1;
	}
	fseek(rh,0,SEEK_SET);

	/**** get mem & load ****/

	infile 	= (unsigned char*) malloc(sizeof_file);	
	iadrmax	= (unsigned char*) infile + sizeof_file;
	infileorg   = infile; 
    	fread(infile,1,sizeof_file,rh);   	
    	fclose(rh);
    
    	/**** compress ****/
    	
    	if((sizeof_file&1)==1) sizeof_file++;
    
	simpleRLE16(infile,sizeof_file/2,&RLE16);	// RLE 16
	packlen=RLE16.simpleRLE16len;
   
   	/**** print stat ****/
   	
   	printf("pack %d -> %d (%d %%)\n",sizeof_file,packlen,packlen*100/sizeof_file);
   
   	/**** write out ****/
   	
   	wh = fopen(savefile,"wb");
	if(wh==NULL)
	{
		printf("cant write to file %s\n",savefile);
		free(infileorg);
   		free(outfileorg);
		return -1;
	}
	
	{
		char ident[]={"GOLDPACK"};
		char type[]={"RLEW"};
		long dummy=0;
	
		fwrite(ident,1,8,wh);		/** ident **/
		fwrite(&type,1,4,wh);		/** typ **/
		fwrite(&RLE16.simpleRLE16len,4,1,wh);                                 // write len
  		fwrite(&RLE16.simpleRLE16key,2,1,wh);                                 // key
  		fwrite(&dummy,2,1,wh);                                                // dummy
		fwrite(RLE16.simpleRLE16data,RLE16.simpleRLE16len,1,wh);              // rle datas

	}
	

	
	fclose(wh);
   	
   	/**** free ****/
   
   	free(infileorg);
   	free(RLE16.simpleRLE16data);
   
	return 0;
}
