/*	:*****************************************************************
	:	"bin2str.c"
	:-----------------------------------------------------------------
	:	バイナリデータをＣ言語ソースに変換
	:*****************************************************************
*/
#include	<stdio.h>
#include	<stdlib.h>
#include	<string.h>
#include	<ctype.h>

char	*ValName    = NULL;
char	*InputPath  = NULL;
char	*OutputPath = NULL;
FILE	*InputFp    = stdin;
FILE	*OutputFp   = stdout;

int			bin2str(void)
{
	unsigned char	ch;
	unsigned long	cnt = 0l;

	if ( ValName )
		fprintf( OutputFp,"%s =\r\n", ValName );

	fputs( "{\r\n", OutputFp);
	for(;;)
	{
		if ( fread( &ch, 1, 1, InputFp ) < 1 )
			break;
		if ( (cnt & 15l) == 0 )
			fputs( "\r\n\t", OutputFp);
		fprintf( OutputFp, "0x%02X,", ch );
		++cnt;
	}
	fputs( "\r\n\}\r\n", OutputFp);
	return (0);
}


static	void	help(void)
{
	exit(1);
}

static	void	paraerr( char *s )
{
	exit(2);
}

int	main(int argc,char *argv[])
{
	int			i;
	char		*s;

	for ( i = 1; i < argc; ++i )
	{
		s = argv[i];
		if ( *s == '?' )
			help();
		if ( *s == '-' || *s == '/' )
		{	/* option	*/
			++s;
			if ( *s == '?' )
				help();
			if ( strcmpi( s, "write") == 0 && i + 1 < argc )
			{	++i;
				OutputPath = argv[i];
			} else if ( strcmpi( s, "name") == 0 && i + 1 < argc )
			{	++i;
				ValName = argv[i];
			}
		} else
		{	if ( InputPath == NULL )
				InputPath = s;
			 else
				paraerr( s );
		}
	}
	
	if ( InputPath )
	{
		fprintf(stderr,"filename %s\n", InputPath );
		if ( (InputFp = fopen(InputPath,"rb")) == NULL )
		{	fprintf(stderr,"@ Read file open error!! (%s)\n", InputPath );
			exit(2);
		}
	} else
	{
		paraerr( NULL );
	}

	if ( OutputPath )
	{
		if ( (OutputFp = fopen(OutputPath,"wb")) == NULL )
		{	fprintf(stderr,"@ Write file open error!! (%s)\n", OutputPath );
			exit(2);
		}
	}

	return	bin2str();
}

