/*
 *  FILE: dbuf.c
 *  Support routines for converting a single-buffered Intuition screen
 *  into a double-buffered screen and back.
 *
 *  Public Domain, but keep my name in it as the original author.
 *  31-Aug-88	Jan Sven Trabandt   first release version
 */


#define I_AM_DBUF
#include "gimmelib/gimmefuncs.h"
#include "gimmelib/minterm.h"


short makeDBuf( screen, bmptr )
    struct Screen   *screen;
    struct BitMap   **bmptr;
{
#ifdef GIMME_WIMPY
    if( !screen || !bmptr ) {
	return( -1 );
    }
#endif
    if( !*bmptr ) {
	*bmptr = gimmeBitMap( screen->BitMap.Depth, screen->Width,
				screen->Height );
	if( !*bmptr ) {
	    return( -1 );
	}
    }
    screen->RastPort.BitMap = *bmptr;	    /* draw to back buffer */
    return( 0 );
} /* makeDBuf */


short unmakeDBuf( screen, bmptr, bm )
    struct Screen   *screen;
    struct BitMap   **bmptr;
    struct BitMap   *bm;
{
    struct BitMap   *viewbm;

#ifdef GIMME_WIMPY
    if( !screen || !bmptr ) {
	return( -1 );
    }
#endif
    viewbm = screen->ViewPort.RasInfo->BitMap;
    if( !(screen->Flags & CUSTOMBITMAP) && viewbm == *bmptr ) {
	BltBitMap( viewbm, 0L, 0L, screen->RastPort.BitMap, 0L, 0L,
		    (ULONG)(bm->BytesPerRow) << 3, (ULONG) bm->Rows,
		    (ULONG) GIM_MINTERM_COPY, 0x0ffL, NULL );
	swapDBuf( screen, GIM_MINTERM_DEST );
    }
    if( viewbm != screen->RastPort.BitMap ) {
	screen->RastPort.BitMap = viewbm;
    }
    if( bm ) {
	getRidOfBitMap( bm );
    }
    return( 0 );
} /* unmakeDBuf */


short swapDBuf( screen, minterm )
    register struct Screen  *screen;
    SHORT   minterm;
{
    struct BitMap   *bm;

#ifdef GIMME_WIMPY
    if( !screen ) {
	return( -1 );
    }
#endif
    Forbid();
    bm = screen->ViewPort.RasInfo->BitMap;
    if( bm == screen->RastPort.BitMap ) {
	Permit();
	return( 0 );
    }
    screen->ViewPort.RasInfo->BitMap = screen->RastPort.BitMap;
    screen->RastPort.BitMap = bm;
    Permit();
    MakeScreen( screen );
    RethinkDisplay();
    if( minterm != GIM_MINTERM_DEST ) {
	BltBitMap( screen->ViewPort.RasInfo->BitMap, 0L, 0L, bm, 0L, 0L,
		    (ULONG)(bm->BytesPerRow) << 3, (ULONG) bm->Rows,
		    (ULONG) minterm, 0x0ffL, NULL );
    }
    return( 0 );
} /* swapDBuf */
