/* Auto: make
*/

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

#define Line(pair, xl, yt, xr, yb) \
{ pair->xs = xl; pair->ys = yt; pair->xe = xr; pair->ye = yb; ++pair; }

#define HLine(pair, xl, xr, y) Line(pair, xl, y, xr, y)
#define VLine(pair, yt, yb, x) Line(pair, x, yt, x, yb)

IMPORT struct IntuitionBase *IntuitionBase;

IMPORT struct RastPort rp;

WORD OF;

typedef struct {
    WORD xs, ys;
    WORD xe, ye;
} Pair;

Pair OldFrame[8];
Pair NewFrame[8];

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;
    }
}

STATIC VOID MultiDraw(rp, pairs)
struct RastPort *rp;
Pair *pairs;
{
    REGISTER LONG i = 8;
    REGISTER Pair *coord = pairs;

    while (i--) {
        Move(rp, (LONG)coord->xs, (LONG)coord->ys);
        Draw(rp, (LONG)coord->xe, (LONG)coord->ye);
        coord++;
    }
}

VOID BuildFrame(xl, yt, xr, yb)
WORD xl, yt, xr, yb;
{
    REGISTER LONG tx  = (xr - xl) / 3;
    REGISTER LONG ty  = (yb - yt) / 3;
    REGISTER Pair *pair = &NewFrame[0];

    HLine(pair, xl, xr, yt);
    HLine(pair, xl, xr, yt + ty);
    HLine(pair, xl, xr, yb - ty);
    HLine(pair, xl, xr, yb);
    VLine(pair, yt, yb, xl);
    VLine(pair, yt, yb, xl + tx);
    VLine(pair, yt, yb, xr - tx);
    VLine(pair, yt, yb, xr);
}

VOID EraseFrame()
{
    if (OF) {
        MultiDraw(&rp, &OldFrame[0]);
        OF = 0;
    }
}

VOID DrawFrame()
{
    REGISTER LONG i;

    WaitTOF();
    EraseFrame();
    MultiDraw(&rp, &NewFrame[0]);
    i = 8;
    while (i--) {
        OldFrame[i] = NewFrame[i];
    }
    OF = 1;
}
