/*******************************************/
/*                                         */
/*    binary to bulk                       */
/*                                         */
/*    coded   by A.Kobayashi 2004.7.2      */
/*                                         */
/*******************************************/
/*
	cc bitobu.c -o bitobu
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void usage()
{
	static char *h[]=
	{"bitobu -h -s -N -r -u -i {file|-}\n"
#if 0
	,"\t-h : help\n"
	,"\t-s : space\n"
	,"\t-N : LF by N bytes\n"
	,"\t-r : CR+LF\n"
	,"\t-u : output upper char\n"
	,"\t-i : no touch CR and LF\n"
#else
	,"\t-h : help\n"
	,"\t-s : １バイト毎にspace(0x20)を出力する。\n"
	,"\t-N : Ｎバイト毎に改行(0x0aを出力)する。\n"
	,"\t-r : 改行するときにCRLF(0x0d0a)を出力する。\n"
	,"\t-u : output upper char\n"
	,"\t-i : 改行コード(0x0dと0x0a)はそのまま出力する。\n"
#endif
	,NULL
	};
	char **ph,*p;

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

int main(argc, argv)
int   argc;
char *argv[];
{
	int  c,c1,iNum,iCR,iSpace,iUpper,iInter,count;
	char *p,*fname,buf[3];
	FILE *fp;

	iNum = iCR = iSpace = iUpper = iInter = count = 0;
	fp = NULL;
	fname = NULL;
	while (--argc > 0) {
		argv++;
		p = argv[0];
		if ((c=*p) == '-') {
			if (!(c=*(++p))) fp = stdin;
			else if (c>='0' && c<='9') iNum = atoi(p);
			else {
				while (c) {
					if (c == 'r') iCR = 1;
					else if (c == 's') iSpace = 1;
					else if (c == 'u') iUpper = 1;
					else if (c == 'i') iInter = 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) {
			if (c=='\r' || c=='\n') {
				putchar(c);
				continue;
			}
		}
		sprintf(buf,"%02x",c);
		if (iUpper) {
			buf[0] = toupper(buf[0]);
			buf[1] = toupper(buf[1]);
		}
		putchar(buf[0]);
		putchar(buf[1]);
		if (iSpace) putchar(' ');
		if (iNum > 0) {
			if (++count >= iNum) {
				if (iCR) putchar('\r');
				putchar('\n');
				count = 0;
			}
		}
	}
	exit(0);
}
