#ifndef lint
static char *RCSid = "$Header: dispatch.c,v 1.10 90/03/19 10:51:31 mr-frog Exp $";
#endif

/*
 * dispatch.c
 *
 * actually execute the command given the comline
 *
 * from PSL Empire, 1985
 */

#include "misc.h"
#include "com.h"
#include "user.h"
#include "tm.h"
#include "match.h"
#include "nat.h"
#include "file.h"
#include "proto.h"
#include "io.h"

int	locks;

dispatch(buf, redir)
	char	*buf;
	char	*redir;
{
	extern	int nuke();
	extern	int laun();
	extern	char *argp[];
	extern	char combuf[];
	extern	int nstat;
	extern	int btused;
	struct	natstr *np;
	int	(*fn)();
	int	cmd;
	int	cost;
	int	lock;

	if ((cmd = comtch(argp[0])) < 0) {
		if (cmd == M_NOTUNIQUE)
			pr(fmt("\"%s\" is ambiguous -- ", buf));
		else {
			pr(fmt("\"%s\" is not a legal command ", buf));
			if (nstat != ncomstat)
				pr("now ");
			pr("\n");
		}
		return -1;
	}
	fn = coms[cmd].c_addr;
	cost = coms[cmd].c_cost;
	lock = coms[cmd].c_lock;
	np = getnatp(cnum);
	if (np->nat_btu < cost && cost > 0) {
		pr("You don't have the BTU's, bozo\n");
		return 0;
	}
	if (fn == 0) {
		pr("Command not implemented\n");
		return 0;
	}
	if (lock && tm_lock(lock) <= 0) {
		pr("Update in progress...command failed\n");
		return 0;
	}
	if (redir) {
		prredir(redir);
		pr(buf);
		pr("\n");
	}
	locks = lock;
	switch (fn()) {
	case RET_OK:
		btused += cost;
		break;
	case RET_FAIL:
		pr("command failed\n");
		btused += cost;
		break;
	case RET_SYN:
		pr(fmt("Usage: %s\n", coms[cmd].c_form));
		break;
	default:
		logerror("%s: returned bad value", coms[cmd].c_form);
		break;
	}
	return 0;
}
