int LZW_Compression(char *in_filename, char *out_filename)
{ unsigned int next_code;
unsigned int character;
unsigned int string_code;
unsigned int index;
int i;
FILE *input;
FILE *output;
code_value=malloc(TABLE_SIZE*sizeof(unsigned int));
prefix_code=malloc(TABLE_SIZE*sizeof(unsigned int));
append_character=malloc(TABLE_SIZE*sizeof(unsigned char));
if (code_value==NULL || prefix_code==NULL || append_character==NULL)
{ printf("Fatal error allocating table space!\n");
return 0;
}
input=fopen(in_filename,"rb");
output=fopen(out_filename,"wb");
if (input==NULL || output==NULL)
{ printf("Fatal error opening files.\n");
return 0;
};
/* compressing... */
next_code=256; /* Next code is the next available string code*/
for (i=0;i<TABLE_SIZE;i++) /* Clear out the string table before starting */
code_value[i]=-1;
i=0;
printf("Compressing...\n");
string_code=getc(input); /* Get the first code */
while ((character=getc(input)) != (unsigned)EOF)
{ if (++i==1000)
{ i=0;
printf(".");
}
index=find_match(string_code,character);
if (code_value[index] != -1)
string_code=code_value[index];
else
{ if (next_code <= MAX_CODE)
{ code_value[index]=next_code++;
prefix_code[index]=string_code;
append_character[index]=character;
}
output_code(output,string_code);
string_code=character;
}
}
output_code(output,string_code);
output_code(output,MAX_VALUE); /* Output the end of buffer code */
output_code(output,0); /* This code flushes the output buffer*/
printf("\n");
fclose(input);
fclose(output);
free(code_value);
free(prefix_code);
free(append_character);
return 1;
}