! Utilities to manipulate command symbols and run programs.
! NB: Interface to dictionary procedures subject to change,
! so please %include this file in preference to incorporating a copy.

!You will need to include the following:
!%include "inc:util.imp"
!%include "inc:dict.imp"
!%externalroutinespec run program(%string(255)file)

routine  define command symbol(string (255)s,v)
! Define command S to have value V.
integer  ts,tv
  returnif  s="" or  v=""
  toupper(s) {but not v}
  ts = defname(s,comdict,8)<<1>>1; returnif  ts=0
  tv = defname(v,fildict,8)<<1>>1; returnif  tv=0
  integer(ts) = tv
end 

string (255)fn  translate command symbol(string (255)s)
! Acquire the value of symbol S.  If not defined, return itself.
integer  t
  result  = "" if  s=""
  toupper(s)
  t = refname(s,comdict); result  = s if  t=0
  t = integer(t); result  = s if  t=0
  transname(t,s)
  result  = s
end 

routine  translate command(string (255)name  s,rest)
!S contains a command (consisting of verb and parameters).
!Extract the verb and translate it.
!Return the translated verb in S, and the combined parameters in REST.
!Example: Given definitions v=fmac:e, and e=v-pre=mystyle.pre, then
!with S="v fred" we would get S="fmac:e" and REST="-pre=mystyle.pre fred".
string (255)t
integer  lives=9,pos,k
  cycle 
    pos = 1
    cycle 
      exitif  pos>length(s)
      k = charno(s,pos); exitif  k='-' or  k='/' or  k<=' '
      pos = pos+1
    repeat 
    rest = substring(s,pos,length(s))
    s = substring(s,1,pos-1)
    t = translate command symbol(s)
    returnif  s=t or  lives=0
    lives = lives-1
    s = t.rest
  repeat 
end 

routine  obey command(string (255)command,parameter)
! Achieve the effect of typing COMMAND PARAMETER to the CLI
! (but only those that would involve running a program, i.e.
! excluding commands that invoke a command file or define a symbol).
  returnif  command=""
  command = command." ".parameter unless  parameter=""
  translate command(command,parameter)
  cliparam = parameter
  run program(command)
end