#!/bin/tcsh -f

if ($#argv == 1) then
   if ("$1" == "-h" || "$1" == "-help") then
                  cat << EOF

A script to parse for global help options
The first parameter is the ALWAYS the program name whose help
output you seek. All other options follow.
It is meant to be called by other scripts.
It returns 0 when it has nothing to do.
           1 when it does something and wants calling
program to quit

To use this in any script follow these steps
1- Add this line before any parsing, right after the 1st line
      @global_parse \`basename \$0\` "\$*" ; if (\$status) exit 0
2- Add this line right where you fail to recognize an option
      apsearch -popt \`basename \$0\` -word \$argv[\$cnt]
3- Add this line somewhere in the help section
      @global_parse -gopts_help
4- Eliminate going to help immediately when too few options
   are set. One option, such as -all_opts is always good

EOF
      exit 0
   else if ("$1" == "-gopts_help" || "$1" == "-gopts_help_formats") then
                  cat << EOF
Global Help Options:
--------------------

   -h_web: Open webpage with help for this program
   -hweb: Same as -h_web
   -h_view: Open -help output in a GUI editor
   -hview: Same as -hview
   -all_opts: List all of the options for this script
   -h_find WORD: Search for lines containing WORD in -help
                 output. Seach is approximate.
EOF
      if ("$1" == "-gopts_help_formats") then
                  cat << EOF
   -h_raw: Raw help string
   -h_txt: Text formatted help string
   -h_spx: Sphinx formatted help string
   -h_aspx: Sphinx formatted help string with auto tagging of options    
EOF
      endif
      exit 0
   else if ("$1" == `basename $0`)then
      echo "What?"
      exit 1
   else
      #Nothing to do here
      exit 0
   endif
endif

   echo "$*" | \grep -w -E  '\-h_find|\-h_view|\-hview|\-all_opts|\-h_web|\-hweb' >& /dev/null
   if ($status) then
      #Nothing here, go back
      exit 0
   endif
   echo "$*" | \grep -w '\-h_view' >& /dev/null
   if ($status == 0) then
      apsearch -view_prog_help $1
      exit 1
   endif
   echo "$*" | \grep -w '\-hview' >& /dev/null
   if ($status == 0) then
      apsearch -view_prog_help $1
      exit 1
   endif
   echo "$*" | \grep -w '\-h_web' >& /dev/null
   if ($status == 0) then
      apsearch -web_prog_help $1
      exit 1
   endif
   echo "$*" | \grep -w '\-hweb' >& /dev/null
   if ($status == 0) then
      apsearch -web_prog_help $1
      exit 1
   endif
   echo "$*" | \grep -w '\-all_opts' >& /dev/null
   if ($status == 0) then
      apsearch -all_popts $1
      exit 1
   endif
   echo "$*" | \grep -w '\-h_find' >& /dev/null
   if ($status == 0) then
      set wrd = (`echo "$*" | sed 's/^.*-h_find *//' | cut -f 1 -d ' '`)
      if ($#wrd < 1) then
         echo "-h_find needs a WORD with it"
         exit 1
      endif
      set echo
      apsearch -phelp $1 -word "$wrd[1]"
      exit 1
   endif

exit 0
