-- File: PupNameServerCold.mesa,  Last Edit: HGM March 8, 1981  1:23 AM

DIRECTORY
  Process USING [Pause, MsecToTicks],
  Runtime USING [IsBound],
  Event USING [AddNotifier, Item, Reason],

  MiscServerDefs USING [
    PupMiscServerOn, PupMiscServerOff, IgnoreThisPacket, SetNameServer],
  NameServerDefs USING [
    busy, CloseDirectoryFile, OpenDirectoryFile, PupNameServer, UpdatePicture];

PupNameServerCold: PROGRAM
  IMPORTS Process, Runtime, Event, MiscServerDefs, NameServerDefs
  EXPORTS NameServerDefs =
  BEGIN OPEN NameServerDefs;

  useCount: CARDINAL ← 0;
  nameRunning: PUBLIC BOOLEAN ← FALSE;

  eventItem: Event.Item ← [eventMask: 177777B, eventProc: Broom];

  PupNameServerOn: PUBLIC PROCEDURE =
    BEGIN
    IF (useCount ← useCount + 1) = 1 THEN
      BEGIN nameRunning ← TRUE; Starter[]; END;
    MaybeUpdatePicture[];
    END;

  Starter: PROCEDURE =
    BEGIN
    MiscServerDefs.PupMiscServerOn[];
    OpenDirectoryFile[];
    MiscServerDefs.SetNameServer[PupNameServer];
    END;

  PupNameServerOff: PUBLIC PROCEDURE =
    BEGIN
    IF useCount # 0 AND (useCount ← useCount - 1) = 0 THEN
      BEGIN nameRunning ← FALSE; Stopper[]; END;
    MaybeUpdatePicture[];
    END;

  Stopper: PROCEDURE =
    BEGIN
    MiscServerDefs.SetNameServer[MiscServerDefs.IgnoreThisPacket];
    MiscServerDefs.PupMiscServerOff[];
    CloseDirectoryFile[];
    WHILE busy DO Process.Pause[Process.MsecToTicks[1000]]; ENDLOOP;
    END;

  MaybeUpdatePicture: PROCEDURE =
    BEGIN
    IF Runtime.IsBound[NameServerDefs.UpdatePicture] THEN
      NameServerDefs.UpdatePicture[];
    END;

  Broom: PROCEDURE [why: Event.Reason] =
    BEGIN
    SELECT why FROM
      makeImage, makeCheck, stopMesa => IF nameRunning THEN Stopper[];
      startImage, restartCheck, continueCheck => IF nameRunning THEN Starter[];
      ENDCASE => NULL;
    END;

  Event.AddNotifier[@eventItem];
  END.