/*
 *	vdg2xbm.c - convert an ascii char on command line to a VDG bitmap
 *	output in xbm form to stdout or filename on cmdline
 */

#include <stdio.h>

#include "global.h"
#include "vdg_data.h"

/*  This is a bug fix to stop inclusion of needless libraries at link time
 *  with BC4.0x
 */
#ifdef __BORLANDC__
# if __BORLANDC__ >= 0x0450 && __BORLANDC__ <= 0x0452
void _ExceptInit (void)
{
}
# endif
#endif /*  BORLANDC  */

/*  bit reverses b_in - need 'cos X stores bits the other way round to me  */
Byte	bit_reverse ( Byte b_in )
{
	int	i;
	Byte	b_out = 0x00;

	for ( i = 0; i < 8; i++, b_in <<= 1 )
		b_out = ( b_out >> 1 ) | ( b_in & 0x80 );

	return( b_out );
}

int	main ( int argc, char *argv[] )
{
	FILE	*op;
	int	row;
	char	c;
	const char	*xbm_tag = "vdg_char";
	
	if ( argc < 2 )
	{
		fprintf( stderr, "Usage: %s vdg_char [filename.xbm]\n", argv[0] );
		return( 0 );
	}

	if ( argc >= 3 )
	{
		/*  Output filename given  */
		if (( op = fopen( argv[2], "wt" )) == NULL )
		{
			fprintf( stderr, "%s: Unable to write %s\n", argv[0], argv[2] );
			return( 1 );
		}
	}
	else
		/*  Use stdout  */
		op = stdout;

	c = argv[1][0];

	/*  lower->upper case ?  */
	if ( c >= 'a' && c <= 'z' )
		c += 'A' - 'a';

	if ( c < 0x20 || c >= 0x60 )
	{
		fprintf( stderr, "%s: Can't convert char '%c'\n", argv[0], c );
		return( 2 );
	}
	/*  Base to VDG data table - converts Ascii code to VDG code  */
	c &= 0x3f;

	/*  xbm header  */
	fprintf( op, "#define %s_width 8\n", xbm_tag );
	fprintf( op, "#define %s_height 12\n", xbm_tag );
	fprintf( op, "static unsigned char %s_bits[] = {\n  ", xbm_tag );

	/*  3 blank scan lines above the character  */
	fprintf( op, "0x00, 0x00, 0x00, " );

	/*  7 rows of actual data  */
	for ( row = 0; row < 7; row ++ )
		fprintf( op, "0x%02x, ", bit_reverse( vdg_data[(int)c].row[row] ) );

	/*  2 blank scan lines below  */
	fprintf( op, "0x00, 0x00\n" );

	/*  Close xbm data struct  */
	fprintf( op, "};\n" );

	if ( op != stdout )
		fclose( op );

	return( 0 );
}
