/*
 * Usage:       PasteClip
 * Function:    Show the content of the clipboard if it is text.
 * Description: This is an example of the standard way of using the 
 *              iffparser in the most simple way, i.e. in the 
 *              RAWSTEP-mode when you want to read data from the 
 *              clipboard (and files).
 *
 * Written by:  Michael Jansson. 1990-12-08
 */


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

#define NAME        "Error in PasteClip: "
#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

struct Library *IFFParseBase;

void
main(void)
{
    struct ContextNode *chunk = NULL;
    struct IFFHandle *iff = NULL;
    long error, size;
    char *string;

    /* Open and initiate the usual stuff. */
    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_READ)) {
        puts(ERR_OPEN);
        goto die;
    }

    /* Read the data. */
    do {
        switch(error=ParseIFF(iff, IFFPARSE_RAWSTEP)) {
        case IFFERR_EOC:
            break;
        case IFFERR_EOF:
            goto die;
            break;
        case SUCCESS:
            chunk = CurrentChunk(iff);
            /* The proper way to know when the propper chunk has been reached
             * is to keep track of it with flags etc. There is a slight 
             * possibility that there is a CHRS-FTXT in the clipboard that
             * is not part of a FORM-FTXT chunk.
             */
            if (chunk->cn_ID=='CHRS' && chunk->cn_Type=='FTXT') {
                size = chunk->cn_Size;
                if ((string = (char *)AllocMem((long)size, 0L))==NULL) {
                    puts(ERR_MEM);
                    goto die;
                }
                ReadChunkBytes(iff, (APTR)string, (long)size);
                Write(Output(), string, size);
                FreeMem((APTR)string, (long)size);
                goto die;
            }
            break;
        default:
            printf(ERR_FAILED, error);
            goto die;
            break;
        }
    } while (TRUE);

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