#define SCREENTOP\
   (screen->TopEdge << ((screen->ViewPort.Modes & LACE)? 0: 1))

IMPORT struct IntuitionBase *IntuitionBase;
IMPORT struct MsgPort *Sharedport;
IMPORT WORD Sharedrefs;

struct Screen *WhichScreen()
{ 
    REGISTER struct Screen *screen;
    Forbid();
    screen = IntuitionBase->FirstScreen;
    while (screen && IntuitionBase->MouseY < SCREENTOP) {
        screen = screen->NextScreen;
    }
    if (screen == NULL) {     /* Shouldn't happen */
        screen = IntuitionBase->ActiveScreen;
    }
    Permit();
    return screen;
}

struct Window *WhichWindow(screen)
struct Screen *screen;
{ 
    struct Layer *layer;
    layer = (struct Layer *)WhichLayer(&screen->LayerInfo,
      (LONG)screen->MouseX, (LONG)screen->MouseY);
    if (layer) {
        return (struct Window *)layer->Window;
    } else {
        return NULL;
    }
}

struct Window *opensharedwindow(nw)
struct NewWindow *nw;
{
    struct Window *win;
    struct Screen scr;

    if (Sharedport) {
        nw->IDCMPFlags = NULL;
    } else {
        nw->IDCMPFlags = CLOSEWINDOW;
    }
    if (!GetScreenData(&scr, (LONG)sizeof(struct Screen), WBENCHSCREEN, NULL)) {
        return NULL;     /* No WB */
    }
    if (nw->TopEdge+nw->Height > scr.Height) {
        nw->TopEdge = scr.Height-nw->Height;
    }
    if (nw->LeftEdge+nw->Width > scr.Width) {
        nw->LeftEdge = scr.Width-nw->Width;
    }
    if (nw->TopEdge < 0) {
        nw->TopEdge = 0;
    }
    if (nw->LeftEdge < 0) {
        nw->LeftEdge = 0;
    }

    if (win = OpenWindow(nw)) {
        if (Sharedport) {
            win->UserPort = Sharedport;
            ModifyIDCMP(win, CLOSEWINDOW);
        } else {
            Sharedport = win->UserPort;
        }
        ++Sharedrefs;
    }
    return(win);
}


VOID closesharedwindow(win)
struct Window *win;
{
    Forbid();
    win->UserPort = NULL;
    ModifyIDCMP(win, GADGETUP);     /* NEVER occurs */
    Permit();
    CloseWindow(win);
    --Sharedrefs;
    if (Sharedrefs == 0 && Sharedport) {
        DeletePort(Sharedport);
        Sharedport = NULL;
    }
}

VOID FreePlanes(bm, width, height)
struct BitMap *bm;
LONG width, height;
{ 
    SHORT i;
    for (i=0; i < bm->Depth; i++) {
        if (bm->Planes[i]) {
            FreeRaster(bm->Planes[i], width, height);
        }
    }
}

WORD AllocPlanes(bm, width, height)
struct BitMap *bm;
LONG width, height;
{ 
    WORD i;
    for (i=0; i < bm->Depth; i++) {
        bm->Planes[i] = NULL;
    }
    for (i=0; i < bm->Depth; i++) {
        if (!(bm->Planes[i] = AllocRaster(width, height))) {
            return 0;
        }
    }
    return 1;
}
