-- Copyright (C) 1983  by Xerox Corporation. All rights reserved. 
-- CoPilotWatcher.mesa, HGM, 10-Nov-83 19:04:08

DIRECTORY
  Ascii USING [CR],
  DeviceCleanup USING [Item, Await],
  Process USING [Detach, MsecToTicks, Ticks, Pause],
  Put USING [Text],
  SpecialSpace USING [MakeGlobalFrameResident, MakeProcedureResident, SpecialError],
  String USING [AppendChar, AppendLongDecimal, AppendString],
  Time USING [AppendCurrent];

CoPilotWatcher: PROGRAM
  IMPORTS DeviceCleanup, Process, Put, SpecialSpace, String, Time =
  BEGIN
  
  kick: LONG CARDINAL ← 0;

  Init: PROCEDURE =
    BEGIN
    MakeResident[];
    AddCleanup[];
    Process.Detach[FORK Watch[]];
    END;

  MakeResident: PROCEDURE =
    BEGIN
    SpecialSpace.MakeGlobalFrameResident[CoPilotWatcher ! SpecialSpace.SpecialError => CONTINUE];
    SpecialSpace.MakeProcedureResident[AddCleanup ! SpecialSpace.SpecialError => CONTINUE];
    END;

  AddCleanup: PROCEDURE =
    BEGIN
    item: DeviceCleanup.Item;
    DO
      SELECT DeviceCleanup.Await[@item] FROM
        turnOn => kick ← kick + 1;
        ENDCASE;
      ENDLOOP
    END;

  Watch: PROCEDURE =
    BEGIN
    pause: Process.Ticks = Process.MsecToTicks[5000];
    oldKick: LONG CARDINAL ← 0;
    DO
      Process.Pause[pause];
      IF oldKick # kick THEN
        BEGIN
	temp, missed: LONG CARDINAL;
	temp ← kick;
	missed ← temp - oldKick;
	oldKick ← temp;
	WriteMessage[missed];
	THROUGH [0..10) DO Process.Pause[pause]; ENDLOOP;  -- Don't clutter up screen
	END;
      ENDLOOP;
    END;

  WriteMessage: PROCEDURE [howMany: LONG CARDINAL] =
    BEGIN
    text: STRING = [200];
    Time.AppendCurrent[text];
    String.AppendString[text, "  Looks like we just came back from CoPilot"L];
    IF howMany > 1 THEN
      BEGIN
      String.AppendString[text, " ("L];
      String.AppendLongDecimal[text, howMany];
      String.AppendString[text, " times)"L];
      END;
    LogString[text];
    END;

  LogString: PROCEDURE [text: LONG STRING] =
    BEGIN
    String.AppendChar[text, '.];
    String.AppendChar[text, Ascii.CR];
    Put.Text[NIL, text];
    END;
    
  Init[];
  END.