/*
 * edit.c: This is really a mishmash of function and such that deal with IRCII
 * commands (both normal and keybinding commands) 
 *
 * Written By Michael Sandrof
 *
 * Copyright (c) 1990 Michael Sandrof.
 * Copyright (c) 1991, 1992 Troy Rollo.
 * Copyright (c) 1992-2006 Matthew R. Green.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include "irc.h"
IRCII_RCSID("@(#)$eterna: edit.c,v 1.194 2006/07/22 03:50:10 mrg Exp $");

#include <sys/stat.h>

#include "parse.h"
#include "ircterm.h"
#include "server.h"
#include "edit.h"
#include "crypt.h"
#include "vars.h"
#include "ircaux.h"
#include "lastlog.h"
#include "window.h"
#include "screen.h"
#include "whois.h"
#include "hook.h"
#include "input.h"
#include "ignore.h"
#include "keys.h"
#include "names.h"
#include "alias.h"
#include "history.h"
#include "funny.h"
#include "ctcp.h"
#include "dcc.h"
#include "translat.h"
#include "output.h"
#include "exec.h"
#include "notify.h"
#include "numbers.h"
#include "status.h"
#include "if.h"
#include "help.h"
#include "stack.h"
#include "queue.h"
#include "icb.h"
#include "strsep.h"

/*
 * current_exec_timer - used to make sure we don't remove a timer
 * from within itself.
 */
static	int	current_exec_timer = -1;

static	int	save_which;
static	int	save_do_all;

static	void	show_timer(u_char *);
static	int	create_timer_ref(int);
static	void	get_history(int);
static	void	oper_password_received(u_char *, u_char *);
static	void	send_action(u_char *, u_char *);

TimerList *PendingTimers = (TimerList *) 0;

/* used with input_move_cursor */
#define RIGHT 1
#define LEFT 0

/* used with /save */
#define	SFLAG_ALIAS	0x0001
#define	SFLAG_BIND	0x0002
#define	SFLAG_ON	0x0004
#define	SFLAG_SET	0x0008
#define	SFLAG_NOTIFY	0x0010
#define	SFLAG_DIGRAPH	0x0020

/* The maximum number of recursive LOAD levels allowed */
#define MAX_LOAD_DEPTH 10

/* recv_nick: the nickname of the last person to send you a privmsg */
	u_char	*recv_nick = NULL;

/* sent_nick: the nickname of the last person to whom you sent a privmsg */
	u_char	*sent_nick = NULL;
	u_char	*sent_body = NULL;

/* Used to keep down the nesting of /LOADs and to determine if we
 * should activate the warning for /ONs if the NOVICE variable is set.
 */
	int	load_depth = 0;

/* Used to prevent global messaging */
extern	int	in_on_who;

typedef	struct	WaitCmdstru
{
	u_char	*stuff;
	struct	WaitCmdstru	*next;
}	WaitCmd;

static	WaitCmd	*start_wait_list = NULL,
		*end_wait_list = NULL;

	u_char	lame_wait_nick[] = "1#LAME";

	int	my_echo_set_message_from;	/* XXX */

/* a few advance declarations */
static	void	sendlinecmd(u_char *, u_char *, u_char *);
static	void	do_send_text(u_char *, u_char *, u_char *);
static	void	funny_stuff(u_char *, u_char *, u_char *);
static	void	catter(u_char *, u_char *, u_char *);
static	void	cd(u_char *, u_char *, u_char *);
static	void	e_wall(u_char *, u_char *, u_char *);
static	void	send_squery(u_char *, u_char *, u_char *);
static	void	send_brick(u_char *, u_char *, u_char *);
static	void	send_2comm(u_char *, u_char *, u_char *);
static	void	send_comm(u_char *, u_char *, u_char *);
static	void	send_invite(u_char *, u_char *, u_char *);
static	void	send_motd(u_char *, u_char *, u_char *);
static	void	send_topic(u_char *, u_char *, u_char *);
static	void	send_channel_nargs(u_char *, u_char *, u_char *);
static	void	send_channel_2args(u_char *, u_char *, u_char *);
static	void	send_channel_1arg(u_char *, u_char *, u_char *);
static	void	my_clear(u_char *, u_char *, u_char *);
static	void	quote(u_char *, u_char *, u_char *);
static	void	e_privmsg(u_char *, u_char *, u_char *);
static	void	flush(u_char *, u_char *, u_char *);
static	void	away(u_char *, u_char *, u_char *);
static	void	oper(u_char *, u_char *, u_char *);
static	void	e_channel(u_char *, u_char *, u_char *);
static	void	who(u_char *, u_char *, u_char *);
static	void	whois(u_char *, u_char *, u_char *);
static	void	ison(u_char *, u_char *, u_char *);
static	void	userhost(u_char *, u_char *, u_char *);
static	void	info(u_char *, u_char *, u_char *);
static	void	e_nick(u_char *, u_char *, u_char *);
static	void	commentcmd(u_char *, u_char *, u_char *);
static	void	sleepcmd(u_char *, u_char *, u_char *);
static	void	version(u_char *, u_char *, u_char *);
static	void	ctcp(u_char *, u_char *, u_char *);
static	void	dcc(u_char *, u_char *, u_char *);
static	void	deop(u_char *, u_char *, u_char *);
static	void	my_echo(u_char *, u_char *, u_char *);
static	void	save_settings(u_char *, u_char *, u_char *);
static	void	redirect(u_char *, u_char *, u_char *);
static	void	waitcmd(u_char *, u_char *, u_char *);
static	void	describe(u_char *, u_char *, u_char *);
static	void	me(u_char *, u_char *, u_char *);
static	void	mload(u_char *, u_char *, u_char *);
static	void	mlist(u_char *, u_char *, u_char *);
static	void	evalcmd(u_char *, u_char *, u_char *);
static	void	hook(u_char *, u_char *, u_char *);
static	void	timercmd(u_char *, u_char *, u_char *);
static	void	inputcmd(u_char *, u_char *, u_char *);
static	void	pingcmd(u_char *, u_char *, u_char *);
static	void	xtypecmd(u_char *, u_char *, u_char *);
static	void	beepcmd(u_char *, u_char *, u_char *);
static	void	abortcmd(u_char *, u_char *, u_char *);
static	void	really_save(u_char *, u_char *);

#ifdef HAVE_SETENV
static	void	irc_setenv(u_char *, u_char *, u_char *);
#endif
#ifdef HAVE_UNSETENV
static	void	irc_unsetenv(u_char *, u_char *, u_char *);
#endif

/* IrcCommand: structure for each command in the command table */
typedef	struct
{
	char	FAR *name;				/* what the user types */
	char	*server_func;				/* what gets sent to the server
							 * (if anything) */
	void	(*func)(u_char *, u_char *, u_char *); /* function that is the command */
	unsigned	flags;
}	IrcCommand;

static	IrcCommand *find_command(u_char *, int *);

#define NONOVICEABBREV	0x0001
#define NOINTERACTIVE	0x0002
#define NOSIMPLESCRIPT	0x0004
#define NOCOMPLEXSCRIPT	0x0008
#define SERVERREQ	0x0010
#define NOICB		0x0020

/*
 * irc_command: all the available irc commands:  Note that the first entry has
 * a zero length string name and a null server command... this little trick
 * makes "/ blah blah blah" to always be sent to a channel, bypassing queries,
 * etc.  Neato.  This list MUST be sorted.
 */
static	IrcCommand FAR irc_command[] =
{
	{ "",		CP(empty_string), do_send_text,		NOSIMPLESCRIPT| NOCOMPLEXSCRIPT },
	/*
	 * I really want to remove #, but it will break a lot of scripts.  - mycroft
	 *
	 * I agree - it should be converted to a special character in parse_line.
	 *                                                            - Troy
	 */
	{ "#",		NULL,		commentcmd, 		0 },
	{ ":",		NULL,		commentcmd, 		0 },
	{ "ABORT",      NULL,           abortcmd,               0 },
	{ "ADMIN",	"ADMIN",	send_comm, 		SERVERREQ },
	{ "ALIAS",	"0",		alias,			0 },
#ifdef ALLOC_DEBUG
	{ "ALLOC",	NULL,		alloc_cmd,		0 },
#endif /* ALLOC_DEBUG */
	{ "ASSIGN",	"1",		alias,			0 },
	{ "AWAY",	"AWAY",		away,			SERVERREQ },
	{ "BEEP",	0,		beepcmd,		0 },
	{ "BIND",	NULL,		bindcmd,		0 },
	{ "BRICK",	"BRICK",	send_brick,		SERVERREQ },
	{ "BYE",	"QUIT",		e_quit,			NONOVICEABBREV },
	{ "CAT",	NULL,		catter,			0 },
	{ "CD",		NULL,		cd,			0 },
	{ "CHANNEL",	"JOIN",		e_channel,		SERVERREQ },
	{ "CLEAR",	NULL,		my_clear,		0 },
	{ "COMMENT",	NULL,		commentcmd,		0 },
	{ "CONNECT",	"CONNECT",	send_comm,		SERVERREQ },
	{ "CTCC",	NULL,		dcc,			SERVERREQ },
	{ "CTCP",	NULL,		ctcp,			SERVERREQ },
	{ "DATE",	"TIME",		send_comm,		SERVERREQ },
	{ "DCC",	NULL,		dcc,			0 },
	{ "DEOP",	NULL,		deop,			SERVERREQ },
	{ "DESCRIBE",	NULL,		describe,		SERVERREQ },
	{ "DIE",	"DIE",		send_comm,		SERVERREQ },
	{ "DIGRAPH",	NULL,		digraph,		0 },
	{ "DISCONNECT",	NULL,		disconnectcmd,		SERVERREQ },
	{ "ECHO",	NULL,		my_echo,		0 },
	{ "ENCRYPT",	NULL,		encrypt_cmd,		0 },
	{ "EVAL",	NULL,		evalcmd,		0 },
	{ "EXEC",	NULL,		execcmd,		0 },
	{ "EXIT",	"QUIT",		e_quit,			NONOVICEABBREV },
	{ "FE",		NULL,		foreach_handler,	0 },
	{ "FEC",	NULL,		fec,			0 },
	{ "FLUSH",	NULL,		flush,			SERVERREQ },
	{ "FOR",	NULL,		foreach_handler,	0 },
	{ "FOREACH",	NULL,		foreach_handler,	0 },
	{ "HASH",	"HASH",		send_comm,		SERVERREQ },
	{ "HELP",	NULL,		help,			0 },
	{ "HISTORY",	NULL,		history,		0 },
	{ "HOOK",	NULL,		hook,			0 },
	{ "HOST",	"USERHOST",	userhost,		SERVERREQ },
	{ "ICB",	NULL,		icbcmd,			0 },
	{ "IF",		NULL,		ifcmd,			0 },
	{ "IGNORE",	NULL,		ignore,			0 },
	{ "INFO",	"INFO",		info,			SERVERREQ },
	{ "INPUT",	NULL,		inputcmd,		0 },
	{ "INVITE",	"INVITE",	send_invite,		SERVERREQ },
	{ "ISON",	"ISON",		ison,			SERVERREQ },
	{ "JOIN",	"JOIN",		e_channel,		SERVERREQ },
	{ "KICK",	"KICK",		send_channel_2args,	SERVERREQ|NOICB },
	{ "KILL",	"KILL",		send_2comm,		SERVERREQ|NOICB },
	{ "LASTLOG",	NULL,		lastlog,		0 },
	{ "LEAVE",	"PART",		send_channel_1arg,	SERVERREQ|NOICB },
	{ "LINKS",	"LINKS",	send_comm,		NONOVICEABBREV|SERVERREQ|NOICB },
	{ "LIST",	"LIST",		funny_stuff,		SERVERREQ },
	{ "LOAD",	"LOAD",		load,			0 },
	{ "LUSERS",	"LUSERS",	send_comm,		SERVERREQ },
	{ "ME",		NULL,		me,			SERVERREQ },
	{ "MLIST",	NULL,		mlist,			0 },
	{ "MLOAD",	NULL,		mload,			0 },
	{ "MODE",	"MODE",		send_channel_nargs,	SERVERREQ|NOICB },
	{ "MOTD",	"MOTD",		send_motd,		SERVERREQ },
	{ "MSG",	"PRIVMSG",	e_privmsg,		0 },
	{ "NAMES",	"NAMES",	funny_stuff,		SERVERREQ },
	{ "NICK",	"NICK",		e_nick,			SERVERREQ },
	{ "NOTE",	"NOTE",		send_comm,		SERVERREQ },
	{ "NOTICE",	"NOTICE",	e_privmsg,		SERVERREQ },
	{ "NOTIFY",	NULL,		notify,			SERVERREQ },
	{ "ON",		NULL,		on,			0 },
	{ "OPER",	"OPER",		oper,			SERVERREQ },
	{ "PARSEKEY",	NULL,		parsekeycmd,		0 },
	{ "PART",	"PART",		send_channel_1arg,	SERVERREQ|NOICB },
	{ "PING",	NULL, 		pingcmd,		SERVERREQ },
	{ "QUERY",	NULL,		query,			0 },
	{ "QUEUE",      NULL,           queuecmd,               0 },
	{ "QUIT",	"QUIT",		e_quit,			NONOVICEABBREV },
	{ "QUOTE",	NULL,		quote,			SERVERREQ },
	{ "RBIND",	0,		rbindcmd,		0 },
	{ "REDIRECT",	NULL,		redirect,		0 },
	{ "REHASH",	"REHASH",	send_comm,		SERVERREQ },
	{ "REQUEST",	NULL,		ctcp,			SERVERREQ },
	{ "RESTART",	"RESTART",	send_comm,		SERVERREQ },
	{ "SAVE",	NULL,		save_settings,		0 },
	{ "SAY",	CP(empty_string), do_send_text,		SERVERREQ },
	{ "SEND",	NULL,		do_send_text,		SERVERREQ },
	{ "SENDLINE",	CP(empty_string), sendlinecmd,		0 },
	{ "SERVER",	NULL,		servercmd,		0 },
	{ "SERVLIST",	"SERVLIST",	send_comm,		SERVERREQ|NOICB },
	{ "SET",	NULL,		set_variable,		0 },
#ifdef HAVE_SETENV
	{ "SETENV",	NULL,		irc_setenv,		0 },
#endif
	{ "SIGNOFF",	"QUIT",		e_quit,			NONOVICEABBREV },
	{ "SLEEP",	NULL,		sleepcmd,		0 },
	{ "SQUERY",	"SQUERY",	send_squery,		SERVERREQ|NOICB },
	{ "SQUIT",	"SQUIT",	send_2comm,		SERVERREQ|NOICB },
	{ "STACK",	NULL,		stackcmd,		0 },
	{ "STATS",	"STATS",	send_comm,		SERVERREQ|NOICB },
	{ "SUMMON",	"SUMMON",	send_comm,		SERVERREQ|NOICB },
	{ "TIME",	"TIME",		send_comm,		SERVERREQ|NOICB },
	{ "TIMER",	"TIMER",	timercmd,		0 },
	{ "TOPIC",	"TOPIC",	send_topic,		SERVERREQ },
	{ "TRACE",	"TRACE",	send_comm,		SERVERREQ|NOICB },
	{ "TYPE",	NULL,		typecmd,		0 },
#ifdef HAVE_UNSETENV
	{ "UNSETENV",	NULL,		irc_unsetenv,		0 },
#endif
	{ "USERHOST",	NULL,		userhost,		SERVERREQ },
	{ "USERS",	"USERS",	send_comm,		SERVERREQ|NOICB },
	{ "VERSION",	"VERSION",	version,		0 },
	{ "VOICE",	"VOICE",	e_privmsg,		SERVERREQ },
	{ "WAIT",	NULL,		waitcmd,		SERVERREQ },
	{ "WALL",	"WALL",		e_wall,			SERVERREQ },
	{ "WALLOPS",	"WALLOPS",	e_wall,			SERVERREQ },
	{ "WHICH",	"WHICH",	load,			0 },
	{ "WHILE",	NULL,		whilecmd,		0 },
	{ "WHO",	"WHO",		who,			SERVERREQ },
	{ "WHOIS",	"WHOIS",	whois,			SERVERREQ },
	{ "WHOWAS",	"WHOWAS",	whois,			SERVERREQ },
	{ "WINDOW",	NULL,		windowcmd,		0 },
	{ "XECHO",	"XECHO",	my_echo,		0 },
	{ "XTRA",	"XTRA",		e_privmsg,		SERVERREQ },
	{ "XTYPE",	NULL,		xtypecmd,		0 },
	{ NULL,		NULL,		commentcmd,		0 }
};

