/* count.rexx */

/*
     Format

       COUNT [[FILE] <file>] [W|WORDS] [L|LINES] [C|CHARS] [LO|LONGEST]

   Count the characters, words, lines and/or longest line in a file
   or STDIN, if no file supplied.

*/

signal on break_c
call addlib 'rexxextra.library',-20,-30,0

facility = 'Count'
retcode = 0
template = 'W=WORDS/S,L=LINES/S,C=CHARS/S,LO=LONGEST/S,P=PAGE/S,S=SIZE/K,FILE'
dtemplate = 'FILE,W=WORDS/S,L=LINES/S,C=CHARS/S,LO=LONGEST/S,P=PAGE,S=SIZE/K'
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

aa = 'C W L LO P'
parse value aa 'STDIN 66' with C W L LO P tfile pl . putecom
saycom = "say '"
cmd.	= ''
cmd.C	= 'chars=chars+LL;'
cmd.W	= 'wrds=wrds+words(rec);'
cmd.L	= 'lns=lns+1;'
cmd.LO	= 'if LL>longest then longest=LL;'
cmd.P	= 'ln=ln+1;if ln>pl then do;ln=0;pg=pg+1;end;'
asdf.	= ''
asdf.C	= "Chars:' chars', "
asdf.W	= "Words:' wrds', "
asdf.L	= "Lines:' lns', "
asdf.LO = "Longest:' longest', "
asdf.P	= "Pages:' pg', "

if args.W+args.L+args.C+args.LO+args.P = 0 then do
  args.W=1;args.L=1;args.C=1;args.LO=1;args.P=1
  end
if args.S ~= '' then do
  if ~datatype(args.S,'N') then call sayerror('SIZE value must be numeric')
  pl = args.S
  asdf.P = "Pages:' pg '('pl'/page)'"
  end
if args.FILE ~= '' then do
  if ~exists(args.FILE) then call sayerror('File' args.FILE 'not found')
  if ~open('COUNTHANDLE',args.FILE,'R') then
    call sayerror('Could not open' args.FILE 'for input')
  tfile = 'COUNTHANDLE'
  saycom = saycom"File:' args.FILE; say '"
  end
do jj = 1 to words(aa)
  kk = word(aa,jj)
  if args.kk then do
    putecom = putecom || cmd.kk
    saycom = saycom || asdf.kk
    end
  end
if right(saycom,2) = ', ' then
  saycom = left(saycom,length(saycom)-3)

chars = 0; lns = 0; wrds = 0; longest = 0; ln = 0; pg = 1
rec = readln(tfile)
do until eof(tfile)
  LL = length(rec)
  interpret putecom
  rec = readln(tfile)
end /* do */
interpret saycom

GetOut:
exit retcode

sayerror:
  parse arg x
  say x
  exit 10

break_c:
break_d:
break_e:
break_f:
  say facility'-E-BREAK, Control-C interrupt'
  exit 20
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

