/* Help engine:
 *
 * Copyright 1993 Brian A. Lantz, KO4KS
 */
#include <stdio.h>
#include "config.h"
#include "global.h"
#include "cmdparse.h"
#include "help.h"
#include "files.h"
#include "socket.h"

extern struct cmds DFAR Mbcmds[];
extern struct cmds DFAR Cmds[];

static int ours __ARGS((char *buf, char *search));


static int
ours (buf, search)
char *buf, *search;
{
char buf2[82], search2[82];

	if (strchr (buf, '*'))
		return ((search == NULLCHAR) ? 1 : 0);
	if (search == NULLCHAR)
		return 1;
	strcpy (buf2, buf);
	strcpy (&search2[1], search);
	search2[0] = ':';
	strlwr (buf2);
	strlwr (search2);
	return ((int)strstr (buf2, search2));
}


void
dohelper(title,cmdp,stopstr,filename,search)
char *title, *stopstr, *search, *filename;
register struct cmds *cmdp;
{
int i;
char buf[82];
struct cmds *saved;
int width = 0, count;
FILE *fp;

	saved = cmdp;
	for ( ; cmdp->name != NULL; cmdp++)
		width = (strlen(cmdp->name) > width) ? strlen(cmdp->name) : width;
	width += 1;
	count = (79 / width);
	cmdp = saved;
	if (filename == NULLCHAR || search == NULLCHAR)
		tputs(title);
	if (filename == NULLCHAR)	{	/* '?' commands	*/
		tputs (" ");
		memset(buf,' ',sizeof(buf));
		buf[77] = '\n';
		buf[78] = '\0';
		for(i=0;cmdp->name != NULL;cmdp++,i = ((i+1) % count)){
			if (stopstr && !stricmp (cmdp->name, stopstr))
				break;
			strncpy(&buf[i * width],cmdp->name,strlen(cmdp->name));
			if(i == (count - 1)){
				tprintf("%s ", buf);
				memset(buf,' ',77);
			}
		}
		if(i != 0)
			tprintf(buf);
		else
			tputc ('\b');
		return;
	}
	if ((fp = fopen (filename, READ_TEXT)) != NULLFILE)	{
		if (search != NULLCHAR)
			tputs ("Usage:\n");
		count = 0;
		do	{
			if (fgets (buf, 80, fp))	{
				if (*buf == '#')
					continue;	/* skip comments	*/
				if (*buf != ':')	{
					if (count)	{
						count--;
/*						if (search != NULLCHAR)
							tputs ("  ");
						tputs (buf);		*/
						tprintf ("  %s", buf);
					}
				} else	{	/* start of field or continuation */
					count = (ours (buf, search)) ? 32000 : 0;
					if (search == NULLCHAR && count)
						count = 1;
					if (buf[1] == ':' && count == 1)
						count--;
				}
			}
		} while (!feof (fp));
		fclose (fp);
	}
}

int
dohelp(argc, argv, p)
int argc;
char *argv[];
void *p;
{
	dohelper ("Main commands:\n", &Cmds[1], "a:", (argv[0][0] == '?' && argc == 1) ? NULLCHAR : CommandHelp, (argc == 2) ? argv[1] : NULLCHAR);
	return 0;
}


int
syntax(cmd)
char *cmd;
{
	dohelper (NULLCHAR, &Cmds[1], "a:", CommandHelp, cmd);
	return 0;
}


int
dombxhelp(argc, argv, p)
int argc;
char *argv[];
void *p;
{
char buf[255];

	sprintf (buf, "Mailbox Commands for %s at %s\n\n", Version, Hostname);
	dohelper (buf, &Mbcmds[1], "[", (argv[0][0] == '?' && argc == 1) ? NULLCHAR : MBOXHelp, (argc == 2) ? argv[1] : NULLCHAR);
	return 0;
}


int
mbxsyntax(cmd)
char *cmd;
{
	dohelper (NULLCHAR, &Mbcmds[1], "[", MBOXHelp, cmd);
	return 0;
}



