/* help.c */

#include "copyright.h"

/* commands for giving help */

#include "config.h"
#include "db.h"
#include "interface.h"
#include "externs.h"
#include "help.h"

void spit_file(player, filename)
    dbref player;
    const char *filename;
{
  FILE *f;
  char *p;
  char tbuf1[BUFFER_LEN];

  if ((f = fopen(filename, "r")) == NULL) {
    notify(player,
	   tprintf("Sorry, %s is broken.  Management has been notified.",
		   filename));
    fputs("spit_file:", stderr);
    perror(filename);
  } else {
    while (fgets(tbuf1, sizeof tbuf1, f)) {
      for (p = tbuf1; *p; p++)
	if (*p == '\n') {
	  *p = '\0';
	  break;
	}
      notify(player, tbuf1);
    }
    fclose(f);
  }
}

void do_new_spitfile();

void do_news(player, arg1)
    dbref player;
    char *arg1;
{
  do_new_spitfile(player, arg1, NEWSINDX, NEWS_FILE);
}

void do_help(player,arg1)
    dbref player;
    char *arg1;
{
  do_new_spitfile(player,arg1, HELPINDX, HELPTEXT);
}

void do_new_spitfile(player, arg1, index_file, text_file)
    dbref player;
    char *arg1;
    char *index_file;
    char *text_file;
{
  int help_found;
  help_indx entry;
  FILE *fp;
  char *p, line[LINE_SIZE + 1];
  if (*arg1 == '\0')
    arg1 = (char *) "help";

  if ((fp = fopen(index_file, "r")) == NULL) {
    notify(player, "Sorry, that function is temporarily unavailable.");
    fprintf(stderr, "ERROR: can't open %s for reading\n", index_file);
    return;
  }
  while ((help_found = fread(&entry, sizeof(help_indx), 1, fp)) == 1)
    if (string_prefix(entry.topic, arg1))
      break;
  fclose(fp);
  if (!help_found) {
    notify(player, tprintf("No entry for '%s'.", arg1));
    return;
  }
  if ((fp = fopen(text_file, "r")) == NULL) {
    notify(player, "Sorry, that function is temporarily unavailable.");
    fprintf(stderr, "ERROR: can't open %s for reading\n", text_file);
    return;
  }
  if (fseek(fp, entry.pos, 0) < 0L) {
    notify(player, "Sorry, that function is temporarily unavailable.");
    fprintf(stderr, "ERROR: seek error in file %s\n", text_file);
    return;
  }
  for (;;) {
    if (fgets(line, LINE_SIZE, fp) == NULL)
      break;
    if (line[0] == '&')
      break;
    for (p = line; *p != '\0'; p++)
      if (*p == '\n')
	*p = '\0';
    notify(player, line);
  }
  fclose(fp);
}