begin ; ! Enquire terminal type and install L:<V,W>TLIB
option  "-nocheck-nodiag"

include  "inc:util.imp"
include  "inc:dict.imp"
externalroutinespec  runprogram(string (255)program)

integer  terminal

constinteger  maxdelay=20000,esc=27,types=6,wy75=3
conststring (17)array  codes(1-3:3*types)=-
"",                 "PE550" {Bantam},              "l:btlib",  {0}
"/K",               "V200",                        "l:vtlib",  {1}
"/Z",               "VT52"  {or WY75-ATS},         "l:vtlib",  {2}
"[?1;0c",           "WY75",                        "l:wtlib",  {3}
"[?1;2c",           "VT100",                       "l:wtlib",  {4}
"[?62;1;2;6;7;8;9c","WY85",                        "l:wtlib",  {5}
"[?62;1;2;6;7;8c",  "VT220",                       "l:wtlib"   {6}

string (255)fn  filtered enq(string (255)s)
integer  k,n
  prompt("")
  set terminalmode(single!noecho)
  k = testsymbol until  k<0
  printsymbol(esc); printstring(s); s = ""
  cycle 
    n = maxdelay
    cycle 
      k = testsymbol&(¬128); exitif  k>=0
      n = n-1
    repeatuntil  n<=0
    exitif  k<0
    s = s.tostring(k) unless  k<' '
  repeat 
  set terminalmode(0)
  result  = s
end 

integerfn  terminal type
string (255)s
integer  i
  s = filtered enq("Z")
  for  i = 1,1,types cycle 
    result  = i if  s=codes(i*3-2)
  repeat 
  s = filtered enq("[c")
  for  i = 1,1,types cycle 
    result  = i if  s=codes(i*3-2)
  repeat 
  result  = 0
end 

routine  define symbol(string (255)symbol,value)
integer  stag,vtag
  stag = defname(symbol,comdict,8); returnif  stag=0
  vtag = defname(value,fildict,8); returnif  vtag=0
  integer(stag<<1>>1) = vtag<<1>>1
end 

routine  print escape string(string (255)s)
integer  i,k
  for  i = 1,1,length(s) cycle 
    k = charno(s,i)
    printsymbol(27) if  k='['
    printsymbol(k)
  repeat 
end 

  terminal = terminaltype
  if  terminal=0 start 
    printsymbol(':'); cycle ; repeatuntil  testsymbol>=0
    terminal = terminaltype
  finish 
  if  terminaltype=wy75 start 
! Clear top/bottom/shifted-bottom diag lines, revert to full-screen scrolling
    print escape string("[>+//[>,//[>-//[s[r[u")
  finish 
! %unless terminal=0 %start
    define symbol("TERMINAL",codes(terminal*3-1))
    cliparam = codes(terminal*3).".mob"
    runprogram("fmac:preload")
    cliparam = codes(terminal*3)
    runprogram("fmac:install")
! %finish
end