/* DirIndex.rexx */

/*
      Format

	DIRINDEX [DIR] <directory> [[OUTPUT] <outfile>]

    Argument One: the directory to start at. Lists all
    sub-directories, sub-sub-directories,... Output is sent to
    STDOUT, unless a second argument is specified, then the
    output is sent to the specified output file.

    Note: the output is NOW sorted.

*/
signal on break_c; signal on break_d; signal on break_e; signal on break_f
call addlib 'rexxextra.library',-20,-30,0

facility = 'DirIndex'
retcode = 0
template = 'DIR/A,OUTPUT'
dtemplate = template
args. = ''

parse arg g_c
do while g_c='?'
  options prompt dtemplate': '  /* this template is      */
  parse pull g_c		/* displayed to the user */
  if g_c='?' then do
    g_s=sourceline(3)
    if pos('/*',g_s)=0 then break; if pos('*/',g_s)>0 then break
    say
    g_s=sourceline(4)
    do i=5 while pos('*/',g_s)=0; say g_s; g_s=sourceline(i); end
    say
    end
  end
interpret Cparse(g_c,template,'args')
if args.ERRCODE > 1 then do; say facility'-E-BADARGS,' args.ERRTEXT; exit 5; end

outfile = 'STDOUT'

if args.OUTPUT ~= '' then do
  if open('OUTFILE',args.OUTPUT,'w') then outfile = 'OUTFILE'
  else do
    say facility'-E-OPENIN, cannot open' args.OUTPUT
    exit 5
    end
  end

dev = args.DIR
if right(dev,1) = '/' then dev = left(dev,length(dev)-1)
call writeln outfile, dev
list = sortwords(showdir(dev,'D'))
if right(dev,1) ~= ':' & right(dev,1) ~= '/' then dev = dev'/'
do j = 1 to words(list)
  dire = dev||word(list,j)
  call writeln outfile, dire
  call ldir dire
  end

GetOut:
if outfile ~= 'STDOUT' then call close outfile
exit retcode

break_c:
break_d:
break_e:
break_f:
  say facility'-E-BREAK, Control-C interrupt'; retcode = 20; signal GetOut
failure:
  say facility'-E-FAIL, Line:' sigl', Error:' rc; retcode = rc; signal GetOut
syntax:
  say facility'-E-SYNTAX, Line:' sigl', Error:' rc; retcode = rc; signal GetOut
error:
  say facility'-E-ERROR, Line:' sigl', Error:' rc; retcode = rc; signal GetOut

ldir: procedure expose outfile
  parse arg dire
  if exists(dire) then do
    list = sortwords(showdir(dire,'D'))
    do j = 1 to words(list)
      nextdir = dire'/'word(list,j)
      call writeln outfile, nextdir
      call ldir nextdir
      end
    end
return 0

