/****************************************************************
	Map data archiver for CAR RACE  version 1.20
		  Programmed by Y.Nishida
					[ Jun.25, 1990 ]
 ****************************************************************/

#include	<stdio.h>
#include	<strings.h>
#include	<ctype.h>

#define		unchar		unsigned char
#define		unshort		unsigned short
#define		TRUE		1
#define		FALSE		0
#define		high(c)		((c)>>8)
#define		low(c)		((c)&0xff)

unshort	pointer[32] ;
unshort	length[32] ;

int	counter  = 0 ;
int	address  = 0x009f80 ;
int	datasize = 128 ;


main( argc,argv )
int	argc ;
char	**argv ;
{
	FILE	*tp,*wp ;
	char	tbl_name[65],arc_name[65],map_name[65],ptr_name[65] ;

	puts( "Map data archiver for CAR RACE  version 1.20" ) ;
	if ( argc != 2 ) {
		fputs( "Usage: armap <archive name>\n",stderr ) ;
		exit( 1 ) ;
	}
	strcpy( tbl_name,*++argv ) ;
	strcat( tbl_name,".MTB" ) ;
	if (( tp = fopen( tbl_name,"r" )) == NULL ) {
		perror( tbl_name ) ;
		exit( 1 ) ;
	}
	strcpy( arc_name,*argv ) ;
	strcat( arc_name,".MAP" ) ;
	if (( wp = fopen( arc_name,"w" )) == NULL ) {
		perror( arc_name ) ;
		exit( 1 ) ;
	}

	while ( fgets( map_name,60,tp ) != NULL ) {
		if ( isalpha( map_name[0] )) {
			set_mapname( map_name ) ;
			archive( map_name,wp ) ;		/*  make panel data	*/
		}
	}
	fclose( tp ) ;
	fclose( wp ) ;

	strcpy( ptr_name,*argv ) ;
	strcat( ptr_name,".PTR" ) ;
	save_pointer( ptr_name ) ;

	printf( "\nMap data total size %6d ( $%05X )\n",datasize,datasize ) ;
	exit( 0 ) ;
}

/******* set map file name ***************************************/

set_mapname( ss )
char	*ss ;
{
	while ( *ss != '\n' && *ss != '\0' ) ss++ ;
	*ss = '\0' ;
}

/****************************************************************/
/*	archive map file					*/
/****************************************************************/

archive( fname,wp )
char	*fname ;
FILE	*wp ;
{
	FILE	*rp ;
	unchar	buf[16] ;
	int	cnt = 0 ;

	if ( counter == 31 ) {
		puts( "pointer buffer is over" ) ;
		exit( 1 ) ;
	}
	pointer[counter] = address / 16 ;

	if (( rp = fopen( fname,"r" )) == NULL ) {
		perror( fname ) ;
		exit( 1 ) ;
	}
	while ( fread( buf,sizeof(unchar),16,rp )) {
		address += 16 ;
		cnt     += 16 ;
		fwrite( buf,sizeof(unchar),16,wp ) ;
		if ( !( address & 0xffff )) address += 0x8000 ;
	}
	fclose( rp ) ;

	length[counter++] = cnt / 16 ;
	datasize += cnt ;
	printf( "map file \"%s\"\t: total %05X bytes write.\n", fname,cnt ) ;
}

/****************************************************************/
/*	Save data pointer					*/
/****************************************************************/

save_pointer( fname )
char	*fname ;
{
	FILE	*wp ;
	int	i ;

	pointer[counter] = address / 16 ;

	if (( wp = fopen( fname,"w" )) == NULL ) {
		perror( fname ) ;
		exit( 1 ) ;
	}
	for ( i=0 ; i<32 ; i++ ) {
		fputc(  low( pointer[i] ),wp ) ;
		fputc( high( pointer[i] ),wp ) ;
		fputc(  low(  length[i] ),wp ) ;
		fputc( high(  length[i] ),wp ) ;
	}
	fclose( wp ) ;
}
