#include <stdio.h>

typedef unsigned char uint8;

uint8 SeenEvolution[53][2]=
{
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0},
	{0,0}
};

uint8 EvolutionTable[53][4]=
{
	//prob, nextlps, nextmps, toggle invert
	{0x5a,  1,  1,1}, //0  l,m
	{0x25,  6,  2,0}, //1  l,m
	{0x11,  8,  3,0}, //2  l,m
	{0x08, 10,  4,0}, //3   ,m
	{0x03, 12,  5,0}, //4   ,m
	{0x01, 15,  5,0}, //5   ,m

	{0x5a,  7,  7,1}, //6  l,
	{0x3f, 19,  8,0}, //7  l,m
	{0x2c, 21,  9,0}, //8  l,m
	{0x20, 22, 10,0}, //9   ,m
	{0x17, 23, 11,0}, //10  ,m
	{0x11, 25, 12,0}, //11  ,m
	{0x0c, 26, 13,0}, //12  ,m
	{0x09, 28, 14,0}, //13  ,m
	{0x07, 29, 15,0}, //14  ,m
	{0x05, 31, 16,0}, //15  ,m
	{0x04, 32, 17,0}, //16  ,m
	{0x03, 34, 18,0}, //17  ,m
	{0x02, 35, 5,0},  //18  ,m

	{0x5a, 20, 20,1}, //19 l,m
	{0x48, 39, 21,0}, //20 l,m
	{0x3a, 40, 22,0}, //21 l,m
	{0x2e, 42, 23,0}, //22 l,m
	{0x26, 44, 24,0}, //23 l,m
	{0x1f, 45, 25,0}, //24 l,m
	{0x19, 46, 26,0}, //25 l,m
	{0x15, 25, 27,0}, //26 l,m
	{0x11, 26, 28,0}, //27 l,m
	{0x0e, 26, 29,0}, //28 l,m
	{0x0b, 27, 30,0}, //29  ,m
	{0x09, 28, 31,0}, //30  ,m
	{0x08, 29, 32,0}, //31 l,m
	{0x07, 30, 33,0}, //32 l,m
	{0x05, 31, 34,0}, //33 l,m  <--- changed lps
	{0x04, 33, 35,0}, //34  ,m ... this is NOT skipped
	{0x04, 33, 36,0}, //35  ,m
	{0x03, 34, 37,0}, //36  ,m
	{0x02, 35, 38,0}, //37  ,m ... this is NOT skipped
	{0x02, 36,  5,0}, //38  ,m

	{0x58, 39, 40,1}, //39 l,m
	{0x4d, 47, 41,0}, //40 l,m
	{0x43, 48, 42,0}, //41  ,m
	{0x3b, 49, 43,0}, //42  ,m
	{0x34, 50, 44,0}, //43 l,m
	{0x2e, 51, 45,0}, //44 l,m
	{0x29, 44, 46,0}, //45 l,m
	{0x25, 45, 24,0}, //46  ,m

	{0x56, 47, 48,1}, //47 l,m
	{0x4f, 47, 49,0}, //48 l,m
	{0x47, 48, 50,0}, //49 l,m
	{0x41, 49, 51,0}, //50 l,m
	{0x3c, 50, 52,0}, //51 l,m
	{0x37, 51, 43,0}  //52  ,m
};

#define PROB(x) EvolutionTable[Contexts[x].index][0]
#define NEXT_LPS(x) EvolutionTable[Contexts[x].index][1]
#define NEXT_MPS(x) EvolutionTable[Contexts[x].index][2]
#define TOGGLE_INVERT(x) EvolutionTable[Contexts[x].index][3]

typedef struct {
	uint8 index;
	uint8 invert;
} context_state;

#define NUM_CONTEXTS 30
context_state Contexts[NUM_CONTEXTS];

#define BIT(x,y) ((x>>y)&1)

