/*
 * Usage:       CutClip [string]
 * Function:    Put a given in the clipboard as a FTXT-chunk.
 * Description: This is an example of the standard way of using the 
 *              iffparser when you want to write data to the clipboard
 *              (It works the same way for files).
 *
 * Written by:  Michael Jansson. 1990-12-08
 */


#include <libraries/iffparse.h>
#include <proto/iffparse.h>
#include <setjmp.h>

#define NAME        "Error in cutclip: "
#define ERR_USE     "Usage: CutClip [string]"
#define ERR_LIB     NAME "Could not open iffparse.library!"
#define ERR_MEM     NAME "Out of memory!"
#define ERR_CLIP    NAME "Could not open the clipboard!"
#define ERR_OPEN    NAME "Could not open primary clip in clipboard!"
#define ERR_FAILED  NAME "Failed to read the clipboard (Error Code: %ld)\n!"
#define LEVEL       ". "
#define DONE        "Done!"
#define SUCCESS     0L
#define Safe(fnc)   if ((error=(fnc))<0L) longjmp(env, (int)error)

struct Library *IFFParseBase;

void
main(int argc, char **argv)
{
    struct IFFHandle *iff = NULL;
    jmp_buf env;
    long error;
    
    if (argc!=2) {
        puts(ERR_USE);
        goto die;
    }

    /* Open all the stuff that is needed! */
    if ((IFFParseBase=OpenLibrary("iffparse.library", 0L))==NULL) {
        puts(ERR_LIB);
        goto die;
    }
    if ((iff = AllocIFF())==NULL) {
        puts(ERR_MEM);
        goto die;
    }
    if ((iff->iff_Stream=(ULONG)OpenClipboard(0L))==0L) {
        puts(ERR_CLIP);
        goto die;
    }
    InitIFFasClip(iff);
    if (OpenIFF(iff, IFFF_WRITE)) {
        puts(ERR_OPEN);
        goto die;
    }

    /* Let's be very careful... */
    if (!(error=setjmp(env))) {
        /* Start on the FORM-FTXT chunk... */
        Safe(PushChunk(iff, 'FTXT', 'FORM', IFFSIZE_UNKNOWN));

            /* ...continue on the CHRS-FTXT chunk.*/
            Safe(PushChunk(iff, 0L, 'CHRS', IFFSIZE_UNKNOWN));
            Safe(WriteChunkBytes(iff, (APTR)argv[1], (long)strlen(argv[1])));
            Safe(PopChunk(iff));

        /* Finish the outer most chunk. */
        Safe(PopChunk(iff));
    }

    /* Exit gracefully. */
die:
    if (iff) {
        CloseIFF(iff);
        if (iff->iff_Stream)
           CloseClipboard((struct ClipboardHandle *)iff->iff_Stream);
        FreeIFF(iff);
    }
    if (IFFParseBase)
        CloseLibrary(IFFParseBase);
    exit(0);
}
