;;;
;;; Deal with a usage message which is compatible with the QNX use command.
;;;

;;;
;;; Define the program name.  Setting __PROGRAM will override this.  We
;;; need a program name to insert in the usage string with #%C
;;;

(defvar __PROGRAM
  (let (slash)
    (if (string_p (car argv))
	(progn
	  (if (and (not (undefined_p strrchr))
		   (function_p strrchr))
	      (setq slash (strrchr (car argv) "/"))
	    (setq slash -1))
	  (if (>= slash 0) (substr (car argv) (+ slash 1) -1) (car argv)))
      "unnamed")))

(defvar __USAGE "
#ifdef __USAGE
#%C	No usage available.
#endif
")

;;;
;;; Generate a usage message based on the variable __USAGE, which should
;;; have been defined in the mainline.  If not, then the default
;;; definition is used.
;;;

(defun Usage (&optional (usemsg nil) (program nil))
  (if (and (not usemsg) (not (undefined_p __USAGE))
	   (string_p __USAGE))
      (setq usemsg __USAGE))
  (if (not program)
      (if (and (not (undefined_p __PROGRAM)) (string_p __PROGRAM))
	  (setq program __PROGRAM)
	(setq program (car argv))))

  (let ((strs (string_split program "/" 0)))
    (setq program (car (reverse strs))))

  (let ((strs (string_split usemsg "\n" 0)))
    (for i in strs do
	 (cond
	  ((equal i "") nil)
	  ((equal (substr i 0 6) "#ifdef") nil)
	  ((equal (substr i 0 6) "#endif") nil)
	  ((equal (substr i 0 4) "#%C\t")
	   (princ program " " (substr i 4 -1) "\n"))
	  ((equal (substr i 0 1) "#")
	   (princ (substr i 1 -1) "\n"))
	  )
	 )
    )
  -1		; return -1, which is a valid argument to (exit_program)
  )
