=head1 NAME

CFX5::Help - Help routines for CFX-5 scripts

=head1 SYNOPSIS

This package provides handling for help in the CFX-5 scripts. This is
done, as on UNIX, by including magic comments in the script itself;
here, they are read at compile-time into a variable which can then be
accessed at runtime.

=head1 FORMAT OF COMMENT LINES

All comment lines begin I<at the start of a line> with a two-character
flag, the first character of which is a '#'. These flags are:

=over

=item #H

Heading.

=item #S

Synopsis of the command.

=item #A

Argument name.

=item #U

"Undocumented", ie internal, features.  These lines will be shown iff
the directory CFX5SRCDIR exists.

=item ##

Other text

=back

These are used to enable different styles of output.

=cut

package CFX5::Help;

use strict;

use vars qw($CVSVersion);
$CVSVersion='$Id$ ';

use Exporter;
use vars qw(@ISA @EXPORT_OK %EXPORT_TAGS);
@ISA=qw(Exporter);
@EXPORT_OK=qw(read_help_text show_help show_synopsis);

use CFX5::CurrentConfig qw(query_conf getconf);
use CFX5::Output qw(:all);

=head1 FUNCTIONS

=head2 read_help_text

This function is called internally to read the help text from the .pl
file.

=cut

sub read_help_text {
  my @HelpText;

  my $script=$0;

  local *SCRFILE;
  unless (open SCRFILE, $0) {
    warn "Unable to open script, no help text will be available\n";
    return 0;
  }

  my $gotsome=0;
  while (<SCRFILE>) {
#    last if $gotsome && m/^\#[- ]/;
    next unless m/^\#[\#AHSU]/;
    $gotsome=1;
    s/\s*$//;
    s/^\#(.) ?//;
    push @HelpText, (defined $1 ? $1 : '?').$_;
  }

  close SCRFILE;

  unless (scalar(@HelpText) > 0) {
    warn "No help text was found in $0, no help will be available\n";
  }

  @HelpText;
}

#read_help_text();

=head2 show_help

  CFX5::Help::show_help();

Displays the help text for the current script on STDOUT.

=cut

sub show_help {
  my $dev=getconf('CFX5_DEVELOPER');

  my @HelpText=read_help_text();

  if (scalar(@HelpText) > 0) {
    for my $l (@HelpText) {
      if ($dev or substr($l,0,1) ne 'U') {
	_print substr($l,1), "\n";
      }
    }
  } else {
    _print "No help text is available for this command, sorry.\n";
    return 0;
  }
}

=head2 usage_msg

  _error("Bad argument -foobar", CFX5::Help::usage_msg());

This routine returns a single-line message which can be tacked onto
the end of error messages.  If there is help in the current script, it
will be set to

  Use "-help" for usage information.

with two leading CRs; otherwise, it will be an empty (but defined)
string.

=cut

sub usage_msg {
  my @HelpText=read_help_text();
  return (@HelpText
	  ? "\n\nUse \"-help\" for usage information."
	  : '');
}

=head2 usage_msg_once

The first time this is called, returns the same as C<usage_msg>.
Further calls will return the empty string.

=cut

  {
    my $called;
sub usage_msg_once {
  return '' if $called;
  $called++;
  return usage_msg(@_);
}
  }

1;
