;#########################################################################
;# ^FILE: parseargs.pl - parseargs for perl programs
;#
;# ^DESCRIPTION:
;#    This file defines a perl function named parseargs to parse
;#    command-line arguments for perl scripts.
;#
;# ^HISTORY:
;#    02/25/91	Brad Appleton	<brad@ssd.csd.harris.com>	Created
;##^^#####################################################################


;########
;# ^FUNCTION: parseargs - parse command-line argument vectors
;#
;# ^SYNOPSIS:
;#    rc = &parseargs( @argv, $argd )
;#
;# ^PARAMETERS:
;#    argv -- the vector of command-line arguments (usually ARGV).
;#    argd -- the argument-description string
;#
;# ^DESCRIPTION:
;#    Parseargs will invoke parseargs(1) to parse the command-line given
;#    in <argv> for the command defined by <argd>.  The resulting values
;#    will be assigned to the variables indicated by the argument-description
;#    string.
;#
;# ^REQUIREMENTS:
;#    Any desired initial values for variables from the argument-description
;#    string should be assigned BEFORE calling this function.
;#
;#    The following global variables from package "main" may be assigned
;#    before calling parseargs:
;#
;#       PARSEOPTS -- any extra options to pass to parseargs() (default="-u")
;#
;# ^SIDE-EFFECTS:
;#    The global variable PARSEARGS will contain the command-line used to
;#    invoke parseargs(1).
;#
;#    ARGV and (and any other variables named in <argd>) may be overwritten.
;#
;# ^RETURN-VALUE:
;#    The exit code returned by parseargs(1).
;#
;# ^ALGORITHM:
;#    - read $PARSECNTL environment variable and use corresponding syntax
;#      (long-options or short options) when invoking parseargs(1)
;#    - set defaults for PARSEOPTS
;#    - build the parseargs command (dont forget to quote arguments).
;#    - run parseargs(1) and evaluate the output unless $?
;##^^####

sub parseargs {
   local($argd, @argv) = ( pop(@_), $0, @_ );
   local($unset, $sh, $env, $end) = ( '-u', '-s', '-e', '--' );
   local($parse_output, $_);

   $_ = $main'ENV{'PARSECNTL'};
   if ( /[^!~\^]\s*[KkLl]/ ) {  ## KeyWords only!
      ($unset, $sh, $env, $end) = ( '+unset', '+shell', '+env', '++' );
   }

   if ( ! $main'PARSEOPTS )  { $main'PARSEOPTS = "$unset"; }

   grep( s/'/'\\''/g, @argv );  ## escape embedded quotes
   $PARSEARGS = "parseargs $main'PARSEOPTS $sh perl $env ARGD $end ";
   $PARSEARGS .= "'" . join( "' '", @argv ) . "'";

   $main'ENV{'ARGD'} = $argd;         ## put argd-array into environment
   $parse_output = `$PARSEARGS`;      ## invoke parseargs(1)
   eval $parse_output unless $?;      ## evaluate the output-script
   if ( $? ) {
      $! = 0;
      die "\n";
   }
   return $?;
}

1;
