/*
 *  FILE: bitplane.c
 *  Support routines for dynamic (de)allocation of bitplanes for bitmaps
 *  and/or image data.
 *
 *  Public Domain, but keep my name in it as the original author.
 *  31-Aug-88	Jan Sven Trabandt   first release version
 */


#define I_AM_BITPLANE
#include "gimmelib/gimmefuncs.h"
#include "gimmelib/bitplane.h"


ULONG gimmeBitPlanes( bm, myflags )
    struct BitMap   *bm;
    ULONG	    myflags;
{
    SHORT   i;
    SHORT   width, height, depth;
    ULONG   planesize;

#ifdef GIMME_WIMPY
    if( !bm ) {
	return( GBP_ERROR );
    }
#endif
    width = bm->BytesPerRow << 3;
    height = bm->Rows;
    depth = bm->Depth;
    planesize = RASSIZE((ULONG)width, (ULONG)height);
    bm->Planes[0] = NULL;
    if( myflags & GBP_CONTIGUOUS ) {
	if( bm->Planes[0] = AllocMem( (ULONG)(depth) * planesize,
					MEMF_CHIP | MEMF_CLEAR) ) {
	    for( i = 1; i < depth; ++i ) {
		bm->Planes[i] = (UBYTE *)(bm->Planes[i-1]) + planesize;
	    } /* for */
	    return( GBP_CONTIGUOUS );
	}
    }
    if( (myflags & GBP_SEPARATE) || !myflags ) {
	for( i = 0; i < depth; ++i ) {
	    if( !(bm->Planes[i] = (PLANEPTR)
				    AllocRaster((ULONG)width,(ULONG)height)) ) {
		while( --i >= 0 ) {
		    FreeRaster( bm->Planes[i], (ULONG) bm->BytesPerRow << 3,
				    (ULONG) bm->Rows );
		} /* while */
		return( GBP_ERROR );
	    }
	    BltClear( bm->Planes[i], planesize, 0L );
	} /* for */
	return( GBP_SEPARATE );
    }
    return( GBP_ERROR );
} /* gimmeBitPlanes */


short getRidOfBitPlanes( bm, myflags )
    struct BitMap   *bm;
    ULONG	    myflags;
{
    SHORT   i;
    SHORT   width, height, depth;

#ifdef GIMME_WIMPY
    if( !bm ) {
	return( -1 );
    }
#endif
    width = bm->BytesPerRow << 3;
    height = bm->Rows;
    depth = bm->Depth;
    if( myflags & GBP_CONTIGUOUS ) {
	FreeMem( bm->Planes[0],
		    (ULONG)(depth) * RASSIZE((ULONG)width,(ULONG)height) );
    } else {
	for( i = 0; i < depth && bm->Planes[i]; ++i ) {
	    FreeRaster( bm->Planes[i], (ULONG) width, (ULONG) height );
	} /* for */
    }
    return( 0 );
} /* getRidOfBitPlanes */
