/* write string to clipboard.device */

#include <exec/types.h>
#include <exec/ports.h>
#include <exec/io.h>
#include <exec/memory.h>
#include <exec/exec.h>
#include <devices/clipboard.h>
#include <libraries/dosextens.h>
#include <libraries/dos.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

/*--Functions--*/

int WriteLong(struct IOClipReq *,long *);
struct IOClipReq *CBOpen(ULONG);
int CBWFTXT(struct IOClipReq *,char *);
void CBClose(struct IOClipReq *);


int WriteLong(ior, ldata)
struct IOClipReq *ior;
long *ldata;
{
ior->io_Data    = (STRPTR)ldata;
ior->io_Length  = 4L;
ior->io_Command = CMD_WRITE;
DoIO( (struct IORequest *) ior);
if (ior->io_Actual == 4)
    {
    return( ior->io_Error ? FALSE : TRUE);
    }
return(FALSE);
}


struct IOClipReq *CBOpen(ULONG unit)
{
struct MsgPort *mp;
struct IOStdReq *ior;

if(mp = CreatePort(0L,0L))
    {
    if(ior=CreateExtIO(mp,sizeof(struct IOClipReq)))
        {
        if (!(OpenDevice("clipboard.device",unit,ior,0L)))
            {
            return((struct IOClipReq *)ior);
            }
        DeleteExtIO(ior);
        }
    DeletePort(mp);
    }
return(NULL);
}

int CBWFTXT(struct IOClipReq *ior,char *string)
{
ULONG length, slen;
BOOL odd;
int success;
slen = strlen(string);
odd = (slen & 1);               /* pad byte flag */
length = (odd) ? slen+1 : slen;
/* initial set-up for Offset, Error, and ClipID */
ior->io_Offset = 0;
ior->io_Error  = 0;
ior->io_ClipID = 0;
/* Create the IFF header information */
WriteLong(ior, (long *) "FORM");     /* "FORM"             */
length+=12L;                         /* + "[size]FTXTCHRS" */
WriteLong(ior, &length);             /* total length       */
WriteLong(ior, (long *) "FTXT");     /* "FTXT"             */
WriteLong(ior, (long *) "CHRS");     /* "CHRS"             */
WriteLong(ior, &slen);               /* string length      */
/* Write string */
ior->io_Data    = (STRPTR)string;
ior->io_Length  = slen;
ior->io_Command = CMD_WRITE;
DoIO( (struct IORequest *) ior);
/* Pad if needed */
if (odd)
    {
    ior->io_Data   = (STRPTR)"";
    ior->io_Length = 1L;
    DoIO( (struct IORequest *) ior);
    }
/* Tell the clipboard we are done writing */
ior->io_Command=CMD_UPDATE;
DoIO( (struct IORequest *) ior);
/* Check if io_Error was set by any of the preceding IO requests */
success = ior->io_Error ? FALSE : TRUE;
return(success);
}

void CBClose(struct IOClipReq *ior)
{
struct MsgPort *mp;
mp = ior->io_Message.mn_ReplyPort;
CloseDevice((struct IOStdReq *)ior);
DeleteExtIO((struct IOStdReq *)ior);
DeletePort(mp);
}