/* number of entries in irc_command array */
# define	NUMBER_OF_COMMANDS (sizeof(irc_command) / sizeof(IrcCommand)) - 2

/*
 * find_command: looks for the given name in the command list, returning a
 * pointer to the first match and the number of matches in cnt.  If no
 * matches are found, null is returned (as well as cnt being 0). The command
 * list is sorted, so we do a binary search.  The returned commands always
 * points to the first match in the list.  If the match is exact, it is
 * returned and cnt is set to the number of matches * -1.  Thus is 4 commands
 * matched, but the first was as exact match, cnt is -4.
 */
static	IrcCommand *
find_command(com, cnt)
	u_char	*com;
	int	*cnt;
{
	size_t	len;

	if (com && (len = my_strlen(com)))
	{
		int	min,
			max,
			pos,
			old_pos = -1,
			c;

		min = 1;
		max = NUMBER_OF_COMMANDS + 1;
		while (1)
		{
			pos = (max + min) / 2;
			if (pos == old_pos)
			{
				*cnt = 0;
				return ((IrcCommand *) 0);
			}
			old_pos = pos;
			c = my_strncmp(com, irc_command[pos].name, len);
			if (c == 0)
				break;
			else if (c > 0)
				min = pos;
			else
				max = pos;
		}
		*cnt = 0;
		(*cnt)++;
		min = pos - 1;
		while ((min > 0) && (my_strncmp(com, irc_command[min].name,
				len) == 0))
		{
			(*cnt)++;
			min--;
		}
		min++;
		max = pos + 1;
		while ((max < NUMBER_OF_COMMANDS + 1) && (my_strncmp(com,
				irc_command[max].name, len) == 0))
		{
			(*cnt)++;
			max++;
		}
		if (*cnt)
		{
			if (my_strlen(irc_command[min].name) == len)
				*cnt *= -1;
			else if (*cnt == 1 && 
					irc_command[min].flags&NONOVICEABBREV &&
					get_int_var(NOVICE_VAR))
			{
				say("As a novice you may not abbreviate the %s command", irc_command[min].name);
				*cnt=0;
				return ((IrcCommand *) 0);
			}
			return (&(irc_command[min]));
		}
		else
			return ((IrcCommand *) 0);
	}
	else
	{
		*cnt = -1;
		return (irc_command);
	}
}

/*ARGSUSED*/
static	void
ctcp(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*to,
		*tag;
	int	ctcptype;

	if ((to = next_arg(args, &args)) != NULL)
	{
		if (!my_strcmp(to, "*"))
			if ((to = get_channel_by_refnum(0)) == NULL)
				to = zero;
		if ((tag = next_arg(args, &args)) != NULL)
			upper(tag);
		else
			tag = UP("VERSION");
		if ((ctcptype = in_ctcp()) == -1)
			my_echo(NULL, UP("*** You may not use the CTCP command in an ON CTCP_REPLY!"), empty_string);
		else
		{
			if (args && *args)
				send_ctcp(ctcp_type[ctcptype], to, tag, "%s", args);
			else
				send_ctcp(ctcp_type[ctcptype], to, tag, NULL);
		}
	}
	else
		say("Request from whom?");
}

/*ARGSUSED*/
static	void
hook(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	if (*args)
		do_hook(HOOK_LIST, "%s", args);
	else
		say("Must supply an argument to HOOK");
}

/*ARGSUSED*/
static	void
dcc(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	if (*args)
		process_dcc(args);
	else
		dcc_list((u_char *) 0);
}

/*ARGSUSED*/
static	void
deop(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	send_to_server("MODE %s -o", get_server_nickname(from_server));
}

static	void
funny_stuff(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*arg,
		*cmd = (u_char *) 0,
		*stuff,
		*s;
	int	min = 0,
		max = 0,
		flags = 0;
	size_t	len;

	if (get_server_version(from_server) == ServerICB)
	{
		icb_put_funny_stuff(command, args, subargs);
		return;
	}
	stuff = empty_string;
	while ((arg = next_arg(args, &args)) != NULL)
	{
		len = my_strlen(arg);
		malloc_strcpy(&cmd, arg);
		upper(cmd);
		if (my_strncmp(cmd, "-MAX", len) == 0)
		{
			if ((arg = next_arg(args, &args)) != NULL)
				max = my_atoi(arg);
		}
		else if (my_strncmp(cmd, "-MIN", len) == 0)
		{
			if ((arg = next_arg(args, &args)) != NULL)
				min = my_atoi(arg);
		}
		else if (my_strncmp(cmd, "-ALL", len) == 0)
		{
			flags &= ~(FUNNY_PUBLIC | FUNNY_PRIVATE);
		}
		else if (my_strncmp(cmd, "-PUBLIC", len) == 0)
		{
			flags |= FUNNY_PUBLIC;
			flags &= ~FUNNY_PRIVATE;
		}
		else if (my_strncmp(cmd, "-PRIVATE", len) == 0)
		{
			flags |= FUNNY_PRIVATE;
			flags &= ~FUNNY_PUBLIC;
		}
		else if (my_strncmp(cmd, "-TOPIC", len) == 0)
			flags |= FUNNY_TOPIC;
		else if (my_strncmp(cmd, "-WIDE", len) == 0)
			flags |= FUNNY_WIDE;
		else if (my_strncmp(cmd, "-USERS", len) == 0)
			flags |= FUNNY_USERS;
		else if (my_strncmp(cmd, "-NAME", len) == 0)
			flags |= FUNNY_NAME;
		else
			stuff = arg;
		new_free(&cmd);
	}
	set_funny_flags(min, max, flags);
	if (my_strcmp(stuff, "*") == 0)
		if (!(stuff = get_channel_by_refnum(0)))
			stuff = empty_string;
	if ((s = my_index(stuff, '*')) &&
	    !is_on_channel(stuff, from_server, get_server_nickname(from_server)) &&
	    !(s > stuff && s[-1] == ':'))
	{
		funny_match(stuff);
		send_to_server("%s %s", command, empty_string);
	}
	else
	{
		funny_match(NULL);
		send_to_server("%s %s", command, stuff);
	}
}

/*ARGSUSED*/
static void
waitcmd(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
#ifdef _Windows
	yell("WAIT is not available under Windows");
#else /* Windows */
	int	wait_index;
	u_char	*flag;
	u_char	*procindex;
	int	cmd = 0;
	size_t	len;
	u_char	buffer[BIG_BUFFER_SIZE];

	while (args && *args == '-')
	{
		flag = next_arg(args, &args);
		len = my_strlen(++flag);
		if (!my_strnicmp(UP("CMD"), flag, len))
		{
			cmd = 1;
			break;
		}
		else
			yell("Unknown argument to WAIT: %s", flag);
	}
	if ((procindex = next_arg(args, &args)) && *procindex == '%' &&
			(wait_index = get_process_index(&procindex)) != -1)
	{
		if (is_process_running(wait_index))
		{
			if (cmd)
			{
				add_process_wait(wait_index, args?args:empty_string);
				return;
			}
			else
				set_wait_process(wait_index);
		}
		else
		{
			say("Not a valid process!");
			return;
		}
	}
	else if (cmd)
	{
		WaitCmd	*new;

		snprintf(CP(buffer), sizeof buffer, "%s %s", procindex, args);
		new = (WaitCmd *) new_malloc(sizeof(WaitCmd));
		new->stuff = NULL;
		malloc_strcpy(&new->stuff, buffer);
		new->next = NULL;
		if (end_wait_list)
			end_wait_list->next = new;
		end_wait_list = new;
		if (!start_wait_list)
			start_wait_list = new;
		send_to_server("%s", wait_nick);
		return;
	}
	else
		send_to_server("%s", lame_wait_nick);
	if (waiting)
		yell("WAIT has been called recursively.");

	waiting++;
	irc_io(NULL, NULL, 0, 1);
	waiting--;
#endif /* _Windows */
}

int
check_wait_command(nick)
	u_char 	*nick;
{
	if (waiting && !my_strcmp(nick, lame_wait_nick))
	{
		irc_io_loop = 0;
		return 1;
	}
	if (start_wait_list && !my_strcmp(nick, wait_nick))
	{
		if (start_wait_list->stuff)
		{
			parse_command(start_wait_list->stuff, 0, empty_string);
			new_free(&start_wait_list->stuff);
		}
		start_wait_list = start_wait_list->next;
		return 1;
	}
	return 0;
}

/*ARGSUSED*/
static	void
redirect(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*to;

	if ((to = next_arg(args, &args)) != NULL)
	{
		if (!my_strcmp(to, "*"))
			if (!(to = get_channel_by_refnum(0)))
			{
				say("Must be on a channel to redirect to '*'");
				return;
			}
		if (!my_stricmp(to, get_server_nickname(from_server)))
		{
			say("You may not redirect output to yourself");
			return;
		}
		window_redirect(to, from_server);
		server_list[from_server].sent = 0;
		parse_line((u_char *) 0, args, (u_char *) 0, 0, 0, 0);
		if (server_list[from_server].sent)
			send_to_server("%s", current_screen->redirect_token,
				current_screen->screennum);
		else
			window_redirect(NULL, from_server);
	}
	else
		say("Usage: REDIRECT <nick|channel|%process> <cmd>");
}

/*ARGSUSED*/
static	void
sleepcmd(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
#ifndef _Windows
	u_char	*arg;

	if ((arg = next_arg(args, &args)) != NULL)
		sleep((unsigned)my_atoi(arg));
	else
		say("SLEEP: you must specify the amount of time to sleep (in seconds)");
#else
	say("SLEEP: Not available under Windows");
#endif /* _Windows */
}

/*
 * my_echo: simply displays the args to the screen, or, if it's XECHO,
 * processes the flags first, then displays the text on
 * the screen
 */
static void
my_echo(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	unsigned int	display;
	int	lastlog_level = 0;
	int	from_level = 0;
	u_char	*flag_arg;
	int	temp;
	Window *old_to_window;

	save_message_from();
	old_to_window = to_window;
	if (command && *command == 'X')
	{
		while (args && *args == '-')
		{
			flag_arg = next_arg(args, &args);
			switch(flag_arg[1])
			{
			case 'L':
			case 'l':
				if (!(flag_arg = next_arg(args, &args)))
					break;
				if ((temp = parse_lastlog_level(flag_arg)) != 0)
				{
					lastlog_level = set_lastlog_msg_level(temp);
					from_level = message_from_level(temp);
					my_echo_set_message_from = 1;
				}
				break;
			case 'W':
			case 'w':
				if (!(flag_arg = next_arg(args, &args)))
					break;
				if (isdigit(*flag_arg))
					to_window = get_window_by_refnum((unsigned)my_atoi(flag_arg));
				else
					to_window = get_window_by_name(flag_arg);
				lastlog_level = set_lastlog_msg_level(LOG_CRAP);
				from_level = message_from_level(LOG_CRAP);
				break;
			}
			if (!args)
				args = empty_string;
		}
	}
	display = window_display;
	window_display = 1;
	put_it("%s", args);
	window_display = display;
	if (lastlog_level)
		set_lastlog_msg_level(lastlog_level);
	if (from_level)
		message_from_level(from_level);
	restore_message_from();
	to_window = old_to_window;
	my_echo_set_message_from = 0;
}

