/*
          Head - Display the first lines of a file.

          Original effort by Fabio Rossetti. Inspired by the head program
          by Gary Brant found on <>< 179.

	  (c) 1989 by Fabio Rossetti.

	  To compile under Lattice C v5.0x use:

		lc  -O -v -cus head
		blink lib:cres.o head.o to head lib lib:a.lib lib:lc.lib sd nd

*/

#include <exec/types.h>
#include <exec/memory.h>
#include <exec/libraries.h>
#include <libraries/dos.h>
#include <libraries/dosextens.h>
#include <libraries/arpbase.h>
#include <arpfunctions.h>
#include <proto/exec.h>
#include <proto/dos.h>		


struct ArpBase *ArpBase=NULL;
struct Process *Pr;
LONG argc;

#define NARGS 4
#define BFSIZE 256	
#define FROM	argv[0]
#define TO	argv[1]
#define LIN	argv[2]
#define BAN	argv[3]
STRPTR argv[NARGS];

TEXT *Buf,*OBuf;
TEXT Banner[256];

struct UserAnchor {
	struct	AnchorPath	ua_AP;
	BYTE	moremem[255];	/* extension */
};
struct	UserAnchor *Anchor=NULL;

/* Trick to keep code down to size */
VOID MemCleanup()
{
}

/* shutdown routine */
VOID Cleanup(r1,r2,msg)
LONG r1,r2;
STRPTR msg;
{
	if (msg) Puts(msg);
	if (ArpBase) CloseLibrary((struct Library *)ArpBase);
	Pr->pr_Result2 = r2;
	exit(r1);
}

VOID Head(Inp,Out,lines)
BPTR Inp,Out;
ULONG lines;

{

	REGISTER TEXT c;
	REGISTER ULONG count,l=0,fl=0,i,obp=0;

	/* read until EOF */
	while(count = Read(Inp,Buf,BFSIZE))	{

		/* check break */
		if (SetSignal(0,0) & SIGBREAKF_CTRL_C) 
			Cleanup(RETURN_WARN,NULL,"***Break");

		/* scan buffer */	
		for(i=0; i < count; i++) {
	
			c = *(Buf+i);
	
			*(OBuf + obp++) = c;

			if (obp >= BFSIZE) {
				(VOID)Write(Out,OBuf,obp);
				obp = 0;}

			/* end of line ? */	
			if (c == '\n' ) {
					l++;
					if (l >= lines) {
					if (obp) (VOID)Write(Out,OBuf,obp);
					obp = 0;
					fl=1;
					break;
					}
				}
			}

	if (fl) break;
	}
	
	if (obp) (VOID)Write(Out,OBuf,obp);
}

VOID _main(Line)
STRPTR Line;
{



	BPTR infh,outfh;
	LONG Lines,Result,i=0;
	char **ArV;
	Pr = (struct Process*)FindTask(NULL);
	
	if(!(ArpBase = (struct ArpBase*)OpenLibrary(ArpName,ArpVersion)))
			Cleanup(RETURN_FAIL,ERROR_INVALID_RESIDENT_LIBRARY,NULL);
	
	/* parse command line */
	for (argc=0;argc < NARGS ;++argc)
		argv[argc] = (STRPTR) NULL;

	while(*Line > ' ')
		++Line;

	if((argc = GADS(++Line,
		strlen(Line),
		"Usage: Head [Files file1 file2 ...] [TO filename] [LIN linenumber] [BAN]",
		argv,
		"Files/...,TO/K,LIN/K,BAN/S" )) < 0)
			Cleanup(RETURN_WARN,NULL,FROM);


		if (!(Buf = ArpAllocMem(BFSIZE,MEMF_CLEAR)) ||
		!(OBuf = ArpAllocMem(BFSIZE,MEMF_CLEAR)))
				Cleanup(RETURN_FAIL,ERROR_NO_FREE_STORE,"Error: no memory");


	
	if (LIN) {
		Lines = Atol(LIN);
		if((Errno == ERRBADINT) || (Lines <=0))
			Cleanup(RETURN_ERROR,NULL,"Bad args");
		}
	else Lines = 10;

	if(TO) {
			if(!(outfh=ArpOpen(TO,MODE_NEWFILE))) {
				Printf("Can't open %s\n",TO);
				Cleanup(RETURN_ERROR,ERROR_OBJECT_NOT_FOUND,NULL);
				}
			}
	else outfh = Output();


	ArV = (char **)FROM;
	if (ArV[0]) {

	if ( Anchor = (struct UserAnchor *)ArpAlloc( (ULONG)sizeof( *Anchor )) )
	{
		Anchor->ua_AP.ap_Length = 255;	/* Want full path built */
		
	}
	else
		Cleanup(RETURN_FAIL,ERROR_NO_FREE_STORE,"Error: no memory");
	
	while (ArV[i] != NULL) {

	Result = FindFirst(ArV[i],(struct AnchorPath*) Anchor);

	while (Result == 0) {

		if (Anchor->ua_AP.ap_Info.fib_DirEntryType < 0) {
			if(!(infh=ArpOpen(Anchor->ua_AP.ap_Buf,MODE_OLDFILE))) {
				Printf("Can't open %s\n",FROM);
				Cleanup(RETURN_ERROR,ERROR_OBJECT_NOT_FOUND,NULL);
					}
			else {
				if (BAN) {
					PathName(ArpLock(Anchor->ua_AP.ap_Buf,
					ACCESS_READ),Banner,255);
					FPrintf(outfh,"*** File %s ***\n",
					Banner);
					}
			Head(infh,outfh,Lines);
			}
			}
		else {
			Printf("%s is a directory !\n",ArV[i]);
			Cleanup(RETURN_ERROR,ERROR_OBJECT_WRONG_TYPE,NULL);
			}
		/*else 
			Printf("Can't find %s\n",FROM);
			Cleanup(RETURN_ERROR,ERROR_OBJECT_NOT_FOUND,NULL);
			*/

		Result = FindNext((struct AnchorPath*) Anchor );	
		}
		i++;
		}
	}
	
	else Head(Input(),outfh,Lines);

	Cleanup(NULL,NULL,NULL);


}