! TAB
! Replaces tabs in the input file with the appropriate number of spaces,
! and/or introduces tabs into the output file to compress spaces.

! By default tabs are removed and replaced with spaces up to the next
! multiple of 8 columns.  Setting TABIN=0 leaves tabs alone.

! By default TABOUT=0, so the output will contain no tabs except those
! which might have been let in when TABIN=0.  Setting TABOUT to a nonzero
! value causes multiple spaces to be compressed by replacing them with tabs
! assuming that these would advance the "carriage" to the next multiple of
! TABOUT columns.

! RWT 07/12/90

begin 
option  "-nodiag-nocheck"
include  "inc:util.imp"
string (255)infile="",outfile=""
integer  intab=8,outtab=0
constinteger  tab=9,cr=13,strip=0,leave=1,add=2
byte  crs=strip
integer  spaces=0,inpos=0,outpos=0,k

routine  put(integer  k)
  if  k=' ' then  spaces = spaces+1 elsestart 
    if  outtab>1 and  spaces>1 start 
      while  spaces+outpos>=outtab cycle 
        printsymbol(tab); spaces = spaces-outtab+outpos; outpos = 0
      repeat 
    finish 
    while  spaces>0 cycle 
      spaces = spaces-1
      printsymbol(' '); outpos = outpos+1
      outpos = 0 if  outpos>=outtab
    repeat 
    printsymbol(k); outpos = outpos+1
    outpos = 0 if  outpos>=outtab or  k<32
  finish 
end 

  on  3,9 start 
    if  event_event=3 start 
      selectoutput(0)
      printstring("DETAB: "); printstring(event_message); newline
    finish 
    stop 
  finish 

  defineparam("infile",infile,pamnodefault)
  defineparam("outfile",outfile,pamnewgroup)
  defineintparam("intab",intab,0)
  defineintparam("outtab",outtab,0)
  defineenumparam("StripCR,LeaveCR,AddCR",crs,0)
  processparameters(cliparam)
  outfile = infile if  outfile=""

  openinput(1,infile); openoutput(1,outfile)
  selectinput(1); selectoutput(1)

  cycle 
    readsymbol(k)
    if  k<32 start 
      if  k=tab and  intab#0 start 
        put(' ') and  inpos = inpos+1 until  inpos>=intab
      elseif  k=cr
        put(cr) if  crs=leave
      elseif  k=nl
        put(cr) if  crs=add; put(nl)
      finishelse  put(k)
      inpos = 0
    else 
      put(k); inpos = inpos+1; inpos = 0 if  inpos>=intab
    finish 
  repeat 

end