/*
 */
static	void
oper_password_received(data, line)
	u_char	*data;
	u_char	*line;
{
	send_to_server("OPER %s %s", data, line);
}

/* oper: the OPER command.  */
/*ARGSUSED*/
static	void
oper(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*password;
	u_char	*nick;

	oper_command = 1;
	if (!(nick =  next_arg(args, &args)))
		nick =  nickname;
	if (!(password = next_arg(args, &args)))
	{
		add_wait_prompt(UP("Operator Password:"),
			oper_password_received, nick, WAIT_PROMPT_LINE);
		return;
	}
	send_to_server("OPER %s %s", nick, password);
}

/* Full scale abort.  Does a "save" into the filename in line, and
        then does a coredump */
static  void   
abortcmd(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
        u_char    *filename = (u_char *) next_arg(args, &args);

	if (!filename)
		filename = UP("irc.aborted");
	save_which = SFLAG_ALIAS | SFLAG_BIND | SFLAG_ON | SFLAG_SET |
			     SFLAG_NOTIFY | SFLAG_DIGRAPH;
        really_save(filename, UP("y"));
#ifdef ALLOC_DEBUG
        alloc_cmd("ALLOC", "d", (u_char *) 0);
#endif /* ALLOC_DEBUG */
        abort();
}
        
/* This generates a file of your ircII setup */
static	void
really_save(file, line)
	u_char	*file;
	u_char	*line;
{
	FILE	*fp;

	if (*line != 'y' && *line != 'Y')
		return;
	if ((fp = fopen(CP(file), "w")) != NULL)
	{
		if (save_which & SFLAG_BIND)
			save_bindings(fp, save_do_all);
		if (save_which & SFLAG_ON)
			save_hooks(fp, save_do_all);
		if (save_which & SFLAG_NOTIFY)
			save_notify(fp);
		if (save_which & SFLAG_SET)
			save_variables(fp, save_do_all);
		if (save_which & SFLAG_ALIAS)
			save_aliases(fp, save_do_all);
		if (save_which & SFLAG_DIGRAPH)
			save_digraphs(fp);
		fclose(fp);
		say("IRCII settings saved to %s", file);
	}
	else
		say("Error opening %s: %s", file, strerror(errno));
}

/* save_settings: saves the current state of IRCII to a file */
/*ARGSUSED*/
static	void
save_settings(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	buffer[BIG_BUFFER_SIZE];
	u_char	*arg, *temp;
	int	all = 1, save_force = 0;

	save_which = save_do_all = 0;
	while ((arg = next_arg(args, &args)) != NULL)
	{
		if ('-' == *arg)
		{
			u_char	*cmd = NULL;

			all = 0;
			malloc_strcpy(&cmd, arg+1);
			upper(cmd);
			if (0 == my_strncmp("ALIAS", cmd, 5))
				save_which |= SFLAG_ALIAS;
			else if (0 == my_strncmp("ASSIGN", cmd, 6))
				save_which |= SFLAG_ALIAS;
			else if (0 == my_strncmp("BIND", cmd, 4))
				save_which |= SFLAG_BIND;
			else if (0 == my_strncmp("ON", cmd, 2))
				save_which |= SFLAG_ON;
			else if (0 == my_strncmp("SET", cmd, 3))
				save_which |= SFLAG_SET;
			else if (0 == my_strncmp("NOTIFY", cmd, 6))
				save_which |= SFLAG_NOTIFY;
			else if (0 == my_strncmp("DIGRAPH", cmd, 7))
				save_which |= SFLAG_DIGRAPH;
			else if (0 == my_strncmp("ALL", cmd, 3))
				save_do_all = 1;
			else if (0 == my_strncmp("FORCE", cmd, 3))
				save_force = 1;
			else
			{
				say("%s: unknown argument", arg);
				new_free(&cmd);
				return;
			}
			new_free(&cmd);
			continue;
		}
#ifdef DAEMON_UID
		if (getuid() == DAEMON_UID)
		{
			say("You may only use the default value");
			return;
		}
#endif /* DAEMON_UID */
		temp = expand_twiddle(arg);
		if (temp)
		{
			if (ircrc_file)
				new_free(&ircrc_file);
			ircrc_file = temp;
		}
		else
		{
			say("Unknown user");
			return;
		}
	}
	if (all || !save_which)
		save_which = SFLAG_ALIAS | SFLAG_BIND | SFLAG_ON | SFLAG_SET |
			     SFLAG_NOTIFY | SFLAG_DIGRAPH;
	if (dumb || save_force)
		really_save(ircrc_file, UP("y"));
	else
	{
		snprintf(CP(buffer), sizeof buffer, "Really write %s? ", ircrc_file);
		add_wait_prompt(buffer, really_save, ircrc_file,
				WAIT_PROMPT_LINE);
	}
}

/*
 * do_channel : checks whether the channel has already been joined and
 * returns the channel's name if not
 */
u_char *
do_channel(chan, force)
	u_char	*chan;
	int force;
{
	ChannelList	*channel;
	u_char		*old;

	if (from_server < 0 || curr_scr_win->server < 0)
		return (u_char *) 0;

	channel = lookup_channel(chan, curr_scr_win->server, CHAN_NOUNLINK);

	if (is_bound(chan, curr_scr_win->server) && channel && channel->window != curr_scr_win)
		say("Channel %s is bound", chan);
	else if (is_on_channel(chan, curr_scr_win->server, get_server_nickname(curr_scr_win->server)) ||
	    (get_server_version(from_server) == ServerICB && my_stricmp(get_server_icbgroup(from_server), chan) == 0))
	{
		is_current_channel(chan, curr_scr_win->server, 1);
		say("You are now talking to channel %s", set_channel_by_refnum(0, chan));
		update_all_windows();
	}
	else
	{
		/* only do this if we're actually joining a new channel */
		if (get_int_var(NOVICE_VAR) && get_server_version(from_server) != ServerICB)
		{
			if ((old = get_channel_by_refnum(0)) && my_strcmp(old, zero))
				send_to_server("PART %s", old);
		}
		add_channel(chan, 0, from_server, CHAN_JOINING, (ChannelList *) 0);
		force = 1;
	}
	if (force)
		return chan;
	else
		return (u_char *) 0;
}

/*
 * e_channel: does the channel command.  I just added displaying your current
 * channel if none is given 
 */
static	void
e_channel(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*chan;
	size_t	len;
	u_char	*chanstr = (u_char *) 0,
		*ptr;
	int 	force = 0;

	if (get_server_version(from_server) == Server2_5)
		command = UP("CHANNEL");
	save_message_from();
	message_from((u_char *) 0, LOG_CURRENT);		/* XXX should delete this */
	if ((chan = next_arg(args, &args)) != NULL)
	{
		len = MAX(2, my_strlen(chan));
		if (my_strnicmp(chan, UP("-force"), len) == 0)
		{
			force = 1;
			if ((chan = next_arg(args, &args)) == NULL)
				goto out;	/* XXX: allow /alias join join -force */
			len = MAX(2, my_strlen(chan));
		}
		if (my_strnicmp(chan, UP("-invite"), len) == 0)
		{
			if (invite_channel)
			{
				if ((ptr = do_channel(invite_channel, force)))
				{
					if (get_server_version(from_server) == ServerICB)
						icb_put_group(invite_channel);
					else
						send_to_server("%s %s %s", command, invite_channel, args);
				}
				else
					say("You are already on %s ?", invite_channel);
			}
			else
				say("You have not been invited to a channel!");
		}
		else if (get_server_version(from_server) == ServerICB)
		{
			if (do_channel(chan, force))
				icb_put_group(chan);
		}
		else
		{
			malloc_strcpy(&chanstr, chan);
			chan = chanstr;

			ptr = my_strsep(&chanstr, UP(","));
			if ((ptr = do_channel(ptr, force)) && *ptr)
				send_to_server("%s %s %s", command, ptr, args);

			while (get_int_var(NOVICE_VAR) == 0 && (ptr = my_strsep(&chanstr, UP(","))))
				if ((ptr = do_channel(ptr, force)) && *ptr)
					send_to_server("%s %s %s", command, ptr, args);

			new_free(&chan);
		}
	}
	else
out:
		list_channels();
	restore_message_from();
}

/* comment: does the /COMMENT command, useful in .ircrc */
/*ARGSUSED*/
static	void
commentcmd(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	/* nothing to do... */
}

/*
 * e_nick: does the /NICK command.  Records the users current nickname and
 * sends the command on to the server 
 */
/*ARGSUSED*/
static	void
e_nick(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*nick;

	if (!(nick = next_arg(args, &args)))
	{
		say("Your nickname is %s",
			get_server_nickname(get_window_server(0)));
		return;
	}
	if (get_server_version(from_server) == ServerICB)
	{
		icb_put_nick(nick);
		return;
	}
	send_to_server("NICK %s", nick);
	if (server_list[from_server].attempting_to_connect)
		set_server_nickname(get_window_server(0), nick);
	if (get_server_version(from_server) == Server2_5)
		add_to_whois_queue(nick, whois_nickname, NULL);
}

/* version: does the /VERSION command with some IRCII version stuff */
static	void
version(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*host;

	if (get_server_version(from_server) != ServerICB && ((host = next_arg(args, &args)) != NULL))
	{
		send_to_server("%s %s", command, host);
	}
	else
	{ 
		say("Client: ircII %s", irc_version);
		if (get_server_version(from_server) == ServerICB)
			icb_put_version(args);
		else
			send_to_server("%s", command);
	}
}

/*
 * info: does the /INFO command.  I just added some credits
 * I updated most of the text -phone, feb 1993.
 */
static	void
info(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	if (!args || !*args)
	{
		say("This is ircII version %s", irc_version);
		say(" - originally written by Michael Sandrof");
		say(" - versions 2.1 to 2.2pre7 by Troy Rollo");
		say(" - development continued by matthew green");
		say("       e-mail: mrg@eterna.com.au  irc: phone");
		say(" - copyright (c) 1990-2004");
		say(" - do a /help ircii copyright for the full copyright");
		say(" - ircii includes software developed by the university");
		say("   of california, berkeley and its contributors");
		say("");
		say("ircii contributors");
		say("");
		say("\tMichael Sandrof       Mark T. Dameu");
		say("\tStellan Klebom        Carl v. Loesch");
		say("\tTroy Rollo            Martin  Friedrich");
		say("\tMichael Weber         Bill Wisner");
		say("\tRiccardo Facchetti    Stephen van den Berg");
		say("\tVolker Paulsen        Kare Pettersson");
		say("\tIan Frechette         Charles Hannum");
		say("\tmatthew green         christopher williams");
		say("\tJonathan Lemon        Brian Koehmstedt");
		say("\tNicolas Pioch         Brian Fehdrau");
		say("\tDarren Reed           Jeff Grills");
		say("\tJeremy Nelson         Philippe Levan");
		say("\tScott Reynolds        Glen McCready");
		say("\tChristopher Kalt      Joel Yliluoma");
		say("\tFlier");
	}
	if (get_server_version(from_server) != ServerICB)
		send_to_server("%s %s", command, args);
}

void
ison_now(notused, nicklist, notused2)
	WhoisStuff	*notused;
	u_char		*nicklist,
			*notused2;
{
	if (do_hook(current_numeric, "%s", nicklist))
		put_it("%s Currently online: %s", numeric_banner(), nicklist);
}

static	void
ison(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	if (!args[strspn(CP(args), " ")])
		args = get_server_nickname(from_server);
	add_ison_to_whois(args, ison_now);
}

/*
 * userhost: Does the USERHOST command.  Need to split up the queries,
 * since the server will only reply to 5 at a time.
 */
static	void
userhost(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	int	n = 0,
		total = 0,
		userhost_cmd = 0;
	u_char	*nick;
	u_char	buffer[BIG_BUFFER_SIZE];

	while ((nick = next_arg(args, &args)) != NULL)
	{
		size_t	len;

		++total;
		len = my_strlen(nick);
		if (!my_strnicmp(nick, UP("-CMD"), len))
		{
			if (total < 2)
			{
				yell("userhost -cmd with no nick!");
				return;
			}
			userhost_cmd = 1;
			break;
		}
		else
		{
			if (n++)
				my_strmcat(buffer, " ", sizeof buffer);
			else
				*buffer = '\0';
			my_strmcat(buffer, nick, sizeof buffer);
		}
	}
	if (n)
	{
		u_char	*the_list = (u_char *) 0;
		u_char	*s, *t;
		int	i;

		malloc_strcpy(&the_list, buffer);
		s = t = the_list;
		while (n)
		{
			for (i = 5; i && *s; s++)
				if (' ' == *s)
					i--, n--;
			if (' ' == *(s - 1))
				*(s - 1) = '\0';
			else
				n--;
			my_strmcpy(buffer, t, sizeof buffer);
			t = s;

			if (userhost_cmd)
				add_to_whois_queue(buffer, userhost_cmd_returned, "%s", args);
			else
				add_to_whois_queue(buffer, USERHOST_USERHOST, 0);
		}
		new_free(&the_list);
	}
	else if (!total)
		/* Default to yourself.  */
		add_to_whois_queue(get_server_nickname(from_server), USERHOST_USERHOST, 0);
}

