#include <stdio.h>
#include <stdlib.h>
#include <intuition/intuition.h>
#include <intuition/screens.h>
#include <exec/types.h>
#include <hardware/custom.h>
#include <hardware/cia.h>
#include <proto/intuition.h>
#include <proto/graphics.h>

#define CIAAPRA 0xbfe001

#define LEFT_BUTTON 1
#define RIGHT_BUTTON 2

extern struct Custom far custom;
struct CIA *cia = (struct CIA *) CIAAPRA;

static void  showImage(unsigned char *buf, unsigned char *grey, int Width, int Height);
UBYTE Mouse();

struct Screen *scr;
struct IntuitionBase *IntuitionBase;
struct GfxBase *GfxBase;
struct NewScreen ns;

UBYTE Mouse()
{
    UBYTE result=0;
    UWORD pot;
    
    custom.potgo=0xff00;
    pot=custom.potinp;
    
    result+=!(cia->ciapra & 0x0040)?LEFT_BUTTON:0;
    result+=!(pot&0x0400)?RIGHT_BUTTON:0;
    return result;
}

static void  showImage(buf, grey, Width, Height)
unsigned char *buf;
unsigned char *grey;
int Width;
int Height;
{
   register int i, x, y;
   struct RastPort *rp;
   
   IntuitionBase=(struct IntuitionBase *) OldOpenLibrary("intuition.library");
   if(!IntuitionBase) exit(100);

   GfxBase=(struct GfxBase *) OldOpenLibrary("graphics.library");
   if(!GfxBase) exit(100);
        
        scr=(struct Screen *)OpenScreenTags(&ns, SA_Width, Width, SA_Height, Height,
                SA_Depth, 4, SA_DisplayID, 0x8004,
                SA_Type, CUSTOMSCREEN | AUTOSCROLL,
                SA_Overscan, OSCAN_TEXT, SA_AutoScroll, TRUE,
                SA_Quiet, 1, TAG_END);
        if(scr)
        {
                rp=&scr->RastPort;
                for(i=0;i<16;i++)
                        SetRGB4(&scr->ViewPort, i, i, i, i);
                for(y=0;y<Height;y++)
                {
                        for(x=0;x<=Width;x++)
                        {
                               SetAPen(rp, grey[*buf++]);
                               WritePixel(rp, x, y);
                        }
                     if(Mouse()&RIGHT_BUTTON) break;
                     }
                while(!(Mouse()&RIGHT_BUTTON));
                CloseScreen(scr);
        }
        CloseLibrary((struct Library *)GfxBase);
        CloseLibrary((struct Library *)IntuitionBase);
}
