#include "graph.h"

struct BitMap   *bm   = NULL;
struct RastPort *rast = NULL;

void cleanup_drawing(void)
{
    int i;

    if (bm) {
        for (i=0; i<DEPTH; ++i) {
            if (bm->Planes[i]) {
                FreeRaster(bm->Planes[i], WIDTH, HEIGHT);
            }
        }
    }
}

static int getbitmap(void)
{
    int i;

    bm = (struct BitMap *)malloc(sizeof(struct BitMap));
    if (!bm) {
        message("Error: Not enough memory to allocate bitmap.");
        return 0;
    }
    InitBitMap(bm, DEPTH, WIDTH, HEIGHT);
    for (i = 0; i<DEPTH; ++i) {
        if (bm->Planes[i] = (PLANEPTR)AllocRaster(WIDTH, HEIGHT)) { 
            /* clear it */
            BltClear(bm->Planes[i], RASSIZE(WIDTH,HEIGHT), 0);
        } else {
            /* Memory allocation failed */
            message("Error: Not enough memory to allocate raster.");
            return 0;
        }
    }
    /* success */
    return 1;
}

/* Experimental.  Where do I get dpi? */
void getprefinfo(void)
{

   /* under construction */
   struct Preferences pref;
   GetPrefs(&pref, sizeof(struct Preferences));
   printf("Prefs: \n");
   printf("PrintDensity     %d \n", (int)pref.PrintDensity);
   printf("FontHeight       %d \n", (int)pref.FontHeight);
   printf("BaudRate         %d \n", (int)pref.BaudRate);
   printf("PrintMaxWidth    %d \n", (int)pref.PrintMaxWidth);
   printf("PrintMaxHeight   %d \n", (int)pref.PrintMaxHeight);
   printf("RowSizeChange    %d \n", (int)pref.RowSizeChange);
   printf("ColumnSizeChange %d \n", (int)pref.ColumnSizeChange);
}

int getraster(void)
{
#if 0
    getprefinfo();
#endif
    if (getbitmap()) {
        rast = (struct RastPort *)malloc(sizeof(struct RastPort));
        if (rast) {
            InitRastPort(rast);
            SetAPen(rast, 1);
            SetBPen(rast, 0);
            rast->BitMap = bm;
            return 1;
        }
    } else {
        message("Error: not enough memory to allocate RastPort.");
    }
    /* couldn't get raster or bitmap */
    return 0;
}

void freeraster(void)
{
    cleanup_drawing();

    free(bm);
    rast->BitMap = bm = NULL;
    free(rast);
    rast = NULL;
}