/*
 * whois: the WHOIS and WHOWAS commands.  This translates the 
 * to the whois handlers in whois.c 
 */
static	void
whois(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	if (get_server_version(from_server) == ServerICB)
	{
		int	display;
		u_char	*buf;
		size_t	len;

		display = window_display;
		window_display = 0;
		len = 7 + 1 + my_strlen(args) + 1;
		buf = new_malloc(len);
		snprintf(CP(buf), len, "whereis %s", args);
		icb_put_msg2(UP("server"), buf);
		new_free(&buf);
		window_display = display;
		return;
	}

	if (args && *args)
		send_to_server("%s %s", command, args);
	else /* Default to yourself  -lynx */
		send_to_server("%s %s", command, get_server_nickname(from_server));
}

/*
 * who: the /WHO command. Parses the who switches and sets the who_mask and
 * whoo_stuff accordingly.  Who_mask and who_stuff are used in whoreply() in
 * parse.c 
 */
static	void
who(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*arg,
		*channel = NULL;
	int	no_args = 1;
	size_t	len;

	if (get_server_version(from_server) == ServerICB)
	{
		icb_put_who(args);
		return;
	}

	who_mask = 0;
	new_free(&who_name);
	new_free(&who_host);
	new_free(&who_server);
	new_free(&who_file);
	new_free(&who_nick);
	new_free(&who_real);
	while ((arg = next_arg(args, &args)) != NULL)
	{
		no_args = 0;
		if ((*arg == '-') && (!isdigit(*(arg + 1))))
		{
			u_char	*cmd = NULL;

			arg++;
			if ((len = my_strlen(arg)) == 0)
			{
				say("Unknown or missing flag");
				return;
			}
			malloc_strcpy(&cmd, arg);
			lower(cmd);
			if (my_strncmp(cmd, "operators", len) == 0)
				who_mask |= WHO_OPS;
			else if (my_strncmp(cmd, "lusers", len) == 0)
				who_mask |= WHO_LUSERS;
			else if (my_strncmp(cmd, "chops", len) == 0)
				who_mask |= WHO_CHOPS;
			else if (my_strncmp(cmd, "hosts", len) == 0)
			{
				if ((arg = next_arg(args, &args)) != NULL)
				{
					who_mask |= WHO_HOST;
					malloc_strcpy(&who_host, arg);
					channel = who_host;
				}
				else
				{
					say("WHO -HOSTS: missing arguement");
					new_free(&cmd);
					return;
				}
			}
			else if (my_strncmp(cmd, "here", len) ==0)
				who_mask |= WHO_HERE;
			else if (my_strncmp(cmd, "away", len) ==0)
				who_mask |= WHO_AWAY;
			else if (my_strncmp(cmd, "servers", len) == 0)
			{
				if ((arg = next_arg(args, &args)) != NULL)
				{
					who_mask |= WHO_SERVER;
					malloc_strcpy(&who_server, arg);
					channel = who_server;
				}
				else
				{
					say("WHO -SERVERS: missing arguement");
					new_free(&cmd);
					return;
				}
			}
			else if (my_strncmp(cmd, "name", len) == 0)
			{
				if ((arg = next_arg(args, &args)) != NULL)
				{
					who_mask |= WHO_NAME;
					malloc_strcpy(&who_name, arg);
					channel = who_name;
				}
				else
				{
					say("WHO -NAME: missing arguement");
					new_free(&cmd);
					return;
				}
			}
			else if (my_strncmp(cmd, "realname", len) == 0)
			{
				if ((arg = next_arg(args, &args)) != NULL)
				{
					who_mask |= WHO_REAL;
					malloc_strcpy(&who_real, arg);
					channel = who_real;
				}
				else
				{
					say("WHO -REALNAME: missing arguement");
					new_free(&cmd);
					return;
				}
			}
			else if (my_strncmp(cmd, "nick", len) == 0)
			{
				if ((arg = next_arg(args, &args)) != NULL)
				{
					who_mask |= WHO_NICK;
					malloc_strcpy(&who_nick, arg);
					channel = who_nick;
				}
				else
				{
					say("WHO -NICK: missing arguement");
					new_free(&cmd);
					return;
				}
				/* WHO -FILE by Martin 'Efchen' Friedrich */
			}
			else if (my_strncmp(cmd, "file", len) == 0)
			{
				who_mask |= WHO_FILE;
				if ((arg = next_arg(args, &args)) != NULL)
				{
					malloc_strcpy(&who_file, arg);
				}
				else
				{
					say("WHO -FILE: missing arguement");
					new_free(&cmd);
					return;
				}
			}
			else
			{
				say("Unknown or missing flag");
				new_free(&cmd);
				return;
			}
			new_free(&cmd);
		}
		else if (my_strcmp(arg, "*") == 0)
		{
			channel = get_channel_by_refnum(0);
			if (!channel || *channel == '0')

			{
				say("I wouldn't do that if I were you");
				return;
			}
		}
		else
			channel = arg;
	}
	if (no_args)
		say("No argument specified");
	else
	{
		u_char *o = NULL;

		if (who_mask & WHO_OPS)
			o = UP(" o");
		if (!channel && who_mask & WHO_OPS)
			channel = UP("*");
		send_to_server("%s %s%s", command,
				channel ? channel : empty_string,
				o ? o : empty_string);
	}
}

/*
 * query: the /QUERY command.  Works much like the /MSG, I'll let you figure
 * it out.
 */
/*ARGSUSED*/
void
query(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*nick,
		*rest;

	save_message_from();
	message_from((u_char *) 0, LOG_CURRENT);
	if ((nick = next_arg(args, &rest)) != NULL)
	{
		if (my_strcmp(nick, ".") == 0)
		{
			if (!(nick = sent_nick))
			{
				say("You have not messaged anyone yet");
				goto out;
			}
		}
		else if (my_strcmp(nick, ",") == 0)
		{
			if (!(nick = recv_nick))
			{
				say("You have not recieved a message from \
						anyone yet");
				goto out;
			}
		}
		else if (my_strcmp(nick, "*") == 0)
			if (!(nick = get_channel_by_refnum(0)))
			{
				say("You are not on a channel");
				goto out;
			}

#ifndef _Windows
		if (*nick == '%')
		{
			if (is_process(nick) == 0)
			{
				say("Invalid processes specification");
				goto out;
			}
		}
#endif /* _Windows */
		say("Starting conversation with %s", nick);
		set_query_nick(nick);
	}
	else
	{
		if (query_nick())
		{
			say("Ending conversation with %s", query_nick());
			set_query_nick(NULL);
		}
		else
			say("You aren't querying anyone!");
	}
	update_input(UPDATE_ALL);
out:
	restore_message_from();
}

/*
 * away: the /AWAY command.  Keeps track of the away message locally, and
 * sends the command on to the server.
 */
static	void
away(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	size_t	len;
	u_char	*arg = NULL;
	int	flag = AWAY_ONE;
	int	i;

	if (*args)
	{
		if (*args == '-')
		{
			u_char	*cmd = (u_char *) 0;

			args = next_arg(args, &arg);
			len = my_strlen(args);
			if (len == 0)
			{
				say("%s: No argument given with -", command);
				return;
			}
			malloc_strcpy(&cmd, args);
			upper(cmd);
			if (0 == my_strncmp(cmd, "-ALL", len))
			{
				flag = AWAY_ALL;
				args = arg;
			}
			else if (0 == my_strncmp(cmd, "-ONE", len))
			{
				flag = AWAY_ONE;
				args = arg;
			}
			else
			{
				say("%s: %s unknown flag", command, args);
				new_free(&cmd);
				return;
			}
			new_free(&cmd);
		}
	}
	if (flag == AWAY_ALL)
		if (*args)
		{
			away_set = 1;
			MarkAllAway(command, args);
		}
		else
		{
			away_set = 0;
			for(i = 0; (i < number_of_servers); i++)
				if (server_list[i].whois_stuff.away)
					new_free(&(server_list[i].away));
		}
	else
	{
		send_to_server("%s :%s", command, args);
		if (*args)
		{
			away_set = 1;
			malloc_strcpy(&(server_list[
				curr_scr_win->server].away), args);
		}
		else
		{
			new_free(&(server_list[
				curr_scr_win->server].away));
			away_set = 0;
			for(i = 0; (i < number_of_servers) && !away_set ; i++)
				if (server_list[i].read != -1 &&
						server_list[i].away)
					away_set = 1;
		}
	}
	update_all_status();
}

/* e_quit: The /QUIT, /EXIT, etc command */
/*ARGSUSED*/
void
e_quit(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	int	max;
	int	i;
	u_char	*Reason;

	Reason = ((args && *args) ? args : (u_char *) "Leaving");
	max = number_of_servers;
	for (i = 0; i < max; i++)
		if (is_server_connected(i))
		{
			from_server = i;
			if (get_server_version(i) != ServerICB)
				send_to_server("QUIT :%s", Reason);
		}
	irc_exit();
}

/* flush: flushes all pending stuff coming from the server */
/*ARGSUSED*/
static	void
flush(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	if (get_int_var(HOLD_MODE_VAR))
	{
		while (curr_scr_win->held_lines)
			remove_from_hold_list(curr_scr_win);
		hold_mode((Window *) 0, OFF, 1);
	}
	say("Standby, Flushing server output...");
	flush_server();
	say("Done");
}

/* e_wall: used for WALL and WALLOPS */
static	void
e_wall(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	save_message_from();
	if (my_strcmp(command, "WALL") == 0)
	{	/* I hate this */
		message_from(NULL, LOG_WALL);
		if (!get_server_operator(from_server))
			put_it("## %s", args);
	}
	else
	{
		message_from(NULL, LOG_WALLOP);
		if (!get_server_flag(from_server, USER_MODE_W))
			put_it("!! %s", args);
	}
	if (!in_on_who)
		send_to_server("%s :%s", command, args);
	restore_message_from();
}

void
redirect_msg(dest, msg)
	u_char *dest;
	u_char *msg;
{
	u_char	buffer[BIG_BUFFER_SIZE];

	my_strmcpy(buffer, dest, sizeof buffer);
	my_strmcat(buffer, " ", sizeof buffer);
	my_strmcat(buffer, msg, sizeof buffer);
	e_privmsg(UP("PRIVMSG"), buffer, NULL);
}

/*
 * e_privmsg: The MSG command, displaying a message on the screen indicating
 * the message was sent.  Also, this works for the NOTICE command. 
 */
static	void
e_privmsg(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*nick;
	int old_from_server = -2;

	if ((nick = next_arg(args, &args)) != NULL)
	{
		if (my_stricmp(nick, UP("-server")) == 0)
		{
			u_char *server;
			int sgroup, target_server = -1;

			if ((server = next_arg(args, &args)) == NULL)
			{
bad_server:
				say("You must supply a valid server name or "
				    "group with -server");
				goto out;
			}
			if ((nick = next_arg(args, &args)) == NULL)
				goto missing_nick;
			sgroup = find_server_group(server, 0);
			if (sgroup == 0) {
				target_server = my_atoi(server);
				if (target_server < 0 || target_server >= number_of_servers)
				{
					u_char	*port = (u_char *) 0,
						*nick2 = (u_char *) 0,
						*foo = (u_char *) 0;
					int type, port_num = 0;

					parse_server_info(&server, &port, &foo,
							  &nick2, &foo, &foo, &type);
					if (port && *port)
						port_num = my_atoi(port);
					target_server = find_in_server_list(server,
								port_num, nick2);
				}
			} else
				target_server = active_server_group(sgroup);

			if (target_server == -1)
				goto bad_server;

			old_from_server = from_server;
			from_server = target_server;
		}

		if (my_strcmp(nick, ".") == 0)
		{
			if (!(nick = sent_nick))
			{
				say("You haven't sent a message to anyone yet");
				goto out;
			}
		}

		else if (my_strcmp(nick, ",") == 0)
		{
			if (!(nick = recv_nick))
			{
				say("You have not received a message from anyone yet");
				goto out;
			}
		}
		else if (!my_strcmp(nick, "*"))
			if (!(nick = get_channel_by_refnum(0)))
				nick = zero;
		send_text(nick, args, command);
	}
	else
missing_nick:
		say("You must specify a nickname or channel!");
out:
	if (old_from_server != -2)
		from_server = old_from_server;
}

/*
 * quote: handles the QUOTE command.  args are a direct server command which
 * is simply send directly to the server 
 */
/*ARGSUSED*/
static	void
quote(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	if (!in_on_who)
		send_to_server("%s", args);
}

/* clear: the CLEAR command.  Figure it out */
/*ARGSUSED*/
static	void
my_clear(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*arg;
	int	all = 0,
		unhold = 0;

	while ((arg = next_arg(args, &args)) != NULL)
	{
		upper(arg);
		/* -ALL and ALL here becuase the help files used to be wrong */
		if (!my_strncmp(arg, "ALL", my_strlen(arg))
				|| !my_strncmp(arg, "-ALL", my_strlen(arg)))
			all = 1;
		else if (!my_strncmp(arg, "-UNHOLD", my_strlen(arg)))
			unhold = 1;
		else
			say("Unknown flag: %s", arg);
	}
	if (all)
		clear_all_windows(unhold);
	else
	{
		if (unhold)
			hold_mode((Window *) 0, OFF, 1);
		clear_window_by_refnum(0);
	}
	update_input(UPDATE_JUST_CURSOR);
}

/*
 * send_comm: the generic command function.  Uses the full command name found
 * in 'command', combines it with the 'args', and sends it to the server 
 */
static	void
send_comm(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	if (args && *args)
		send_to_server("%s %s", command, args);
	else
		send_to_server("%s", command);
}

