/*
 *  marge.c : program to add a margin on the front of every line
 *            in a file.
 *
 *     by Joel Swank 9/21/88
 */

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

char linebuf[500];
int filecnt = 0;
FILE *in, *out;
char pad = '\t';	/* default pad cahracter is tab */
int numpad = 1;	/* default number of pad characters is 1 */

main(argc, argv)
int argc;
char *argv[];
{
	int i = 1;
	if (argc == 0) exit(0); /* no workbench */

	/* default is stdin and stdout */
	in = stdin;
	out = stdout;
	/* interrogate the command line */
	while (--argc >0)
		{
		if (argv[i][0] == '-')	/* got a switch */
			{
			if (argv[i][1] == 'b') pad = ' ';
			else if (argv[i][1] == '?')
				{
				usage();
				specs();
				exit(0);
				}
			else if (isdigit(argv[i][1]))
				numpad = atoi(&argv[i][1]);
			else {
				fprintf(stderr,"Marge: invalid switch: %s\n",argv[i]);
				usage();
				exit(1);
				}
			}
		else {
			if (filecnt == 0) /* its input file name */
				{
				in = fopen(argv[i],"r");
				if (!in)
					{
					fprintf(stderr,"Marge: Input open failed on %s\n",argv[i]);
					exit(1);
					}
				}
			if (filecnt == 1) /* its output file name */
				{
				out = fopen(argv[i],"w");
				if (!out)
					{
					fprintf(stderr,"Marge: Output open failed on %s\n",argv[i]);
					exit(1);
					}
				}
			if (filecnt > 1) /* its too many file names */
				{
				fprintf(stderr,"Marge: too many filenames\n");
				}
			filecnt++;
			}
		i++;
		}

	/* Now process the data */

	while (fgets(linebuf,500,in) != 0)
		{
		for (i=0; i<numpad; i++) putc(pad,out);
		fputs(linebuf,out);
		}

	exit(0);
}

usage()
{
	fprintf(stderr,"Usage:marge [-b] [-#] [-?] [infile] [outfile]\n");
}

specs()
{
	fprintf(stderr," Add whitespace to front of each line of a file.\n");
	fprintf(stderr," Default is to add 1 tab. Specify file names or\n");
	fprintf(stderr," use stdin/stdout. - Flags:\n");
	fprintf(stderr," -b add blanks instead of tabs\n");
	fprintf(stderr," -# integer number of characters to add\n");
	fprintf(stderr," -? display specifications\n");
}
