#include <libraries/xpk.h>           /* xType - Unpack file to stdout */
#include <proto/exec.h>
#include <proto/dos.h>
#include <stdlib.h>
#include <string.h>

struct Library *XpkBase;
UBYTE errbuf[XPKERRMSGSIZE+1], *outbuf;
long outbuflen;

void end( char *text )
{
	if( text )    Write(Output(), text, strlen(text));
	if( XpkBase ) CloseLibrary( XpkBase );
	exit(text ? 10 : 0);
}

void main(int argc, char *argv[])
{
	XFH   *xfh;
	UBYTE *ptr, *last, *eol;
	int i, len;

	if( !(XpkBase=OpenLibrary( XPKNAME, 0)))
		end("Cannot open " XPKNAME "\n");

	if( argc<2 || !strcmp(argv[1],"?"))
		end("Usage: xType filename\n");

	for( i=1; i<argc; i++ ) {

		if(XpkOpenTags( &xfh, XPK_InName,argv[i], XPK_PassThru,TRUE, TAG_DONE ))
			end(strcat(errbuf,"\n"));

		if( !(outbuf=(UBYTE*)AllocMem( outbuflen=xfh->NLen+XPK_MARGIN,0)))
			end("Out of memory\n");

		while( (len=XpkRead(xfh, outbuf, XPKLEN_ONECHUNK ))>0 ) {

			ptr = (UBYTE*)outbuf;
			last= ptr +   len;
			*last='\n';

			do {
				if( SetSignal(0L,0L) & SIGBREAKF_CTRL_C )
					end("***Break");

				if( !(eol=strchr(ptr, '\n')))
					eol=last-1;
				Write(Output(),ptr,1+eol-ptr);
				ptr=eol+1;
			} while( ptr<last );
		}

		if( XpkClose(xfh) || len )
			end(strcat(errbuf,"\n"));

		FreeMem( outbuf, outbuflen );
		outbuf=NULL;
	}

	end( NULL );
}
