#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 "global.h"
#include "constants.h"
#include "window.h"

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

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

extern server_ptr gsrv;
extern int lbr$output_help();

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;
}

int help_input(str, prompt, len)
  struct dsc$descriptor *str, *prompt;
  unsigned long *len;
{
  char buffer[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(buffer, 100, &buffer[2]);
  (void)strcpy(str->dsc$a_pointer, buffer);
  str->dsc$w_length = strlen(buffer);
  return 1;
}

int in_help = 0;

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

  keywords_d.dsc$b_dtype = DSC$K_DTYPE_T;
  keywords_d.dsc$b_class = DSC$K_CLASS_S;
  keywords_d.dsc$w_length = strlen(str);
  get_variable("HELP_PATH", NULL, help_file);
  strcat(help_file, "irchelp.hlb");
  help_file_d.dsc$w_length = strlen(help_file);
  if (access(help_file, R_OK) == -1)
    say("*** Could not find the help file.");
  else
  {
    old_in_help = in_help;
    in_help = 1;
    status = lbr$output_help(help_output, &width, &keywords_d, &help_file_d,
                             &flags, help_input);
    in_help = old_in_help;
  }
}
