/*******************************************/
/*                                         */
/*    bulk to binary                       */
/*                                         */
/*    coded   by A.Kobayashi   94.6.7      */
/*    updated by A.Kobayashi 2004.7.1      */
/*                                         */
/*******************************************/
/*
	cc butobi.c -o butobi
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void usage()
{
	static char *h[]=
	{"butobi -h -i {file|-}\n"
#if 0
	,"\t-h : help\n"
	,"\t-i : no touch CR and LF\n"
	,"\t-o : omit CR and LF\n"
#else
	,"\t-h : help\n"
	,"\t-i : 改行コード(0x0dと0x0a)はそのまま出力する。\n"
	,"\t-o : 改行コード(0x0dと0x0a)を削除する。\n"
#endif
	,NULL
	};
	char **ph,*p;

	ph = h;
	while (p = *ph++) fprintf(stderr,p);
}

unsigned char atox1(c)
char    c;
{
	if ((c >= '0') && (c <= '9')) c -= '0';
	else if ((c >= 'a') && (c <= 'f')) c -= ('a' - 10);
	else if ((c >= 'A') && (c <= 'F')) c -= ('A' - 10);
	else c = 0xff;

	return c;
}
		 
/* Convert bulk --> Binary
butobi(bu, len, bi)
char    *bu;
char    *bi;
long    len;	*/
int main(argc, argv)
int   argc;
char *argv[];
{
	int  c,c1,iInter,iOMIT;
	char *p,*fname;
	FILE *fp;

	fp = NULL;
	fname = NULL;
	iInter = iOMIT = 0;
	while (--argc > 0) {
		argv++;
		p = argv[0];
		if ((c=*p) == '-') {
			if (!(c=*(++p))) fp = stdin;
			else {
				while (c) {
					if (c == 'i') iInter = 1;
					else if (c == 'o') iOMIT = 1;
					else {
						usage();
						exit(1);
					}
					c = *p++;
				}
			}
		}
		else fname = p;
	}

	if (!fp) {
		if (fname) {
			fp = fopen(fname,"rb");
			if (!fp){
				fprintf(stderr,"file[%s] open error!!\n",p);
				exit(2);
			}
		}
		else {
			usage();
			exit(1);
		}
	}

	while ((c=getc(fp))!=EOF) {
		if (iInter || iOMIT) {
			if (c=='\r' || c=='\n') {
				if (!iOMIT) putchar(c);
				continue;
			}
		}
		if ((c = atox1(c)) == 0xff) continue;
		if ((c1=getc(fp))==EOF) c1 = 0;
		else {
			if (iInter || iOMIT) {
				if (c1=='\r' || c1=='\n') {
					putchar(c << 4);
					if (!iOMIT) putchar(c1);
					continue;
				}
			}
			if ((c1 = atox1(c1)) == 0xff) c1 = 0;
		}
		putchar((c << 4) + c1);
	}
	exit(0);
}
