/***************************************************************
    Back screen data compress for CAR RACE  version 1.00
		    Programmed by Y.Nishida
					[ Feb.08, 1990 ]
 ***************************************************************/

#include	<stdio.h>

#define		unchar		unsigned char
#define		unshort		unsigned short
#define		ERROR		-1
#define		COMPLETE	0


int	bincnt  = 0 ;			/*  counter of total byte			*/
int	norcnt  = 0 ;			/*  counter of normal format counter		*/
int	comcnt2 = 0 ;			/*  counter of compress 2 byte format data	*/
int	comcnt3 = 0 ;			/*  counter of compress 3 byte format data	*/
int	nulcnt  = 0 ;			/*  counter of null character format data	*/


main( argc,argv )
int	argc ;
char	**argv ;
{
	FILE	*rp,*wp ;
	void	make_data() ;

	puts( "\nBack screen data compress for CAR RACE  version 1.00" ) ;
	if ( argc != 3 ) {
		puts( "Usage: mkback <source file> <destination file>" ) ;
		exit( 1 ) ;
	}
	if (( rp = fopen( *++argv,"r" )) == NULL ) {
		perror( *argv ) ;
		exit( 1 ) ;
	}
	if (( wp = fopen( *++argv,"w" )) == NULL ) {
		perror( *argv ) ;
		exit( 1 ) ;
	}
	make_data( rp,wp ) ;
	fclose( rp ) ;
	fclose( wp ) ;

	bincnt = norcnt * 2 + comcnt2 * 2 + comcnt3 * 3 + nulcnt + 1 ;

	printf( "\nnon compress format data      %4d", norcnt  ) ;
	printf( "\n2 byte compress format data   %4d", comcnt2 ) ;
	printf( "\n3 byte compress format data   %4d", comcnt3 ) ;
	printf( "\nnull character format data    %4d", nulcnt  ) ;
	printf( "\n\nTotal %5d ( %04X ) bytes write\n", bincnt,bincnt ) ;
	exit( 0 ) ;
}

/****************************************************************/
/*	make data						*/
/****************************************************************/

void make_data( rp,wp )
FILE	*rp,*wp ;
{
	unshort	red_code,arc_code ;
	int	arc_count = 1 ;

	fread( &arc_code,sizeof(unshort),1,rp ) ;

	while ( fread( &red_code,sizeof(unshort),1,rp ) == 1 ) {
		if ( arc_code == red_code ) {
			arc_count ++ ;
		} else {
			write_data( arc_code,arc_count,wp ) ;
			arc_code  = red_code ;
			arc_count = 1 ;
		}
	}
	write_data( arc_code,arc_count,wp ) ;
	fputc( 0xfc,wp ) ;
}

/******* write data ********************************************/

write_data( code,cnt,wp )
int	code,cnt ;
FILE	*wp ;
{
	register int	ch,at,nn ;

	ch = code >> 8 ;
	at = code & 0x00ff ;

	if ( at & 0x01 ) {
		while ( cnt > 64 ) {
			fputc( 0xff, wp ) ;
			nulcnt ++ ;
			cnt -= 64 ;
		}
		nn = ((( cnt-1 ) << 2 ) | 0x03 ) & 0xff ;
		fputc( nn, wp ) ;
		nulcnt ++ ;
	}
	else {
		if ( cnt == 1 ) {
			nn = at & 0xc4 ;
			fprintf( wp,"%c%c", nn,ch ) ;
			norcnt ++ ;
		}
		else {
			while ( cnt > 256 ) {
				nn = ( at & 0xc4 ) | 0x02 ;
				fprintf( wp,"%c%c%c", nn,ch,255 ) ;
				comcnt3 ++ ;
				cnt -= 256 ;
			}
			if ( cnt > 8 ) {
				nn = ( at & 0xc4 ) | 0x02 ;
				fprintf( wp,"%c%c%c", nn,ch,cnt-1 ) ;
				comcnt3 ++ ;
			} else {
				nn = ( at & 0xc4 ) | ((( cnt-1 ) & 0x07 ) << 3 ) | 0x01 ;
				fprintf( wp,"%c%c", nn,ch ) ;
				comcnt2 ++ ;
			}
		}
	}
}
