#include <stdio.h>
#include <local.h>

#define	LINSIZ	255	/* max bytes in 1 line  */
#define DEFAULT	10	/* lines to use default */

/*
 * HEAD.C - the head of a file, works like a filter if there are no
 * files specified on the command line, the unix utility does not
 * allow wildcards in the head and tail commands, so they are not
 * supported, usage like: head {/n} {file file ... }
 */

static	char *Program [] = { "S. Leoce, *nix(tm) head.c"
			     "v1.0 r1.0 svclvl 1 va@psj" };

static	char *Usage = "usage: head [/hn#] [file file ...]";

#include "b:cmdline.c"

int main (argc, argv)
char	*argv[];
int	 argc;
{
	short	unsigned LineOption = FALSE;
	short	unsigned header     = FALSE;
	long	register number = DEFAULT;	/* default lines to write */
	FILE	*fp;				/* file stream pointer	  */
	char	line [LINSIZ];			/* input line		  */

	opterr = FALSE;
	while ((LineOption = getopt(argc, argv, "hn:")) != EOF)
		switch(LineOption) {
		case '?':
			fprintf(stderr,"head: illegal option %c\n",badopt);
			_exit (0x04);
		case 'n':
			number = max(atol(optarg),0);
			break;
		case 'h':
			header = TRUE;
		}	/* switch closed here */

	if (number == 0)
		_exit(fprintf(stderr,"%s\n", Usage) + 0x04);

	if (argv[optind] == NULL)	/* use like a filter now	  */
		while(gets(line) != NULL && number-- > 0)
			printf("%s\n",line);
	else {				/* do each file			  */
		long save = number;
		while (argv[optind] != NULL) {
			putchar('\n');
			if (header)
				printf("--------------- %s\n",argv[optind]);
			number = save;
			if ((fp = fopen(argv[optind++], "r")) == NULL)
				_exit(perror(strcat("head: can't open ",
					strupr(argv[optind-1]))) + 0x10);
			number = save;
			while(fgets(line, LINSIZ, fp) != NULL && number-- > 0)
				printf("%s", line);
			fclose (fp);
		}
	}	/* else is closed */

	return (0);
}