void Decompress(uint8 *datain, uint8 *dataout, int len)
{
	uint8 top,val;
	uint8 con,mps,prob;
	uint8 flag_lps,shift,mask;

	int out=0;
	int inverts=0;
	int lps=0;

	unsigned char in;
	int in_count;

	int i,bit;

	//setup
	top=0xFF;

	val=*datain;
	datain++;

	in=*datain;
	datain++;
	in_count=8;

	//reset context states
	for(i=0;i<NUM_CONTEXTS;i++)
	{
		Contexts[i].index=0;
		Contexts[i].invert=0;
	}

	for(i=0;i<len;i++)
	{
		if(i==-1800)
		{
			int k;
			printf("\nEvolution table:\n");
			for(k=0;k<53;k++)
				printf("  %d,%d //%d\n",SeenEvolution[k][0],SeenEvolution[k][1],k);
		}


		for(bit=0;bit<8;bit++)
		{
			//get context
			mask = (1<<(bit&3)) - 1;
			con = mask + ((inverts&mask)^(lps&mask));
			if(bit>3)
				con+=15;

			//get PROB and MPS
			prob = PROB(con);
			mps  = (BIT(out,15) ^ Contexts[con].invert);

			if(i>=15 && i<=18 && 0)
				printf("byte %d bit %d: val=%.2X top=%.2X prob=%.2X mps=%d   con=%d state=%d\n",
					i,bit,val,top,prob,mps,con,Contexts[con].index);

			//get bit
			if (val <= top-prob)
			{
				//mps
				top = top - prob;
				out = (out << 1) + mps;

				flag_lps=0;
			}
			else
			{
				//lps
				val = val - (top - (prob - 1));
				top = prob - 1;
				out = (out << 1) + 1-mps;

				flag_lps=1;
			}

			// renormalize
			shift=0;
			while(top<0x7F) // NOTE: not 0x80, it's a strange border case
			{
				shift++;

				top = (top<<1)+1;
				val = (val<<1)+(in>>7);

				in = (in<<1);
				if(--in_count==0)
				{
					in=*datain;
					datain++;
					in_count=8;
				}
			}

			//update processing info
			lps = (lps<<1) + flag_lps;
			inverts  = (inverts<<1) + Contexts[con].invert;

			//update context state
			if(flag_lps & TOGGLE_INVERT(con))
				Contexts[con].invert ^= 1;

			if(flag_lps)
			{
				SeenEvolution[Contexts[con].index][0]=1;
				Contexts[con].index = NEXT_LPS(con);
			}
			else if(shift)
			{
				SeenEvolution[Contexts[con].index][1]=1;
				Contexts[con].index = NEXT_MPS(con);
			}
		}

		//save byte
		*dataout = (out & 0xFF);
		dataout++;
	}
}


// I'm lazy, so here's static allocation
//plenty of room for all the files we'll be looking at
uint8 datain[0x10000];
uint8 dataout[0x10000];
uint8 realout[0x10000];

int main(int argc, char *arg[])
{
	char filename[256];
	int i,len;
	FILE *fp;

	if(argc<2)
	{
		printf("\nExample:  DecompTest FILE\n");
		printf("    this will take 'FILE.compressed' as input and compare\n");
        printf("    decompressor output to 'FILE.uncompressed'.\n\n");
		return 0;
	}

	//read in compressed file
	sprintf(filename,"%s.compressed",arg[1]);
	fp=fopen(filename,"rb");
	if(fp==NULL)
	{
		printf("ERROR: Can't open file [%s] for reading.\n",filename);
		return 1;
	}

	fseek(fp,0,SEEK_END);
	len=ftell(fp);
	fseek(fp,0,SEEK_SET);
	i=fread(datain,1,len,fp);
	fclose(fp);

	if(i!=len)
	{
		printf("ERR: Only read %d of %d bytes from [%s]\n",i,len,filename);
		return 1;
	}
	printf("Read %d bytes from [%s]\n",i,filename);


	//read in uncompressed file
	sprintf(filename,"%s.uncompressed",arg[1]);
	fp=fopen(filename,"rb");
	if(fp==NULL)
	{
		printf("ERROR: Can't open file [%s] for reading.\n",filename);
		return 1;
	}

	fseek(fp,0,SEEK_END);
	len=ftell(fp);
	fseek(fp,0,SEEK_SET);
	i=fread(realout,1,len,fp);
	fclose(fp);

	if(i!=len)
	{
		printf("ERR: Only read %d of %d bytes from [%s]\n",i,len,filename);
		return 1;
	}
	printf("Read %d bytes from [%s]\n",i,filename);


	//do decompression
	Decompress(datain,dataout,len);

	//compare
	for(i=0;i<len;i++)
		if(dataout[i]!=realout[i])
			break;

	if(i==len)
		printf("Success! No mismatches.\n");
	else
	{
		int j;

		printf("****FAIL**** mismatch on byte %d\n",i);

		j=i-3;
		if(j<0)
			j=0;

		for(;j<=i;j++)
			printf("byte %d: decomp[%.2X]->real[%.2X]\n",j,dataout[j],realout[j]);

		if(0)
		{
			printf("\nEvolution table:\n");
			for(i=0;i<53;i++)
				printf("  %d,%d //%d\n",SeenEvolution[i][0],SeenEvolution[i][1],i);
		}
	}

	return 0;
}