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

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

int main(int argc, char *argv[])
{
	long packlen,sizeof_file;
	FILE *rh,*wh;
	char *openfile,*savefile;
	
	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;
	outfile = (unsigned char*) malloc(sizeof_file*2);
	outfileorg  = outfile;
	infileorg   = infile; 
    
    	fread(infile,1,sizeof_file,rh);
    	
    	fclose(rh);
    
    	/**** compress ****/
    
	packlen 	= Encode();     // lzss
   
   	/**** 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[]={"LZSS"};
	
		fwrite(ident,1,8,wh);		/** ident **/
		fwrite(type,1,4,wh);		/** typ **/
		fwrite(&packlen,1,4,wh);	/** packlänge **/
	}
	
	fwrite(outfileorg,1,packlen,wh);
	
	fclose(wh);
   	
   	/**** free ****/
   
   	free(infileorg);
   	free(outfileorg);
   
	return 0;
}
