/**********************************************************************
 *
 *       fichier:  BMap.c
 *
 *       fonction: Alloc & Free de BitMap
 *
 *       creation: .........  gauthier groult
 *       revision: 20-Sep-88  jm forgeas
 *
 **********************************************************************/


#include <exec/types.h>
#include <exec/memory.h>
#include <graphics/rastport.h>
#include <intuition/intuisup.h>

#ifdef USE_PROTOS
#include <proto/all.h>
#endif


VOID is_FreeBMap( bitmap )
struct BitMap *bitmap;
{
  UBYTE i;

    if (!bitmap) return;
    for(i=0; i<bitmap->Depth; i++)
        if (bitmap->Planes[i]) FreeMem( bitmap->Planes[i], bitmap->BytesPerRow * bitmap->Rows );
    FreeMem( bitmap, sizeof(struct BitMap) );
}

struct BitMap *is_AllocBMap( depth, width, height )
UBYTE depth;
UWORD width, height;
{
    struct BitMap *bitmap;
    UBYTE i;

        if ((bitmap = (struct BitMap *) AllocMem( sizeof(struct BitMap), MEMF_PUBLIC | MEMF_CLEAR)))
            {
            InitBitMap( bitmap, depth, width, height );
            if (!(bitmap->Planes[0] = (PLANEPTR)AllocRaster(width, height*depth)))
                    {
                    is_FreeBMap( bitmap );
                    return(NULL);
                    }
            for (i=1; i<depth; i++)
                 bitmap->Planes[i] = (PLANEPTR)(bitmap->Planes[0]+RASSIZE(width, height*i));
            BltClear( bitmap->Planes[0], RASSIZE(width, height*depth), 1);
            }
        return( bitmap );
}

VOID is_FreeRPort( rport )
struct RastPort *rport;
{
    if (rport) FreeMem( rport, sizeof(struct RastPort) );
}

struct RastPort *is_AllocRPort()
{
  struct RastPort *rport;

    if (rport = (struct RastPort *) AllocMem( sizeof(struct RastPort), MEMF_PUBLIC | MEMF_CLEAR))
    InitRastPort( rport );
    return( rport );
}

VOID is_FreeBMapRPort( rport )
struct RastPort *rport;
{
    is_FreeBMap( rport->BitMap );
    is_FreeRPort( rport );
}


struct RastPort *is_AllocBMapRPort( depth, width, height )
UBYTE  depth;
UWORD  width, height;
{
  struct RastPort *rport=NULL;

    if (rport = is_AllocRPort())
        {
        if (! (rport->BitMap = is_AllocBMap( depth, width, height )))
            {
            is_FreeBMapRPort( rport );
            rport = NULL;
            }
        }
    return( rport );
}
