#include <stdio.h>
#include <string.h>
#include <descrip.h>
#ifdef __GNUC__
#define HLP$M_PROMPT 1
#else
#include <lbrdef.h>
#include <hlpdef.h>
#include <unixio.h>
#endif
#include "base_includes.h"
#include "set.h"
#include "inp.h"
#include "irchelp.h"

#ifndef R_OK
#define R_OK 4
extern int access();
#endif

extern int lbr$output_help(); /* not defined in header files */

static char help_file[MAXLEN];
static $DESCRIPTOR(help_file_d, help_file);

extern server_ptr gsrv;

static int help_output(out)
  struct dsc$descriptor *out;
{
  char buffer[100];
  if (!(int)out->dsc$w_length) return 1;
  (void)strncpy(buffer, out->dsc$a_pointer, out->dsc$w_length);
  buffer[(int)out->dsc$w_length] = 0;
  if (*buffer)
    say("%s", buffer);
  else
    say(" ");
  return 1;
}

static int help_input(str, prompt, len)
  struct dsc$descriptor *str, *prompt;
  unsigned long *len;
{
  char buffer[100], input[100];
  (void)strncpy(buffer, prompt->dsc$a_pointer, prompt->dsc$w_length);
  buffer[(int)prompt->dsc$w_length-1] = 32;
  buffer[(int)prompt->dsc$w_length] = 0;
  (void)read_input(input, 100, &buffer[2]);
  (void)strcpy(str->dsc$a_pointer, input);
  str->dsc$w_length = strlen(input);
  return 1;
}

int in_help = 0;

void help(char *str, int varpar, char *subparams)
{
  unsigned status;
  int loop, flags = HLP$M_PROMPT, context, width=77;
  struct dsc$descriptor keywords_d;
  keywords_d.dsc$a_pointer = (*str)?str:"help";

  keywords_d.dsc$b_dtype = DSC$K_DTYPE_T;
  keywords_d.dsc$b_class = DSC$K_CLASS_S;
  keywords_d.dsc$w_length = strlen(keywords_d.dsc$a_pointer);
  get_variable("HELP_PATH", NULL, help_file);
  strcat(help_file, "irchelp.hlb");
  help_file_d.dsc$w_length = strlen(help_file);
  if (strstr(help_file, ":") == NULL)
    say("*** The HELP_PATH must contain a full specification - include a device");
  else if (access(help_file, R_OK) == -1)
    say("*** Could not find the help file.");
  else
  {
    in_help = 1;
    status = lbr$output_help(help_output, &width, &keywords_d, &help_file_d,
                             &flags, help_input);
    in_help = 0;
  }
}