static	void
send_invite(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{

	if (get_server_version(from_server) == ServerICB)
		icb_put_invite(args);
	else
		send_comm(command, args, subargs);
}

static	void
send_motd(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{

	if (get_server_version(from_server) == ServerICB)
		icb_put_motd(args);
	else
		send_comm(command, args, subargs);
}

static	void
send_topic(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*arg;
	u_char	*arg2;

	if (get_server_version(from_server) == ServerICB)
	{
		icb_put_topic(args);
		return;
	}
	else
	if (!(arg = next_arg(args, &args)) || (my_strcmp(arg, "*") == 0))
		arg = get_channel_by_refnum(0);

	if (!arg)
	{
		say("You aren't on a channel in this window");
		return;
	}
	if (is_channel(arg))
	{
		if ((arg2 = next_arg(args, &args)) != NULL)
			send_to_server("%s %s :%s %s", command, arg,
					arg2, args);
		else
			send_to_server("%s %s", command, arg);
	}
	else
	if (get_channel_by_refnum(0))
		send_to_server("%s %s :%s", command, get_channel_by_refnum(0), subargs);
	else
		say("You aren't on a channel in this window");
}

static void
send_squery(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	put_it("*** Sent to service %s: %s", command, args);
	send_2comm(command, args, subargs);
}

static void
send_brick(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{

	if (args && *args)
	{
		u_char	*channel;

		channel = next_arg(args, &args);
		send_to_server("%s %s :%s", command, channel, args);
	}
	else
		send_to_server("%s", command);
}

/*
 * send_2comm: Sends a command to the server with one arg and
 * one comment. Used for KILL and SQUIT.
 */
static	void
send_2comm(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*comment;

	args = next_arg(args, &comment);
	
	send_to_server("%s %s %c%s",
		       command,
		       args && *args ? args : (u_char *) "",
		       comment && *comment ? ':' : ' ',
		       comment && *comment ? comment : (u_char *) "");
}

/*
 * send_channel_nargs: Sends a command to the server with one channel,
 * and 0-n args. Used for MODE.
 */

static	void
send_channel_nargs(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*arg1 = 0,
	        *s = get_channel_by_refnum(0);

	args = next_arg(args, &arg1);
	if (!args || !my_strcmp(args, "*"))
	{
		if (s)
			args = s;
		else
		{
			say("You aren't on a channel in this window");
			return;
		}
	}

	send_to_server("%s %s %s",
		       command,
		       args,
		       arg1 && *arg1 ? arg1 : (u_char *) "");
}

/*
 * send_channel_2args: Sends a command to the server with one channel,
 * one arg and one comment. Used for KICK
 */

static	void
send_channel_2args(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*arg1 = 0,
		*comment = 0,
	        *s = get_channel_by_refnum(0);

	args = next_arg(args, &arg1);
	if (!args || !my_strcmp(args, "*"))
	{
		if (s)
			args = s;
		else
		{
			say("You aren't on a channel in this window");
			return;
		}
	}

	if (arg1 && *arg1)
		arg1 = next_arg(arg1, &comment);
	
	send_to_server("%s %s %s %c%s",
		       command,
		       args,
		       arg1 && *arg1 ? arg1 : (u_char *) "",
		       comment && *comment ? ':' : ' ',
		       comment && *comment ? comment : (u_char *) "");
}

/*
 * send_channel_1arg: Sends a command to the server with one channel
 * and one comment. Used for PART (LEAVE)
 */
static	void
send_channel_1arg(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*comment,
		*s = get_channel_by_refnum(0);

	args = next_arg(args, &comment);

	if (!args || !my_strcmp(args, "*"))
	{
		if (s)
			args = s;
		else
		{
			say("You aren't on a channel in this window");
			return;
		}
	}

	send_to_server("%s %s %c%s",
		       command,
		       args,
		       comment && *comment ? ':' : ' ',
		       comment && *comment ? comment : (u_char *) "");
}

/*
 * send_text: Sends the line of text to whomever the user is currently
 * talking.  If they are quering someone, it goes to that user, otherwise
 * it's the current channel.  Some tricky parameter business going on. If
 * nick is null (as if you had typed "/ testing" on the command line) the
 * line is sent to your channel, and the command parameter is never used. If
 * nick is not null, and command is null, the line is sent as a PRIVMSG.  If
 * nick is not null and command is not null, the message is sent using
 * command.  Currently, only NOTICEs and PRIVMSGS work. 
 * fixed to not be anal about "/msg foo,bar foobar" -phone
 */
void
send_text(org_nick, line, command)
	u_char	*org_nick;
	u_char	*line;
	u_char	*command;
{
	crypt_key	*key;
	u_char 	*ptr,
		*free_nick,
		*nick = NULL;
	int	lastlog_level,
		list_type,
		old_server;
	int	check_away = 0;
	u_char	the_thing;
	u_char	*query_command = NULL;
	u_char	nick_list[IRCD_BUFFER_SIZE];
	int	do_final_send = 0;
	int	is_icb = get_server_version(from_server) == ServerICB;
	
	*nick_list = '\0';
	malloc_strcpy(&nick, org_nick);
	free_nick = ptr = nick;
	save_message_from();
	while ((nick = ptr) != NULL)
	{
		if (is_icb && is_current_channel(nick, curr_scr_win->server, 0))
			ptr = NULL;
		else if ((ptr = my_index(nick, ',')) != NULL)
			*(ptr++) = (u_char) 0;
		if (!*nick)
			continue;
#ifndef _Windows
		if (is_process(nick))
		{
			int	i;

			if ((i = get_process_index(&nick)) == -1)
				say("Invalid process specification");
			else
				text_to_process(i, line, 1);
			continue;
		}
#endif /* _Windows */
		if (!*line)
			continue; /* lynx */
		if (in_on_who && *nick != '=') /* allow dcc messages anyway */
		{
			say("You may not send messages from ON WHO, ON WHOIS, or ON JOIN");
			continue;
		}
		if (doing_privmsg)
			command	= UP("NOTICE");
		if (is_current_channel(nick, curr_scr_win->server, 0))
		{
			/* nothing */
		}
		else if (*nick == '\\') /* quoteme */
			nick++;
		else if (my_strcmp(nick, "\"") == 0) /* quote */
		{
			send_to_server("%s", line);
			continue;
		}
		else if (*nick == '=') /* DCC chat */
		{
			old_server = from_server;
			from_server = -1;
			dcc_chat_transmit(nick + 1, line);
			from_server = old_server;
			continue;
		}
		else if (*nick == '/') /* Command */
		{
			malloc_strcpy(&query_command, nick);
			malloc_strcat(&query_command, UP(" "));
			malloc_strcat(&query_command, line);
			parse_command(query_command, 0, empty_string);
			new_free(&query_command);
			continue;
		}
		if (send_text_flag == NOTICE_LIST)
		{
			say("You cannot send a message from a NOTICE");
			new_free(&free_nick);
			goto out;
		}
		if (is_icb)
		{
			if (my_stricmp(nick, get_server_icbgroup(from_server)) != 0 ||
			    (command && my_strcmp(command, "PRIVMSG") == 0)) {
				icb_put_msg2(nick, line);
				malloc_strcpy(&sent_nick, nick);
			} else
				icb_put_public(line);
		}
		else
		{	/* special */
		if (send_text_flag == MSG_LIST)
			command = UP("NOTICE");
		if (is_channel(nick))
		{
			int	current;

			current = is_current_channel(nick, curr_scr_win->server, 0);
			if (!command || my_strcmp(command, "NOTICE"))
			{
				check_away = 1;
				command = UP("PRIVMSG");
				lastlog_level = set_lastlog_msg_level(LOG_PUBLIC);
				message_from(nick, LOG_PUBLIC);
				list_type = SEND_PUBLIC_LIST;
				the_thing = '>';
			}
			else
			{
				lastlog_level = set_lastlog_msg_level(LOG_NOTICE);
				message_from(nick, LOG_NOTICE);
				list_type = SEND_NOTICE_LIST;
				the_thing = '-';
			}
			if (do_hook(list_type, "%s %s", nick, line))
			{
				if (current)
					put_it("%c %s", the_thing, line);
				else
					put_it("%c%s> %s", the_thing, nick,
						line);
			}
			set_lastlog_msg_level(lastlog_level);
			if ((key = is_crypted(nick)) != 0)
			{
				u_char	*crypt_line;

				if ((crypt_line = crypt_msg(line, key, 1)))
					send_to_server("%s %s :%s", command, nick, crypt_line);
				continue;
			}
			if (!in_on_who)
			{
				if (*nick_list)
				{
					my_strmcat(nick_list, ",", sizeof nick_list);
					my_strmcat(nick_list, nick, sizeof nick_list);
				}
				else
					my_strmcpy(nick_list, nick, sizeof nick_list);
			}
			do_final_send = 1;
		}
		else
		{
			if (!command || my_strcmp(command, "NOTICE"))
			{
				check_away = 1;
				lastlog_level = set_lastlog_msg_level(LOG_MSG);
				command = UP("PRIVMSG");
				message_from(nick, LOG_MSG);
				list_type = SEND_MSG_LIST;
				the_thing = '*';
			}
			else
			{
				lastlog_level = set_lastlog_msg_level(LOG_NOTICE);
				message_from(nick, LOG_NOTICE);
				list_type = SEND_NOTICE_LIST;
				the_thing = '-';
			}
			if (window_display && do_hook(list_type, "%s %s", nick, line))
				put_it("-> %c%s%c %s", the_thing, nick, the_thing, line);
			if ((key = is_crypted(nick)) != NULL)
			{
				u_char	*crypt_line;

				if ((crypt_line = crypt_msg(line, key, 1)))
					send_to_server("%s %s :%s", command ? command : (u_char *) "PRIVMSG", nick, crypt_line);
				continue;
			}
			set_lastlog_msg_level(lastlog_level);

			if (!in_on_who)
			{
				if (*nick_list)
				{
					my_strmcat(nick_list, ",", sizeof nick_list);
					my_strmcat(nick_list, nick, sizeof nick_list);
				}
				else
					my_strmcpy(nick_list, nick, sizeof nick_list);
			}

			if (get_int_var(WARN_OF_IGNORES_VAR) && (is_ignored(nick, IGNORE_MSGS) == IGNORED))
				say("Warning: You are ignoring private messages from %s", nick);

			malloc_strcpy(&sent_nick, nick);
			do_final_send = 1;
		}
		}	/* special */
	}
	if (check_away && server_list[curr_scr_win->server].away && get_int_var(AUTO_UNMARK_AWAY_VAR) &&
	    get_server_version(from_server) != ServerICB)
		away(UP("AWAY"), empty_string, empty_string);

	malloc_strcpy(&sent_body, line);
	if (do_final_send)
		send_to_server("%s %s :%s", command ? command : (u_char *) "PRIVMSG", nick_list, line);
	new_free(&free_nick);
out:
	restore_message_from();
}

static void
do_send_text(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*tmp;

	if (command)
		tmp = get_channel_by_refnum(0);
	else
		tmp = get_target_by_refnum(0);
	send_text(tmp, args, NULL);
}

/*
 * command_completion: builds lists of commands and aliases that match the
 * given command and displays them for the user's lookseeing 
 */
void
command_completion(key, ptr)
	u_int	key;
	u_char	*ptr;
{
	int	do_aliases;
	int	cmd_cnt,
		alias_cnt,
		i,
		c,
		len;
	u_char	**aliases = NULL;
	u_char	*line = NULL,
		*com,
		*cmdchars,
		*rest,
		firstcmdchar = '/';
	u_char	buffer[BIG_BUFFER_SIZE];
	IrcCommand	*command;

	malloc_strcpy(&line, get_input());
	if ((com = next_arg(line, &rest)) != NULL)
	{
		if (!(cmdchars = get_string_var(CMDCHARS_VAR)))
			cmdchars = UP(DEFAULT_CMDCHARS);
		if (my_index(cmdchars, *com))
		{
			firstcmdchar = *cmdchars;
			com++;
			if (*com && my_index(cmdchars, *com))
			{
				do_aliases = 0;
				alias_cnt = 0;
				com++;
			}
			else
				do_aliases = 1;
			upper(com);
			if (do_aliases)
				aliases = match_alias(com, &alias_cnt,
					COMMAND_ALIAS);
			if ((command = find_command(com, &cmd_cnt)) != NULL)
			{
				if (cmd_cnt < 0)
					cmd_cnt *= -1;
				/* special case for the empty string */

				if (*(command[0].name) == (u_char) 0)
				{
					command++;
					cmd_cnt = NUMBER_OF_COMMANDS;
				}
			}
			if ((alias_cnt == 1) && (cmd_cnt == 0))
			{
				snprintf(CP(buffer), sizeof buffer, "%c%s %s", firstcmdchar,
					aliases[0], rest);
				set_input(buffer);
				new_free(&(aliases[0]));
				new_free(&aliases);
				update_input(UPDATE_ALL);
			}
			else if (((cmd_cnt == 1) && (alias_cnt == 0)) ||
			    ((cmd_cnt == 1) && (alias_cnt == 1) &&
			    (my_strcmp(aliases[0], command[0].name) == 0)))
			{
				snprintf(CP(buffer), sizeof buffer, "%c%s%s %s", firstcmdchar,
					do_aliases ? (u_char *) "" : &firstcmdchar,
					command[0].name, rest);
				set_input(buffer);
				update_input(UPDATE_ALL);
			}
			else
			{
				*buffer = (u_char) 0;
				if (command)
				{
					say("Commands:");
					my_strmcpy(buffer, "\t", sizeof buffer);
					c = 0;
					for (i = 0; i < cmd_cnt; i++)
					{
						my_strmcat(buffer, command[i].name,
							sizeof buffer);
						for (len =
						    my_strlen(command[i].name);
						    len < 15; len++)
							my_strmcat(buffer, " ",
							    sizeof buffer);
						if (++c == 4)
						{
							say("%s", buffer);
							my_strmcpy(buffer, "\t",
							    sizeof buffer);
							c = 0;
						}
					}
					if (c)
						say("%s", buffer);
				}
				if (aliases)
				{
					say("Aliases:");
					my_strmcpy(buffer, "\t", sizeof buffer);
					c = 0;
					for (i = 0; i < alias_cnt; i++)
					{
						my_strmcat(buffer, aliases[i],
							sizeof buffer);
						for (len = my_strlen(aliases[i]);
								len < 15; len++)
							my_strmcat(buffer, " ",
							    sizeof buffer);
						if (++c == 4)
						{
							say("%s", buffer);
							my_strmcpy(buffer, "\t",
							    sizeof buffer);
							c = 0;
						}
						new_free(&(aliases[i]));
					}
					if ((int) my_strlen(buffer) > 1)
						say("%s", buffer);
					new_free(&aliases);
				}
				if (!*buffer)
					term_beep();
			}
		}
		else
			term_beep();
	}
	else
		term_beep();
	new_free(&line);
}

/*
 * parse_line: This is the main parsing routine.  It should be called in
 * almost all circumstances over parse_command().
 *
 * parse_line breaks up the line into commands separated by unescaped
 * semicolons if we are in non interactive mode. Otherwise it tries to leave
 * the line untouched.
 *
 * Currently, a carriage return or newline breaks the line into multiple
 * commands too. This is expected to stop at some point when parse_command
 * will check for such things and escape them using the ^P convention.
 * We'll also try to check before we get to this stage and escape them before
 * they become a problem.
 *
 * Other than these two conventions the line is left basically untouched.
 */
void
parse_line(name, org_line, args, hist_flag, append_flag, eat_space)
	u_char	*name,
		*org_line,
		*args;
	int	hist_flag,
		append_flag,
		eat_space;
{
	u_char	*line = NULL,
		*free_line, *stuff, *start, *lbuf, *s, *t;
	int	args_flag;

	malloc_strcpy(&line, org_line);
	free_line = line;
	args_flag = 0;
	if (!*line)
		do_send_text(NULL, empty_string, empty_string);
	else if (args)
		do
		{
			stuff = expand_alias(name, line, args, &args_flag,
					&line);
			start = stuff;
			if (eat_space)
				for (; isspace(*start); start++)
					;       

			if (!line && append_flag && !args_flag && args && *args)
			{
				lbuf = (u_char *) new_malloc(my_strlen(stuff) + 1 + my_strlen(args) + 1);
				my_strcpy(lbuf, start);
				my_strcat(lbuf, " ");
				my_strcat(lbuf, args);
				new_free(&stuff);
				start = stuff = lbuf;
			}
			parse_command(start, hist_flag, args);
			new_free(&stuff);
		}
		while (line);
	else
	{
		start = line;
		if (eat_space)
			for (; isspace(*start); start++)
				;
		if (load_depth)
			parse_command(start, hist_flag, args);
		else
			while ((s = line))
			{
				if ((t = sindex(line, UP("\r\n"))) != NULL)
				{
					*t++ = '\0';
					if (eat_space)
						for (; isspace(*t); t++)
							;
					line = t;
				}
				else
					line = NULL;
				parse_command(s, hist_flag, args);
			}
	}
	new_free(&free_line);
	return;
}

/*
 * parse_command: parses a line of input from the user.  If the first
 * character of the line is equal to irc_variable[CMDCHAR_VAR].value, the
 * line is used as an irc command and parsed appropriately.  If the first
 * character is anything else, the line is sent to the current channel or to
 * the current query user.  If hist_flag is true, commands will be added to
 * the command history as appropriate.  Otherwise, parsed commands will not
 * be added. 
 *
 * Parse_command() only parses a single command.  In general, you will want
 * to use parse_line() to execute things.Parse command recognized no quoted
 * characters or anything (beyond those specific for a given command being
 * executed). 
 */
void
parse_command(line, hist_flag, sub_args)
	u_char	*line;
	int	hist_flag;
	u_char	*sub_args;
{
	static	unsigned int	 level = 0;
	unsigned int	display,
			old_display_var;
	u_char	*cmdchars,
		*com,
		*this_cmd = NULL;
	int	args_flag,
		add_to_hist,
		cmdchar_used;

	if (!line || !*line)
		return;
	if (get_int_var(DEBUG_VAR) & DEBUG_COMMANDS)
		yell("Executing [%d] %s", level, line);
	level++;
	if (!(cmdchars = get_string_var(CMDCHARS_VAR)))
		cmdchars = UP(DEFAULT_CMDCHARS);
	malloc_strcpy(&this_cmd, line);
	add_to_hist = 1;
	if (my_index(cmdchars, *line))
	{
		cmdchar_used = 1;
		com = line + 1;
	}
	else
	{
		cmdchar_used = 0;
		com = line;
	}
	/*
	 * always consider input a command unless we are in interactive mode
	 * and command_mode is off.   -lynx
	 */
	if (hist_flag && !cmdchar_used && !get_int_var(COMMAND_MODE_VAR))
	{
		do_send_text(NULL, line, empty_string);
		if (hist_flag && add_to_hist)
		{
			add_to_history(this_cmd);
			set_input(empty_string);
		}
		/* Special handling for ' and : */
	}
	else if (*com == '\'' && get_int_var(COMMAND_MODE_VAR))
	{
		do_send_text(NULL, line+1, empty_string);
		if (hist_flag && add_to_hist)
		{
			add_to_history(this_cmd);
			set_input(empty_string);
		}
	}
	else if (*com == '@')
	{
		/* This kludge fixes a memory leak */
		u_char	*tmp;

		tmp = parse_inline(line + 1, sub_args, &args_flag);
		if (tmp)
			new_free(&tmp);
		if (hist_flag && add_to_hist)
		{
			add_to_history(this_cmd);
			set_input(empty_string);
		}
	}
	else
	{
		u_char	*rest,
			*nalias = NULL,
			*alias_name;
		int	cmd_cnt,
			alias_cnt;
		IrcCommand	*command; /* = (IrcCommand *) 0 */

		display = window_display;
		old_display_var = (unsigned) get_int_var(DISPLAY_VAR);
		if ((rest = my_index(com, ' ')) != NULL)
			*(rest++) = (u_char) 0;
		else
			rest = empty_string;
		upper(com);

		/* first, check aliases */
		if (*com && my_index(cmdchars, *com))
		{
			alias_cnt = 0;
			com++;
			if (*com == '^')
			{
				com++;
				window_display = 0;
			}
		}
		else
		{
			if (*com == '^')
			{
				com++;
				window_display = 0;
			}
			nalias = get_alias(COMMAND_ALIAS, com, &alias_cnt,
				&alias_name);
		}
		if (nalias && (alias_cnt == 0))
		{
			if (hist_flag && add_to_hist)
			{
				add_to_history(this_cmd);
				set_input(empty_string);
			}
			execute_alias(alias_name, nalias, rest);
			new_free(&alias_name);
		}
		else
		{
			/* History */
			if (*com == '!')
			{
				if ((com = do_history(com + 1, rest)) != NULL)
				{
					if (level == 1)
					{
						set_input(com);
						update_input(UPDATE_ALL);
					}
					else
						parse_command(com, 0, sub_args);
					new_free(&com);
				}
				else
					set_input(empty_string);
			}
			else
			{
				if (hist_flag && add_to_hist)
				{
					add_to_history(this_cmd);
					set_input(empty_string);
				}
				command = find_command(com, &cmd_cnt);
				if ((command && cmd_cnt < 0) || (0 == alias_cnt && 1 == cmd_cnt))
				{
					if ((command->flags & SERVERREQ) && connected_to_server == 0)
						say("%s: You are not connected to a server. Use /SERVER to connect.", com);
					else if ((command->flags & NOICB) && get_server_version(from_server) == ServerICB)
						say("%s: Not available for ICB.", command->name);
					else if (command->func)
						command->func(UP(command->server_func), rest, sub_args);
					else
						say("%s: command disabled", command->name);
				}
				else if (nalias && 1 == alias_cnt && cmd_cnt == 1 && !my_strcmp(alias_name, command[0].name))
					execute_alias(alias_name, nalias, rest);
				else if ((alias_cnt + cmd_cnt) > 1)
					say("Ambiguous command: %s", com);
				else if (nalias && 1 == alias_cnt)
					execute_alias(alias_name, nalias, rest);
				else if (!my_stricmp(com, nickname))
						/* nick = /me  -lynx */
					me(NULL, rest, empty_string);
				else
					say("Unknown command: %s", com);
			}
			if (nalias)
				new_free(&alias_name);
		}
		if (old_display_var != get_int_var(DISPLAY_VAR))
			window_display = get_int_var(DISPLAY_VAR);
		else
			window_display = display;
	}
	new_free(&this_cmd);
	level--;
}

/*
 * load: the /LOAD command.  Reads the named file, parsing each line as
 * though it were typed in (passes each line to parse_command). 
 */
/*ARGSUSED*/
void
load(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	FILE	*fp;
	u_char	*filename,
		*expanded = NULL;
	int	flag = 0;
	struct	stat	stat_buf;
	int	paste_level = 0;
	u_char	*start,
		*current_row = NULL,
		lbuf[BIG_BUFFER_SIZE];
	int	no_semicolon = 1;
	u_char	*ircpath;
	int	display;
#ifdef ZCAT
	u_char	*expand_z = NULL;
	int	exists;
	int	pos;
#endif /* ZCAT */

	ircpath = get_string_var(LOAD_PATH_VAR);
	if (!ircpath)
	{
		say("LOAD_PATH has not been set");
		return;
	}

	if (load_depth == MAX_LOAD_DEPTH)
	{
		say("No more than %d levels of LOADs allowed", MAX_LOAD_DEPTH);
		return;
	}
	load_depth++;
	status_update(0);
#ifdef DAEMON_UID
	if (getuid() == DAEMON_UID)
	{
		say("You may only load your SAVED file");
		filename = ircrc_file;
	}
	else
#endif /* DAEMON_UID */
		while ((filename = next_arg(args, &args)) != NULL)
		{
			if (my_strnicmp(filename, UP("-args"), my_strlen(filename)) == 0)
				flag = 1;
			else
				break;
		}
	if (filename)
	{
		if ((expanded = expand_twiddle(filename)) != NULL)
		{
#ifdef ZCAT
			/* Handle both <expanded> and <expanded>.Z */
			pos = my_strlen(expanded) - my_strlen(ZSUFFIX);
			if (pos < 0 || my_strcmp(expanded + pos, ZSUFFIX))
			{
				malloc_strcpy(&expand_z, expanded);
				malloc_strcat(&expand_z, UP(ZSUFFIX));
			}
#endif /* ZCAT */
			if (*expanded != '/')
			{
				filename = path_search(expanded, ircpath);
#ifdef ZCAT
				if (!filename && expand_z)
					filename = path_search(expand_z, ircpath);
#endif /* ZCAT */
				if (!filename)
				{
					say("%s: File not found", expanded);
					status_update(1);
					load_depth--;
#ifdef ZCAT
					new_free(&expand_z);
#endif /* ZCAT */
					new_free(&expanded);
					return;
				}
				else
					malloc_strcpy(&expanded, filename);
			}
#ifdef ZCAT
			if ((exists = stat(CP(expanded), &stat_buf)) == -1)
			{
				if (!(exists = stat(CP(expand_z), &stat_buf)))
				{
					if (expanded)
						new_free(&expanded);
					expanded = expand_z;
				}
				else
					new_free(&expand_z);
			}
			if (exists == 0)
#else
				if (!stat(expanded, &stat_buf))
#endif /* ZCAT */
				{
					if (stat_buf.st_mode & S_IFDIR)
					{
						say("%s is a directory", expanded);
						status_update(1);
						load_depth--;
#ifdef ZCAT
						new_free(&expand_z);
#endif /* ZCAT */
						new_free(&expanded);
						return;
					}
					/* sigh.  this is lame */
#if defined(S_IXUSR) && defined(S_IXGRP) && defined(S_IXOTH)
# define IS_EXECUTABLE (S_IXUSR|S_IXGRP|S_IXOTH)
#else
# define IS_EXECUTABLE 0111
#endif /* S_IXUSR && S_IXGRP && S_IXOTH */
					if (stat_buf.st_mode & IS_EXECUTABLE)
					{
						yell("*** %s is executable and may not be loaded", expanded);
						status_update(1);
						load_depth--;
#ifdef ZCAT
						new_free(&expand_z);
#endif /* ZCAT */
						new_free(&expanded);
						return;
					}
				}
			if (command && *command == 'W')
			{
				say("%s", expanded);
				status_update(1);
				load_depth--;
				new_free(&expanded);
#ifdef ZCAT
				new_free(&expand_z);
#endif /* ZCAT */
				return;
			}
#ifdef ZCAT
			/* Open if uncompressed, zcat if compressed */
			pos = my_strlen(expanded) - my_strlen(ZSUFFIX);
			if (pos >= 0 && !my_strcmp(expanded + pos, ZSUFFIX))
				fp = zcat(expanded);
			else
				fp = fopen(CP(expanded), "r");
			if (fp != NULL)
#else
				if (fp = fopen(CP(expanded), "r"))
#endif /* ZCAT */
				{
					display = window_display;
					window_display = 0;
					current_row = NULL;
					if (!flag)
						args = NULL;
					for (;;)
					{
						if (fgets(CP(lbuf), sizeof(lbuf) / 2, fp))	/* XXX need better /load policy, but this will do for now */
	{
		size_t	len;
		u_char	*ptr;

		for (start = lbuf; isspace(*start); start++)
			;
		if (!*start || *start == '#')
			continue;

		len = my_strlen(start);
	/*
	 * this line from stargazer to allow \'s in scripts for continued
	 * lines <spz@specklec.mpifr-bonn.mpg.de>
	 */
		while (start[len-1] == '\n' && start[len-2] == '\\' &&
		    len < sizeof(lbuf) / 2 && fgets(CP(&(start[len-2])),
		    (int)(sizeof(lbuf) / 2 - len), fp))
			len = my_strlen(start);

		if (start[len - 1] == '\n')
		    start[--len] = '\0';

		while (start && *start)
		{
			u_char	*optr = start;
			while ((ptr = sindex(optr, UP("{};"))) &&
					ptr != optr &&
					ptr[-1] == '\\')
				optr = ptr+1;

			if (no_semicolon)
				no_semicolon = 0;
			else if ((!ptr || ptr != start) && current_row)
			{
				if (!paste_level)
				{
					parse_line(NULL, current_row,
						args, 0, 0, 0);
					new_free(&current_row);
				}
				else
					malloc_strcat(&current_row, UP(";"));
			}

			if (ptr)
			{
				u_char	c = *ptr;

				*ptr = '\0';
				malloc_strcat(&current_row, start);
				*ptr = c;

				switch (c)
				{
				case '{' :
					paste_level++;
					if (ptr == start)
						malloc_strcat(&current_row, UP(" {"));
					else
						malloc_strcat(&current_row, UP("{"));
					no_semicolon = 1;
					break;

				case '}' :
					if (!paste_level)
						yell("Unexpected }");
					else
					{
						--paste_level;
						malloc_strcat(&current_row, UP("}"));
						no_semicolon = ptr[1] ? 1 : 0;
					}
					break;

				case ';' :
					malloc_strcat(&current_row, UP(";"));
					no_semicolon = 1;
					break;
				}

				start = ptr+1;
			}
			else
			{
				malloc_strcat(&current_row, start);
				start = NULL;
			}
		}
	}
						else
							break;
					}
					if (current_row)
					{
						if (paste_level)
							yell("Unexpected EOF");
						else
							parse_line(NULL,
								current_row, 
								args, 0, 0, 0);
						new_free(&current_row);
					}
					window_display = display;
					fclose(fp);
				}
				else
					say("Couldn't open %s: %s", expanded,
						strerror(errno));
			new_free(&expanded);
#ifdef ZCAT
			new_free(&expand_z);
#endif /* ZCAT */
		}
		else
			say("Unknown user");
	}
	else
		say("No filename specified");
	status_update(1);
	load_depth--;
}

/*
 * get_history: gets the next history entry, either the PREV entry or the
 * NEXT entry, and sets it to the current input string 
 */
static void	
get_history(which)
	int	which;
{
	u_char	*ptr;

	if ((ptr = get_from_history(which)) != NULL)
	{
		Debug((3, "get_history: get_from_history(%d) gave ``%s''", which, ptr));
		set_input_raw(ptr);
		update_input(UPDATE_ALL);
	}
}

/* BIND function: */
void
forward_character(key, ptr)
	u_int	key;
	u_char	*ptr;
{
	input_move_cursor(RIGHT);
}

void
backward_character(key, ptr)
	u_int	key;
	u_char	*ptr;
{
	input_move_cursor(LEFT);
}

void
backward_history(key, ptr)
	u_int	key;
	u_char	*ptr;
{
	get_history(PREV);
}

void
forward_history(key, ptr)
	u_int	key;
	u_char	*ptr;
{
	get_history(NEXT);
}

void
toggle_insert_mode(key, ptr)
	u_int	key;
	u_char	*ptr;
{
	set_var_value(INSERT_MODE_VAR, UP("TOGGLE"));
}

/*ARGSUSED*/
void
send_line(key, ptr)
	u_int	key;
	u_char	*ptr;
{
	int	server;
	WaitPrompt	*OldPrompt;

	server = from_server;
	from_server = get_window_server(0);
	reset_hold((Window *) 0);
	hold_mode((Window *) 0, OFF, 1);
	if (current_screen->promptlist && current_screen->promptlist->type == WAIT_PROMPT_LINE)
	{
		OldPrompt = current_screen->promptlist;
		(*OldPrompt->func)(OldPrompt->data, get_input());
		set_input(empty_string);
		current_screen->promptlist = OldPrompt->next;
		new_free(&OldPrompt->data);
		new_free(&OldPrompt->prompt);
		new_free(&OldPrompt);
		change_input_prompt(-1);
	}
	else
	{
		u_char	*line,
			*tmp = NULL;

		line = get_input();
		malloc_strcpy(&tmp, line);

		if (do_hook(INPUT_LIST, "%s", tmp))
		{
			if (get_int_var(INPUT_ALIASES_VAR))
				parse_line(NULL, tmp, empty_string,
					1, 0, 0);
			else
				parse_line(NULL, tmp, NULL,
					1, 0, 0);
		}
		update_input(UPDATE_ALL);
		new_free(&tmp);
	}
	from_server = server;
}

/* The SENDLINE command.. */
static	void
sendlinecmd(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	int	server;
	int	display;

	server = from_server;
	display = window_display;
	window_display = 1;
	if (get_int_var(INPUT_ALIASES_VAR))
		parse_line(NULL, args, empty_string, 1, 0, 0);
	else
		parse_line(NULL, args, NULL, 1, 0, 0);
	update_input(UPDATE_ALL);
	window_display = display;
	from_server = server;
}

/*ARGSUSED*/
void
meta8_char(key, ptr)
	u_int	key;
	u_char	*ptr;
{
	current_screen->meta8_hit = 1;
}

/*ARGSUSED*/
void
meta7_char(key, ptr)
	u_int	key;
	u_char	*ptr;
{
	current_screen->meta7_hit = 1;
}

/*ARGSUSED*/
void
meta6_char(key, ptr)
	u_int	key;
	u_char	*ptr;
{
	current_screen->meta6_hit = 1;
}

/*ARGSUSED*/
void
meta5_char(key, ptr)
	u_int	key;
	u_char	*ptr;
{
	current_screen->meta5_hit = 1;
}

/*ARGSUSED*/
void
meta4_char(key, ptr)
	u_int	key;
	u_char	*ptr;
{
	current_screen->meta4_hit = 1 - current_screen->meta4_hit;
}

/*ARGSUSED*/
void
meta3_char(key, ptr)
	u_int	key;
	u_char	*ptr;
{
	current_screen->meta3_hit = 1;
}

/*ARGSUSED*/
void
meta2_char(key, ptr)
	u_int	key;
	u_char	*ptr;
{
	current_screen->meta2_hit = 1;
}

/*ARGSUSED*/
void
meta1_char(key, ptr)
	u_int	key;
	u_char	*ptr;
{
	current_screen->meta1_hit = 1;
}

void
quote_char(key, ptr)
	u_int	key;
	u_char	*ptr;
{
	current_screen->quote_hit = 1;
}

/* type_text: the BIND function TYPE_TEXT */
/*ARGSUSED*/
void
type_text(key, ptr)
	u_int	key;
	u_char	*ptr;
{
	for (; *ptr; ptr++)
		input_add_character((u_int)*ptr, (u_char *) 0);
}

/*
 * irc_clear_screen: the CLEAR_SCREEN function for BIND.  Clears the screen and
 * starts it if it is held 
 */
/*ARGSUSED*/
void
irc_clear_screen(key, ptr)
	u_int	key;
	u_char	*ptr;
{
	hold_mode((Window *) 0, OFF, 1);
	my_clear(NULL, empty_string, empty_string);
}

/* parse_text: the bindable function that executes its string */
void
parse_text(key, ptr)
	u_int	key;
	u_char	*ptr;
{
	parse_line(NULL, ptr, empty_string, 0, 0, 0);
}

/*
 * edit_char: handles each character for an input stream.  Not too difficult
 * to work out.
 */
void
edit_char(ikey)
	u_int ikey;
{
	void	(*func)(u_int, u_char *);
	u_char	*str;
	u_char	extended_key, key = (u_char)ikey;
	WaitPrompt *oldprompt;

	if (current_screen->promptlist &&
			current_screen->promptlist->type == WAIT_PROMPT_KEY)
	{
		oldprompt = current_screen->promptlist;
		(*oldprompt->func)(oldprompt->data, (u_char *)&key);
		set_input(empty_string);
		current_screen->promptlist = oldprompt->next;
		new_free(&oldprompt->data);
		new_free(&oldprompt->prompt);
		new_free(&oldprompt);
		change_input_prompt(-1);
		return;
	}
	if (!get_int_var(EIGHT_BIT_CHARACTERS_VAR))
		key &= 0x7F;			/* strip to 7-bitness */

	extended_key = key;

	if (current_screen->meta1_hit)
	{
		func = key_names[meta1_keys[key].index].func;
		str = meta1_keys[key].stuff;
		current_screen->meta1_hit = 0;
	}
	else if (current_screen->meta2_hit)
	{
		func = key_names[meta2_keys[key].index].func;
		str = meta2_keys[key].stuff;
		current_screen->meta2_hit = 0;
	}
	else if (current_screen->meta3_hit)
	{
		func = key_names[meta3_keys[key].index].func;
		str = meta3_keys[key].stuff;
		current_screen->meta3_hit = 0;
	}
	else if (current_screen->meta4_hit)
	{
		func = key_names[meta4_keys[key].index].func;
		str = meta4_keys[key].stuff;
	}
	else if (current_screen->meta5_hit)
	{
		func = key_names[meta5_keys[key].index].func;
		str = meta5_keys[key].stuff;
		current_screen->meta5_hit = 0;
	}
	else if (current_screen->meta6_hit)
	{
		func = key_names[meta6_keys[key].index].func;
		str = meta6_keys[key].stuff;
		current_screen->meta6_hit = 0;
	}
	else if (current_screen->meta7_hit)
	{
		func = key_names[meta7_keys[key].index].func;
		str = meta7_keys[key].stuff;
		current_screen->meta7_hit = 0;
	}
	else if (current_screen->meta8_hit)
	{
		func = key_names[meta8_keys[key].index].func;
		str = meta8_keys[key].stuff;
		current_screen->meta8_hit = 0;
	}
	else
	{
		func = key_names[keys[key].index].func;
		str = keys[key].stuff;
	}
	if (!current_screen->meta1_hit && !current_screen->meta2_hit &&
	    !current_screen->meta3_hit && !current_screen->meta5_hit &&
	    !current_screen->meta6_hit && !current_screen->meta7_hit &&
	    !current_screen->meta8_hit)
	{
		if (current_screen->inside_menu == 1)
			menu_key((u_int)key);
		else if (current_screen->digraph_hit)
		{
			if (extended_key == 0x08 || extended_key == 0x7f)
				current_screen->digraph_hit = 0;
			else if (current_screen->digraph_hit == 1)
			{
				current_screen->digraph_first = extended_key;
				current_screen->digraph_hit = 2;
			}
			else if (current_screen->digraph_hit == 2)
			{
				if ((extended_key =
				    get_digraph((u_int)extended_key)) != '\0')
					input_add_character((u_int)extended_key,
					    (u_char *) 0);
				else
					term_beep();
			}
		}
		else if (current_screen->quote_hit)
		{
			current_screen->quote_hit = 0;
			input_add_character((u_int)extended_key, (u_char *) 0);
		}
		else if (func)
			func(extended_key, str ? str : empty_string);
	}
	else
		term_beep();
}

/*ARGSUSED*/
static	void
catter(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char *target = next_arg(args, &args);

	if (target && args && *args)
	{
		u_char *text = args;
		FILE *fp = fopen(CP(target), "r+");

		if (!fp)
		{
			fp = fopen(CP(target), "w");
			if (!fp)
			{
				say("CAT: error: '%s': %s", target, strerror(errno));
				return;
		}	}
		
		fseek(fp, 0, SEEK_END);
		fprintf(fp, "%s\n", text),
		fclose(fp);
	}
	else
		say("Usage: /CAT <destfile> <line>");
}


/*ARGSUSED*/
static	void
cd(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	lbuf[BIG_BUFFER_SIZE];
	u_char	*arg,
		*expand;

#ifdef DAEMON_UID
	if (getuid() == DAEMON_UID)
	{
		say("You are not permitted to use this command");
		return;
	}
#endif /* DAEMON_UID */
	if ((arg = next_arg(args, &args)) != NULL)
	{
		if ((expand = expand_twiddle(arg)) != NULL)
		{
			if (chdir(CP(expand)))
				say("CD: %s", strerror(errno));
			new_free(&expand);
		}
		else
			say("CD: No such user");
	}
	getcwd(CP(lbuf), sizeof(lbuf));
	say("Current directory: %s", lbuf);
}

static	void
send_action(target, text)
	u_char	*target, *text;
{
	if (get_server_version(from_server) == ServerICB)
		icb_put_action(target, text);
	else
		send_ctcp(ctcp_type[CTCP_PRIVMSG], target, UP("ACTION"), "%s", text);
}

#ifdef LYNX_STUFF
static	u_char	*
prepare_action(string)
	u_char	*string;
{
	short	last;
	u_char	*message;

	last = my_strlen(string) - 1;
	while(string[last] == ' ')
		if (--last < 0) return NULL;

	if ((string[last] > 'a' && string[last] < 'z') ||
			(string[last] > 'A' && string[last] < 'Z'))
	{
		message = new_malloc(last + 2);
		my_strmcpy(message, string, last+1);
		message[last + 1] = '.';
		message[last + 2] = '\0';
		return message;
	}
	else
		return NULL;
}
#endif /* LYNX_STUFF */

static	void
describe(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*target;

	target = next_arg(args, &args);
	if (target && args && *args)
	{
		int	old, from_level;
#ifdef LYNX_STUFF
		u_char	*result;
#endif /* LYNX_STUFF */
		u_char	*message;

#ifdef LYNX_STUFF
		if (result = prepare_action(args))
			message = result;
		else
#endif /* LYNX_STUFF */
			message = args;

		old = set_lastlog_msg_level(LOG_ACTION);
		save_message_from();
		from_level = message_from_level(LOG_ACTION);
		send_action(target, message);
		if (do_hook(SEND_ACTION_LIST, "%s %s", target, message))
			put_it("* -> %s: %s %s", target,
				get_server_nickname(from_server), message);
		set_lastlog_msg_level(old);
		restore_message_from();

#ifdef LYNX_STUFF
		if (result)
			new_free(&result);
#endif /* LYNX_STUFF */
	}
	else
		say("Usage: /DESCRIBE <target> <action description>");
}

/*
 * New 'me' command - now automatically appends period.
 * Necessary for new 'action' script.   -lynx'92
 * Hardly, removed this as it was generally considered offensive
 */
static	void
me(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	if (args && *args)
	{
		u_char	*target;

		if ((target = get_target_by_refnum(0)) != NULL)
		{
			int	old;
#ifdef LYNX_STUFF
			u_char	*result;
#endif /* LYNX_STUFF */
			u_char	*message;

			/* handle "/ foo" */
			if (!my_strncmp(target, get_string_var(CMDCHARS_VAR), 1) &&
			    (!(target = get_channel_by_refnum(0))))
			{
				say("No target, neither channel nor query");
				return;
			}
#ifdef LYNX_STUFF
			if (result = prepare_action(args))
				message = result;
			else
#endif /* LYNX_STUFF */

				message = args;

			old = set_lastlog_msg_level(LOG_ACTION);
			save_message_from();
			message_from(target, LOG_ACTION);
			send_action(target, message);
			if (do_hook(SEND_ACTION_LIST, "%s %s", target, message))
				put_it("* %s %s",
				    get_server_nickname(from_server), message);
			set_lastlog_msg_level(old);
			restore_message_from();

#ifdef LYNX_STUFF
			if (result)
				new_free(&result);
#endif /* LYNX_STUFF */
		}
		else
			say("No target, neither channel nor query");
	}
	else
		say("Usage: /ME <action description>");
}

static	void
mload(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*file;

	while ((file = next_arg(args, &args)) != NULL)
		load_menu(file);
}

static	void
mlist(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*menu;

	while ((menu = new_next_arg(args, &args)) != NULL)
		(void) ShowMenu(menu);
}

static	void
evalcmd(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	parse_line(NULL, args, subargs ? subargs : empty_string, 0, 0, 0);
}

/*
 * execute_timer:  checks to see if any currently pending timers have
 * gone off, and if so, execute them, delete them, etc, setting the
 * current_exec_timer, so that we can't remove the timer while its
 * still executing.
 */
extern	void
execute_timer()
{
	struct timeval current;
	TimerList *next;
	int	old_in_on_who,
		old_server = from_server;
	
	gettimeofday(&current, NULL);

	while (PendingTimers &&
	          (PendingTimers->time < current.tv_sec
	        || (PendingTimers->time == current.tv_sec
	        &&  PendingTimers->microseconds <= current.tv_usec)))
	{
		old_in_on_who = in_on_who;
		in_on_who = PendingTimers->in_on_who;
		current_exec_timer = PendingTimers->ref;
		save_message_from();
		message_from((u_char *) 0, LOG_CRAP);
		if (PendingTimers->server >= 0)
			from_server = PendingTimers->server;
		parse_command(PendingTimers->command, 0, empty_string);
		from_server = old_server;
		restore_message_from();
		current_exec_timer = -1;
		new_free(&PendingTimers->command);
		next = PendingTimers->next;
		new_free(&PendingTimers);
		PendingTimers = next;
		in_on_who = old_in_on_who;
	}
}

/*
 * timercmd: the bit that handles the TIMER command.  If there are no
 * arguements, then just list the currently pending timers, if we are
 * give a -DELETE flag, attempt to delete the timer from the list.  Else
 * consider it to be a timer to add, and add it.
 */
static	void
timercmd(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*waittime, *flag;
	struct	timeval timertime;
	long	waitsec, waitusec;
	TimerList **slot,
		  *ntimer;
	int	want = -1,
		refnum;

	if (*args == '-')
	{
		size_t	len;

		flag = next_arg(args, &args);
		len = my_strlen(flag);
		upper(flag);

		/* first check for the -DELETE flag */

		if (!my_strncmp(flag, "-DELETE", len))
		{
			u_char	*ptr;
			int	ref;
			TimerList	*tmp,
					*prev;

			if (current_exec_timer != -1)
			{
				say("You may not remove a TIMER from itself");
				return;
			}
			if (!(ptr = next_arg(args, &args)))
			{
				say("%s: Need a timer reference number for -DELETE", command);
				return;
			}
			ref = my_atoi(ptr);
			for (prev = tmp = PendingTimers; tmp; prev = tmp,
					tmp = tmp->next)
			{
				if (tmp->ref == ref)
				{
					if (tmp == prev)
						PendingTimers =
							PendingTimers->next;
					else
						prev->next = tmp->next;
					new_free(&tmp->command);
					new_free(&tmp);
					return;
				}
			}
			say("%s: Can't delete %d, no such refnum",
				command, ref);
			return;
		}
		else if (!my_strncmp(flag, "-REFNUM", len))
		{
			u_char	*ptr;

			ptr = next_arg(args, &args);
			want = my_atoi(ptr);
			if (want < 0)
			{
				say("%s: Illegal refnum %d", command, want);
				return;
			}
		}
		else
		{
			say("%s: %s no such flag", command, flag);
			return;
		}
	}

	/* else check to see if we have no args -> list */

	if (!(waittime = next_arg(args, &args)))
	{
		show_timer(command);
		return;
	}

	/* must be something to add */

	if ((refnum = create_timer_ref(want)) == -1)
	{
		say("%s: Refnum %d already exists", command, want);
		return;
	}
	
	waitusec = waitsec = 0;
	while (isdigit(*waittime))
		waitsec = waitsec*10 + ((*waittime++) - '0');
	if (*waittime == '.')
	{
		long decimalmul = 100000;
		for(; isdigit(*++waittime); decimalmul /= 10)
			waitusec += (*waittime - '0') * decimalmul;
	}
	
	gettimeofday(&timertime, NULL);	
	timertime.tv_sec += waitsec;
	timertime.tv_usec+= waitusec;
	timertime.tv_sec += (timertime.tv_usec/1000000);
	timertime.tv_usec %= 1000000;
	
	ntimer = (TimerList *) new_malloc(sizeof(TimerList));
	ntimer->in_on_who = in_on_who;
	ntimer->time = timertime.tv_sec;
	ntimer->microseconds = timertime.tv_usec;
	ntimer->server = from_server;
	ntimer->ref = refnum;
	ntimer->command = NULL;
	malloc_strcpy(&ntimer->command, args);

	/* we've created it, now put it in order */

	for (slot = &PendingTimers; *slot; slot = &(*slot)->next)
	{
		if ((*slot)->time > ntimer->time ||
		    ((*slot)->time == ntimer->time &&
		     (*slot)->microseconds > ntimer->microseconds))
			break;
	}
	ntimer->next = *slot;
	*slot = ntimer;
}

/*
 * show_timer:  Display a list of all the TIMER commands that are
 * pending to be executed.
 */
static	void
show_timer(command)
	u_char	*command;
{
	u_char  lbuf[BIG_BUFFER_SIZE];
	TimerList *tmp;
	struct timeval current, time_left;

	if (!PendingTimers)
	{
		say("%s: No commands pending to be executed", command);
		return;
	}

	gettimeofday(&current, NULL);
	say("Timer Seconds      Command");
	for (tmp = PendingTimers; tmp; tmp = tmp->next)
	{
		time_left.tv_sec = tmp->time;
		time_left.tv_usec = tmp->microseconds;
		time_left.tv_sec -= current.tv_sec;

		if (time_left.tv_usec >= current.tv_usec)
			time_left.tv_usec -= current.tv_usec;
		else
		{
			time_left.tv_usec = time_left.tv_usec -
			    current.tv_usec + 1000000;
			time_left.tv_sec--;
		}

		snprintf(CP(lbuf), sizeof(lbuf), "%ld.%06d",
		    (long)time_left.tv_sec, (int)time_left.tv_usec);
		say("%-5d %-12s %s", tmp->ref, lbuf, tmp->command);
	}
}

/*
 * create_timer_ref:  returns the lowest unused reference number for
 * a timer
 */
static	int
create_timer_ref(want)
	int	want;
{
	TimerList	*tmp;
	int	ref = 0;
	int	done = 0;

	if (want == -1)
		while (!done)
		{
			done = 1;
			for (tmp = PendingTimers; tmp; tmp = tmp->next)
				if (ref == tmp->ref)
				{
					ref++;
					done = 0;
					break;
				}
		}
	else
	{
		ref = want;
		for (tmp = PendingTimers; tmp; tmp = tmp->next)
			if (ref == tmp->ref)
			{
				ref = -1;
				break;
			}
	}

	return (ref);
}

/*
 * inputcmd:  the INPUT command.   Takes a couple of arguements...
 * the first surrounded in double quotes, and the rest makes up
 * a normal ircII command.  The command is evalutated, with $*
 * being the line that you input.  Used add_wait_prompt() to prompt
 * the user...  -phone, jan 1993.
 */

static	void
inputcmd(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*prompt;

	if (!args || !*args)
		return;
	
	if (*args++ != '"')
	{
		say("Need \" to begin prompt for INPUT");
		return;
	}

	prompt = args;
	if ((args = my_index(prompt, '"')) != NULL)
		*args++ = '\0';
	else
	{
		say("Missing \" in INPUT");
		return;
	}

	for (; *args == ' '; args++)
		;

	add_wait_prompt(prompt, eval_inputlist, args, WAIT_PROMPT_LINE);
}

/*
 * eval_inputlist:  Cute little wrapper that calls parse_line() when we
 * get an input prompt ..
 */

void
eval_inputlist(args, line)
	u_char	*args,
		*line;
{
	parse_line(NULL, args, line ? line : empty_string, 0, 0, 0);
}

/* pingcmd: ctcp ping, duh - phone, jan 1993. */
static	void
pingcmd(command, args, subargs)
	u_char    *command,
		*args,
		*subargs;
{
	u_char	buffer[BIG_BUFFER_SIZE];

	snprintf(CP(buffer), sizeof buffer, "%s PING %ld", args, (long)time(NULL));
	ctcp(command, buffer, empty_string);
}

static	void
xtypecmd(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*arg;
	size_t	len;

	if (args && *args == '-')
	{
		args++;
		if ((arg = next_arg(args, &args)) != NULL)
		{
			len = my_strlen(arg);
			if (!my_strnicmp(arg, UP("LITERAL"), len))
			{
				for (; *args; args++)
					input_add_character((u_int)*args, (u_char *) 0);
			}
#ifdef _Windows
			else if (!my_strnicmp(arg, UP("REPLACE"), len))
			{
				set_input(args);
				term_resetall();
			}
#endif /* _Windows */
			else
				say ("Unknown flag -%s to XTYPE", arg);
			return;
		}
		input_add_character('-', (u_char *) 0);
	}
	else
		typecmd(command, args, empty_string);
	return;
}

static	void
beepcmd(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	term_beep();
}

#ifdef HAVE_SETENV
static  void   
irc_setenv(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	u_char	*arg;

	if (args && *args && (arg = next_arg(args, &args)) != NULL)
	{
#define SPECIAL_TZ_HACK
#ifdef SPECIAL_TZ_HACK
		/*
		 * XXX
		 * special hack for $TZ to try to stop memory leaks..
		 *
		 * special thanks (heh) to simonb for this idea...
		 */
		int is_tz;

		is_tz = arg[0] == 'T' && arg[1] == 'V' && arg[0] == '\0';
		if (is_tz)
		{
			u_char *otz = UP(getenv("TZ"));
			static size_t tzlen = -1;
			size_t ntzlen = my_strlen(args);

			if (otz)
			{
				size_t otzlen = my_strlen(otz);

				if (tzlen == -1)
					tzlen = otzlen;
				if (otzlen > tzlen)
					say("--- weird, irc_setenv, otzlen > tzlen");

				if (ntzlen > tzlen)
					tzlen = -1;
				else
				{
					my_strncpy(otz, args, otzlen - 1);
					otz[otzlen - 1] = 0;
				}
			}
			if (tzlen == -1)
			{
				setenv(CP(arg), CP(args), 1);
				tzlen = ntzlen;
			}
		}
		else
#endif /* SPECIAL_TZ_HACK */
			setenv(CP(arg), CP(args), 1);
#ifdef HAVE_TZSET
# ifdef SPECIAL_TZ_HACK
		if (is_tz)
# endif /* SPECIAL_TZ_HACK */
			tzset();
#endif /* HAVE_TZSET */
	}
}
#endif

#ifdef HAVE_UNSETENV
static  void   
irc_unsetenv(command, args, subargs)
	u_char	*command,
		*args,
		*subargs;
{
	if (args && *args);
	{
		unsetenv(CP(args));
#ifdef HAVE_TZSET
		if (args[0] == 'T' && args[1] == 'V' && args[0] == '\0')
			tzset();
#endif /* HAVE_TZSET */
	}
}
#endif


syntax highlighted by Code2HTML, v. 0.9.1