/*
	FS1541

	support.c


	These are support routines for PETSCII<->ASCII conversion and
	BCPL conversion.

*/

#include <string.h>

#include <exec/types.h>
#include <exec/execbase.h>
#include <dos/dosextens.h>
#include <dos/filehandler.h>
#include <devices/input.h>
#include <devices/inputevent.h>

#include <proto/exec.h>

#include "support.h"
#include "main.h"

/*-------------------------------------------------------------------------*/

void ReturnPacket(struct DosPacket *packet, LONG res1, LONG res2)
{
	struct MsgPort *mp = packet->dp_Port;

	packet->dp_Port = ourport;
	packet->dp_Res1 = res1;
	packet->dp_Res2 = res2;

	PutMsg(mp, packet->dp_Link);
}

struct DosPacket *GetPacket(struct MsgPort *port)
{
	struct Message *msg;

	if((msg = GetMsg(port)))
		return((struct DosPacket *)msg->mn_Node.ln_Name);
	else
		return(NULL);
}

/*-------------------------------------------------------------------------*/

void copy64name(STRPTR dest, STRPTR src, UBYTE maxlen)
{
	static const UBYTE conv[91]=" !\"#$%&'()·+,-.\\0123456789|;<=>?"
								"@abcdefghijklmnopqrstuvwxyz[£]^{"
								"_ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	UBYTE a;

	while(((a=*src++) != 0xa0) && maxlen--)
		if(a<32 || a>122)
			*dest++ = '_';
		else
			*dest++ = conv[a-32];

	*dest = '\0';
}

void asciito64(STRPTR dest, STRPTR src, UBYTE maxlen)
{
	static const UBYTE conv[91]=" !\"#$%&'()*+,-./0123456789:;<=>?"
								"@abcdefghijklmnopqrstuvwxyz[/]^{"
								"-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	UBYTE a;

	while((a=*src++) && maxlen--)
		if(a<32 || a>122)
			*dest++ = ' ';
		else
			*dest++ = conv[a-32];

	while(maxlen--)
		*dest++ = 0xa0;
}

/*-------------------------------------------------------------------------*/

void SendEvent(BOOL insert)
{
	struct IOStdReq *InputRequest;
	struct MsgPort *InputPort;
	struct InputEvent *ie;

	if((InputPort = (struct MsgPort*)CreateMsgPort()))
	{
		if((InputRequest = (struct IOStdReq*)CreateIORequest(InputPort, sizeof(struct IOStdReq))))
		{
			if(!OpenDevice("input.device", 0, (struct IORequest*)InputRequest, 0))
			{
				if((ie = AllocVec(sizeof(struct InputEvent), MEMF_PUBLIC|MEMF_CLEAR)))
				{
					ie->ie_Class = insert ? IECLASS_DISKINSERTED : IECLASS_DISKREMOVED;
					InputRequest->io_Command = IND_WRITEEVENT;
					InputRequest->io_Data = ie;
					InputRequest->io_Length = sizeof(struct InputEvent);
					DoIO((struct IORequest*)InputRequest);
					FreeVec(ie);
				}
				CloseDevice((struct IORequest*)InputRequest);
			}
			DeleteIORequest (InputRequest);
		}
	    DeleteMsgPort (InputPort);
	}
}
