/* file.c - view BBS files offline
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include "viewfile.h"
#include "terminal.h"


void sh_cont(int);			 /* SIGCONT handler */
void sh_alrm(int);			 /* SIGALRM handler */


typedef void (*sighandler_t) (int);


/* View "name" in the file viewer. The line to start at is given by "line";
 * if it is -1 the viewer will start at either the top or the place given in
 * the LDB. "flags" are the menu flags to use.
 *
 * If "ldbfile" is not null, it is used to store the last access details in
 * and will be created if it does not already exist.
 *
 * If "fakeas" is not null, the LDB entry for that filename is used instead
 * of the one for "name".
 */
int mview(char *name, char *ldbfile, long line, char *fakeas,
	  unsigned long flags)
{
	sighandler_t oh;
	sighandler_t oa;
	struct LDB d;
	int e;

	t_init(getenv("TERM"));
	t_echo_off();
	t_canon_off();

	oh = signal(SIGCONT, sh_cont);
	oa = signal(SIGALRM, sh_alrm);

	if (!fakeas)
		fakeas = name;		    /* if not faking, real = fake */

	ldb_read(ldbfile, fakeas, &d);	    /* read LDB entry for fake file */

	strcpy(d.realname, ldb_filename(name));	/* store real filename */

	if (line >= 0)
		d.current_line = line;

	e = do_read_file(&d, d.filename, flags, 0);	/* view the file */

	if (e != 2)
		ldb_write(ldbfile, &d);	    /* store LDB entry for fake file */

	t_echo_on();
	t_canon_on();

	signal(SIGALRM, oa);
	signal(SIGCONT, oh);

	return (e > 1);
}


/* Handle SIGCONT by reinitialising the terminal.
 */
void sh_cont(int s)
{
	t_init(getenv("TERM"));
	t_echo_off();
	t_canon_off();
	t_clearscreen = 1;
	signal(SIGCONT, sh_cont);
}


/* Handle SIGALRM by not doing anything.
 */
void sh_alrm(int s)
{
	signal(SIGALRM, sh_alrm);
}

/* EOF */
