#include <exec/types.h>
#include <devices/clipboard.h>
#include <dos/dos.h>
#include <libraries/iffparse.h>
#include <proto/exec.h>
#include <proto/dos.h>
#include <string.h>

#define DOSPRINT(x) Write(Output(),x,strlen(x));

void cleanup(char *,int);
int OpenClip(void);
void CloseClip(void);

struct DosLibrary *DOSBase=NULL;
struct IOClipReq *ioc=NULL;
struct MsgPort *port=NULL;
char buf[102],clipb=FALSE,ver[]="\0$VER: OpenClip 1.0 " __AMIGADATE__;
BPTR fh=NULL;

int __saveds __asm not_main(register __a0 char *args, register __d0 long len) {
	ULONG length,formlength;
	if(!(DOSBase=(struct DosLibrary *)OpenLibrary("dos.library",0L))) {
		return(20);
	}
	if(!OpenClip()) cleanup("Couldn't open clipboard.device\n",20);
	args[len-1]=0;
	if(!(fh=Open(args,MODE_OLDFILE))) {
		DOSPRINT("Couldn't open ")
		DOSPRINT(args)
		DOSPRINT("\n")
		cleanup(NULL,10);
	}
	Seek(fh,0,OFFSET_END);
	length=Seek(fh,0,OFFSET_BEGINNING);
	formlength=length+12;
	ioc->io_Offset=0;
	ioc->io_ClipID=0;
	ioc->io_Command=CMD_WRITE;
	ioc->io_Length=4;
	ioc->io_Data=(APTR)"FORM";
	DoIO((struct IORequest *)ioc);
	ioc->io_Data=(APTR)&formlength;
	DoIO((struct IORequest *)ioc);
	ioc->io_Data=(APTR)"FTXT";
	DoIO((struct IORequest *)ioc);
	ioc->io_Data=(APTR)"CHRS";
	DoIO((struct IORequest *)ioc);
	ioc->io_Data=(APTR)&length;
	DoIO((struct IORequest *)ioc);
	while((length=Read(fh,buf,100))) {
		if(length==-1) {
			DOSPRINT("Error reading file\n");
			break;
		}
		ioc->io_Length=length;
		ioc->io_Data=(APTR)buf;
		DoIO((struct IORequest *)ioc);
	}
	ioc->io_Command=CMD_UPDATE;
	DoIO((struct IORequest *)ioc);
	cleanup(NULL,0);
}

void cleanup(char *msg,int code) {
	if(fh) Close(fh);
	if(clipb) CloseClip();
	if(DOSBase) {
		if(msg) DOSPRINT(msg);
		CloseLibrary((struct Library *)DOSBase);
	}
	Exit(code);
}

int OpenClip(void) {
	if(!(port=CreatePort(NULL,0L))) return(FALSE);
	if(!(ioc=(struct IOClipReq *)CreateExtIO(port,sizeof(struct IOClipReq)))) {
		DeletePort(port);
		return(FALSE);
	}
	if(OpenDevice("clipboard.device",0,(struct IORequest *)ioc,0)) {
		DeleteExtIO((struct IORequest *)ioc);
		DeletePort(port);
		return(FALSE);
	}
	clipb=TRUE;
	return(TRUE);
}

void CloseClip(void) {
	CloseDevice((struct IORequest *)ioc);
	DeleteExtIO((struct IORequest *)ioc);
	DeletePort(port);
}
