/* Hist.rexx */

/*
     Format

       HIST [SAVE <name>] [LOAD <name>] [NOCLEAR]
	    [ORDER] [PERM [SEARCH <pattern>]

   Save and/or recall the history buffer. ORDER places the history
   buffer in alphabetical order and removes duplicates. PERM
   recalls the permanent history file. SEARCH searches the
   history buffer for a pattern.

*/

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

facility = 'Hist'
retcode = 0
histfile = 'dat:.History'
permfile = 'Perm'
cmd = ''

template = "SAVE/K,LOAD/K,SEARCH/K,NOCLEAR/S,ORDER/S,PERM/S"
dtemplate = "SAVE/K,LOAD/K,NOCLEAR/S,ORDER/S,PERM/S,SEARCH/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

swflags = ''
if args.NOCLEAR then swflags = 'NOCLEAR'
if (args.SAVE ~= '') & (args.LOAD ~= '') then do
  shistfile = fparse(pragma('D'),args.SAVE,histfile)
  lhistfile = fparse(pragma('D'),args.LOAD,histfile)
  if ~exists(lhistfile) then say lhistfile 'does not exist.'
  else do
    if exists(shistfile) then call Dump shistfile
    'SwapHistory SAVE' shistfile 'LOAD' lhistfile swflags
    end
  end
if args.SAVE ~= '' then do
  histfile = fparse(pragma('D'),args.SAVE,histfile)
  if exists(histfile) then call Dump histfile
  'History >'histfile
  end
if args.LOAD ~= '' then do
  histfile = fparse(pragma('D'),args.LOAD,histfile)
  if ~exists(histfile) then say histfile 'does not exist.'
  else 'SwapHistory LOAD' histfile swflags
  end
if args.ORDER then do
  histfile = fparse(pragma('D'),'Hist-Temp',histfile)
  if exists(histfile) then call Dump histfile
  'History | Sort | NoDuplicates >'histfile
  'SwapHistory LOAD' histfile swflags
  end
if args.PERM then do
  call Hist 'LOAD 'permfile swflags
  end
if args.SEARCH ~= '' then do
  'History | Search STDIN nonum quick' args.SEARCH
  end

GetOut:
exit retcode

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

