-- Copyright (C) 1983  by Xerox Corporation. All rights reserved. 
-- TroubleTajo.mesa, HGM, 24-Sep-83 17:47:10

DIRECTORY
  Ascii USING [CR],
  FileSW USING [GetFile],
  MStream USING [GetLength, SetLogReadLength],
  Process USING [Detach, SetTimeout, SecondsToTicks],
  Put USING [Line],
  Runtime USING [CallDebugger],
  Stream USING [Handle, SendNow],
  String USING [AppendChar, AppendLongNumber, AppendString],
  TextSW USING [GetEOF, SetEOF],
  Time USING [AppendCurrent],
  Window USING [Handle],
  Stats USING [StatUpdate],
  Trouble USING [];

TroubleTajo: MONITOR
  IMPORTS
    FileSW, MStream, Process, Put, Runtime, Stream, String, TextSW, Time,
    Stats
  EXPORTS Trouble =
  BEGIN

  Bug: PUBLIC PROCEDURE [e: LONG STRING] =
    BEGIN
    text: STRING = [200];
    Stats.StatUpdate[];
    String.AppendChar[text, Ascii.CR];
    Time.AppendCurrent[text];
    String.AppendString[text, "  ******  "L];
    String.AppendString[text, e];
    String.AppendChar[text, Ascii.CR];
    DO Runtime.CallDebugger[text]; ENDLOOP;
    END;

  SetUncaughtSignalTrap: PUBLIC PROCEDURE = BEGIN END;

  PupGlitchTrap: PUBLIC PROCEDURE [why: ERROR] =
    BEGIN
    e: STRING = [100];
    String.AppendString[e, "PupPackage Troubles, arg="L];
    String.AppendLongNumber[e, LOOPHOLE[why], 8];
    Bug[e];
    END;

  window: Window.Handle ← NIL;
  stream: Stream.Handle ← NIL;

  WrapTypescriptFile: PUBLIC PROCEDURE [wh: Window.Handle, pages: CARDINAL] =
    BEGIN
    window ← wh;
    stream ← FileSW.GetFile[window].s;
    Process.Detach[FORK Watcher[LONG[pages]*512]];
    END;

  Watcher: ENTRY PROCEDURE [limit: LONG CARDINAL] =
    BEGIN
    pause: CONDITION;
    afterStartup, recent, now: LONG CARDINAL;
    Process.SetTimeout[@pause, Process.SecondsToTicks[15]];
    THROUGH [0..3*4) DO WAIT pause; ENDLOOP;
    afterStartup ← TextSW.GetEOF[window];
    DO  -- forever
      WAIT pause;
      now ← TextSW.GetEOF[window];
      IF recent = now THEN LOOP;
      ForceOutTypescriptFile[];
      recent ← now;
      IF now < limit THEN LOOP;
      ResetTypescriptFile[afterStartup];
      ENDLOOP;
    END;

  ForceOutTypescriptFile: PUBLIC PROCEDURE =
    BEGIN
    Stream.SendNow[stream];
    MStream.SetLogReadLength[stream, MStream.GetLength[stream]];
    END;

  ResetTypescriptFile: PROCEDURE [where: LONG CARDINAL] =
    BEGIN
    text: STRING = [100];
    TextSW.SetEOF[window, where];
    THROUGH [0..5) DO String.AppendChar[text, Ascii.CR]; ENDLOOP;
    Time.AppendCurrent[text];
    String.AppendString[text, "  Typescript file reset."L];
    Put.Line[window, text];
    END;

  END.