/***************************************************************
	Demo pers data compress for CAR RACE  version 1.00
		    Programmed by Y.Nishida
					[ Feb.09, 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			*/


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

	puts( "\nDemo pers data compress for CAR RACE  version 1.00" ) ;
	if ( argc != 3 ) {
		puts( "Usage: mkpers <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 ) ;

	printf( "\nTotal %d ( %04X ) bytes write\n", bincnt,bincnt ) ;
	exit( 0 ) ;
}

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

void make_data( rp,wp )
FILE	*rp,*wp ;
{
	unshort	red_code,arc_code ;
	int	diff ;

	fgetnum( &arc_code         , rp ) ;
	fputnum(  arc_code | 0x8000, wp ) ;

	while ( fgetnum( &red_code, rp )) {
		diff     = arc_code - red_code ;
		arc_code = red_code ;

		if (( 0 <= diff ) && ( diff <= 0x7f )) {
			fputc( diff, wp ) ;
			bincnt ++ ;
		} else {
			fputnum( red_code | 0x8000, wp ) ;
		}
	}
	fputc( 0xff,wp ) ;
}

/******* file get number ***************************************/

fgetnum( num,rp )
unshort	*num ;
FILE	*rp ;
{
	int	ch,cl ;

	if (( cl = fgetc( rp )) == EOF ) return ( 0 ) ;
	if (( ch = fgetc( rp )) == EOF ) return ( 0 ) ;
	*num = ch * 256 + cl ;
	return ( 1 ) ;
}

/******* file put number **************************************/

fputnum( num,wp )
int	num ;
FILE	*wp ;
{
	unshort	code ;

	code = (unshort)num ;
	fwrite( &code,sizeof(unshort),1,wp ) ;
	bincnt += 2 ;
}
