/
rogue25b1/
rogue25b1/space/planets/
rogue25b1/space/prototypes/
rogue25b1/space/ships/
/***************************************************************************\
[*]    ___    ____   ____   __   __  ____ [*]   ROGUE: ROM With Attitude  [*]
[*]   /#/ )  /#/  ) /#/  ) /#/  /#/ /#/   [*]    All rights reserved      [*]
[*]  /#/ <  /#/  / /#/ _  /#/  /#/ /#/--  [*]   Copyright(C) 2000-2001    [*]
[*] /#/   \(#(__/ (#(__/ (#(__/#/ (#(___  [*] Kenneth Conley (Mendanbar)  [*]
[*]  Expression of Digital Creativity..   [*]  scmud@mad.scientist.com    [*]
[-]---------------------------------------+-+-----------------------------[-]
[*] File: comm.c							  [*]
[*] Usage: nanny ;)							  [*]
\***************************************************************************/

/***************************************************************************
 *  Original Diku Mud copyright (C) 1990, 1991 by Sebastian Hammer,        *
 *  Michael Seifert, Hans Henrik St{rfeldt, Tom Madsen, and Katja Nyboe.   *
 *                                                                         *
 *  Merc Diku Mud improvments copyright (C) 1992, 1993 by Michael          *
 *  Chastain, Michael Quan, and Mitchell Tse.                              *
 *                                                                         *
 *  In order to use any part of this Merc Diku Mud, you must comply with   *
 *  both the original Diku license in 'license.doc' as well the Merc       *
 *  license in 'license.txt'.  In particular, you may not remove either of *
 *  these copyright notices.                                               *
 *                                                                         *
 *  Thanks to abaddon for proof-reading our comm.c and pointing out bugs.  *
 *  Any remaining bugs are, of course, our work, not his.  :)              *
 *                                                                         *
 *  Much time and thought has gone into this software and you are          *
 *  benefitting.  We hope that you share your changes too.  What goes      *
 *  around, comes around.                                                  *
 ***************************************************************************/

/***************************************************************************
*	ROM 2.4 is copyright 1993-1998 Russ Taylor			   *
*	ROM has been brought to you by the ROM consortium		   *
*	    Russ Taylor (rtaylor@hypercube.org)				   *
*	    Gabrielle Taylor (gtaylor@hypercube.org)			   *
*	    Brian Moore (zump@rom.org)					   *
*	By using this code, you have agreed to follow the terms of the	   *
*	ROM license, in the file Rom24/doc/rom.license			   *
***************************************************************************/

/*
 * This file contains all of the OS-dependent stuff:
 *   startup, signals, BSD sockets for tcp/ip, i/o, timing.
 *
 * The data flow for input is:
 *    Game_loop ---> Read_from_descriptor ---> Read
 *    Game_loop ---> Read_from_buffer
 *
 * The data flow for output is:
 *    Game_loop ---> Process_Output ---> Write_to_descriptor -> Write
 *
 * The OS-dependent functions are Read_from_descriptor and Write_to_descriptor.
 * -- Furey  26 Jan 1993
 */


#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/signal.h>
#include <sys/resource.h>
#include <errno.h>
#include <stdarg.h>

#include "merc.h"
#include "olc.h"
#include "interp.h"
#include "lookup.h"
#include "recycle.h"
#include "tables.h"
#include "pueblo.h"
#include "clientopt.h"

/*
 * Malloc debugging stuff.
 */
#if defined(sun)
#undef MALLOC_DEBUG
#endif

#if defined(MALLOC_DEBUG)
#include <malloc.h>
extern	int	malloc_debug	args( ( int  ) );
extern	int	malloc_verify	args( ( void ) );
#endif


extern	char *	MENU;
extern	char *	WELC_MESSG;

// constants
extern	SInt32	xp_table	[];
extern	char *	ability_type	[];
extern	char *	align_names	[];
extern	char *	body_type	[];
extern	char *	facial_style	[];
extern	char *	eye_color	[];
extern	char *	skin_color	[];
extern	char *	hair_color	[];
extern	char *	hair_length	[];
extern	char *	hair_type	[];

void roll_temp_abils(CHAR_DATA *ch);

/*
 * Signal handling.
 * Apollo has a problem with __attribute(atomic) in signal.h,
 *   I dance around it.
 */
#if defined(apollo)
#define __attribute(x)
#endif

#if defined(unix)
#include <signal.h>
#endif

#if defined(apollo)
#undef __attribute
#endif



/*
 * Socket and TCP/IP stuff.
 */
#if	defined(macintosh) || defined(MSDOS)
const	char	echo_off_str	[] = { '\0' };
const	char	echo_on_str	[] = { '\0' };
const	char 	go_ahead_str	[] = { '\0' };
#endif

#if	defined(unix)
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include "telnet.h"

const	char	echo_off_str	[] = { IAC, WILL, TELOPT_ECHO, '\0' };
const	char	echo_on_str	[] = { IAC, WONT, TELOPT_ECHO, '\0' };
const	char 	go_ahead_str	[] = { IAC, GA, '\0' };
#endif



/*
 * OS-dependent declarations.
 */
#if	defined(_AIX)
#include <sys/select.h>
void	bzero		args( ( char *b, int length ) );
int	getpeername	args( ( int s, struct sockaddr *name, int *namelen ) );
int	getsockname	args( ( int s, struct sockaddr *name, int *namelen ) );
int	gettimeofday	args( ( struct timeval *tp, struct timezone *tzp ) );
int	listen		args( ( int s, int backlog ) );
int	setsockopt	args( ( int s, int level, int optname, void *optval,
			    int optlen ) );
int	socket		args( ( int domain, int type, int protocol ) );
#endif

#if	defined(apollo)
#include <unistd.h>
void	bzero		args( ( char *b, int length ) );
#endif

#if	defined(__hpux)
int	accept		args( ( int s, void *addr, int *addrlen ) );
int	bind		args( ( int s, const void *addr, int addrlen ) );
void	bzero		args( ( char *b, int length ) );
int	getpeername	args( ( int s, void *addr, int *addrlen ) );
int	getsockname	args( ( int s, void *name, int *addrlen ) );
int	gettimeofday	args( ( struct timeval *tp, struct timezone *tzp ) );
int	listen		args( ( int s, int backlog ) );
int	setsockopt	args( ( int s, int level, int optname,
 				const void *optval, int optlen ) );
int	socket		args( ( int domain, int type, int protocol ) );
#endif

#if	defined(interactive)
#include <net/errno.h>
#include <sys/fnctl.h>
#endif

#if	defined(linux)
/* 
    Linux shouldn't need these. If you have a problem compiling, try
    uncommenting these functions.
*/
/*
int	accept		args( ( int s, struct sockaddr *addr, int *addrlen ) );
int	bind		args( ( int s, struct sockaddr *name, int namelen ) );
int	getpeername	args( ( int s, struct sockaddr *name, int *namelen ) );
int	getsockname	args( ( int s, struct sockaddr *name, int *namelen ) );
int	listen		args( ( int s, int backlog ) );
*/

int	close		args( ( int fd ) );
int	gettimeofday	args( ( struct timeval *tp, struct timezone *tzp ) );

int	select		args( ( int width, fd_set *readfds, fd_set *writefds,
			    fd_set *exceptfds, struct timeval *timeout ) );
int	socket		args( ( int domain, int type, int protocol ) );
#endif

#if	defined(macintosh)
#include <console.h>
#include <fcntl.h>
#include <unix.h>
struct	timeval {
	time_t	tv_sec;
	time_t	tv_usec;
};
#if	!defined(isascii)
#define	isascii(c)		( (c) < 0200 )
#endif
static	long			theKeys	[4];

int	gettimeofday		args( ( struct timeval *tp, void *tzp ) );
#endif

#if	defined(MIPS_OS)
extern	int		errno;
#endif

#if	defined(MSDOS)
int	gettimeofday	args( ( struct timeval *tp, void *tzp ) );
int	kbhit		args( ( void ) );
#endif

#if	defined(NeXT)
int	close		args( ( int fd ) );
int	fcntl		args( ( int fd, int cmd, int arg ) );
#if	!defined(htons)
u_short	htons		args( ( u_short hostshort ) );
#endif
#if	!defined(ntohl)
u_long	ntohl		args( ( u_long hostlong ) );
#endif
int	read		args( ( int fd, char *buf, int nbyte ) );
int	select		args( ( int width, fd_set *readfds, fd_set *writefds,
			    fd_set *exceptfds, struct timeval *timeout ) );
int	write		args( ( int fd, char *buf, int nbyte ) );
#endif

#if	defined(sequent)
int	accept		args( ( int s, struct sockaddr *addr, int *addrlen ) );
int	bind		args( ( int s, struct sockaddr *name, int namelen ) );
int	close		args( ( int fd ) );
int	fcntl		args( ( int fd, int cmd, int arg ) );
int	getpeername	args( ( int s, struct sockaddr *name, int *namelen ) );
int	getsockname	args( ( int s, struct sockaddr *name, int *namelen ) );
int	gettimeofday	args( ( struct timeval *tp, struct timezone *tzp ) );
#if	!defined(htons)
u_short	htons		args( ( u_short hostshort ) );
#endif
int	listen		args( ( int s, int backlog ) );
#if	!defined(ntohl)
u_long	ntohl		args( ( u_long hostlong ) );
#endif
int	read		args( ( int fd, char *buf, int nbyte ) );
int	select		args( ( int width, fd_set *readfds, fd_set *writefds,
			    fd_set *exceptfds, struct timeval *timeout ) );
int	setsockopt	args( ( int s, int level, int optname, caddr_t optval,
			    int optlen ) );
int	socket		args( ( int domain, int type, int protocol ) );
int	write		args( ( int fd, char *buf, int nbyte ) );
#endif

/* This includes Solaris Sys V as well */
#if defined(sun)
int	accept		args( ( int s, struct sockaddr *addr, int *addrlen ) );
int	bind		args( ( int s, struct sockaddr *name, int namelen ) );
void	bzero		args( ( char *b, int length ) );
int	close		args( ( int fd ) );
int	getpeername	args( ( int s, struct sockaddr *name, int *namelen ) );
int	getsockname	args( ( int s, struct sockaddr *name, int *namelen ) );
int	listen		args( ( int s, int backlog ) );
int	read		args( ( int fd, char *buf, int nbyte ) );
int	select		args( ( int width, fd_set *readfds, fd_set *writefds,
			    fd_set *exceptfds, struct timeval *timeout ) );

#if !defined(__SVR4)
int	gettimeofday	args( ( struct timeval *tp, struct timezone *tzp ) );

#if defined(SYSV)
int setsockopt		args( ( int s, int level, int optname,
			    const char *optval, int optlen ) );
#else
int	setsockopt	args( ( int s, int level, int optname, void *optval,
			    int optlen ) );
#endif
#endif
int	socket		args( ( int domain, int type, int protocol ) );
int	write		args( ( int fd, char *buf, int nbyte ) );
#endif

#if defined(ultrix)
int	accept		args( ( int s, struct sockaddr *addr, int *addrlen ) );
int	bind		args( ( int s, struct sockaddr *name, int namelen ) );
void	bzero		args( ( char *b, int length ) );
int	close		args( ( int fd ) );
int	getpeername	args( ( int s, struct sockaddr *name, int *namelen ) );
int	getsockname	args( ( int s, struct sockaddr *name, int *namelen ) );
int	gettimeofday	args( ( struct timeval *tp, struct timezone *tzp ) );
int	listen		args( ( int s, int backlog ) );
int	read		args( ( int fd, char *buf, int nbyte ) );
int	select		args( ( int width, fd_set *readfds, fd_set *writefds,
			    fd_set *exceptfds, struct timeval *timeout ) );
int	setsockopt	args( ( int s, int level, int optname, void *optval,
			    int optlen ) );
int	socket		args( ( int domain, int type, int protocol ) );
int	write		args( ( int fd, char *buf, int nbyte ) );
#endif



/*
 * Global variables.
 */
DESCRIPTOR_DATA *   descriptor_list;	/* All open descriptors		*/
DESCRIPTOR_DATA *   d_next;		/* Next descriptor in loop	*/
FILE *		    fpReserve;		/* Reserved file handle		*/
bool		    god;		/* All new chars are gods!	*/
bool		    merc_down;		/* Shutdown			*/
bool		    wizlock;		/* Game is wizlocked		*/
bool		    newlock;		/* Game is newlocked		*/
char		    str_boot_time[MAX_INPUT_LENGTH];
time_t		    current_time;	/* time of this pulse */	
bool		    MOBtrigger = TRUE;  /* act() switch                 */

/*
 * OS-dependent local functions.
 */
#if defined(macintosh) || defined(MSDOS)
void	game_loop_mac_msdos	args( ( void ) );
bool	read_from_descriptor	args( ( DESCRIPTOR_DATA *d ) );
bool	write_to_descriptor	args( ( int desc, char *txt, int length ) );
#endif

#if defined(unix)
void	game_loop_unix		args( ( int control ) );
int	init_socket		args( ( int port ) );
void	init_descriptor		args( ( int control ) );
bool	read_from_descriptor	args( ( DESCRIPTOR_DATA *d ) );
bool	write_to_descriptor	args( ( DESCRIPTOR_DATA *desc, char *txt, int length ) );
bool	write_to_descriptor_2	args( ( int desc, char *txt, int length ) );
#endif




/*
 * Other local functions (OS-independent).
 */
bool	check_parse_name	args( ( char *name ) );
bool	check_reconnect		args( ( DESCRIPTOR_DATA *d, char *name,
				    bool fConn ) );
bool	check_playing		args( ( DESCRIPTOR_DATA *d, char *name ) );
int	main			args( ( int argc, char **argv ) );
void	nanny			args( ( DESCRIPTOR_DATA *d, char *argument ) );
bool	process_output		args( ( DESCRIPTOR_DATA *d, bool fPrompt ) );
void	read_from_buffer	args( ( DESCRIPTOR_DATA *d ) );
void	stop_idling		args( ( CHAR_DATA *ch ) );
void    bust_a_prompt           args( ( CHAR_DATA *ch ) );
void	do_start		args( ( CHAR_DATA *ch ) );
void	toggle_mxp		args( ( DESCRIPTOR_DATA *d ) );
void	init_signals		args( ( void ) );
void	crash_copyover		args( ( void ) );

int	port;
int	control;

/* externs */
extern int buffer_opt;


int main( int argc, char **argv ) {
    struct timeval now_time;
    bool fCopyOver = FALSE;

    /*
     * Memory debugging if needed.
     */
#if defined(MALLOC_DEBUG)
    malloc_debug( 2 );
#endif


    /*
     * Init time.
     */
    gettimeofday( &now_time, NULL );
    current_time 	= (time_t) now_time.tv_sec;
    strcpy( str_boot_time, ctime( &current_time ) );
    *(str_boot_time + strlen(str_boot_time)-1) = '\0';

    /*
     * Macintosh console initialization.
     */
#if defined(macintosh)
    console_options.nrows = 31;
    cshow( stdout );
    csetmode( C_RAW, stdin );
    cecho2file( "log file", 1, stderr );
#endif

    /*
     * Reserve one channel for our use.
     */
    if ( ( fpReserve = fopen( NULL_FILE, "r" ) ) == NULL )
    {
	perror( NULL_FILE );
	exit( 1 );
    }

    /*
     * Get the port number.
     */
    port = 3033;
    if ( argc > 1 )
    {
	if ( !is_number( argv[1] ))
	{
	    fprintf( stderr, "Usage: %s [port #]\n", argv[0] );
	    exit( 1 );
	}
	else if ( ( port = atoi( argv[1] ) ) <= 1024 )
	{
	    fprintf( stderr, "Port number must be above 1024.\n" );
	    exit( 1 );
	}
	
	/* Are we recovering from a copyover? */
 	if (argv[2] && argv[2][0]) {
 		fCopyOver = TRUE;
 		control = atoi(argv[3]);
 	} else
 		fCopyOver = FALSE;
	
    }

    /*
     * Run the game.
     */
#if defined(macintosh) || defined(MSDOS)
    boot_db();
    log_string("Rogue is ready to rock.");
    game_loop_mac_msdos( );
#endif

#if defined(unix)

    if (!fCopyOver)
	control = init_socket(port);

    init_signals();

    boot_db();
    sprintf( log_buf, "Rogue is ready to rock on port %d.", port );
    log_string( log_buf );

    if (fCopyOver)
	copyover_recover();
    
    game_loop_unix( control );
    close (control);
#endif

    /*
     * That's all, folks.
     */
    log_string( "Normal termination of game." );
    exit( 0 );
    return 0;
}

#if defined(unix)
int init_socket( int port )
{
    static struct sockaddr_in sa_zero;
    struct sockaddr_in sa;
    int x = 1;
    int fd;

    if ( ( fd = socket( AF_INET, SOCK_STREAM, 0 ) ) < 0 )
    {
	perror( "Init_socket: socket" );
	exit( 1 );
    }

    if ( setsockopt( fd, SOL_SOCKET, SO_REUSEADDR,
    (char *) &x, sizeof(x) ) < 0 )
    {
	perror( "Init_socket: SO_REUSEADDR" );
	close(fd);
	exit( 1 );
    }

#if defined(SO_DONTLINGER) && !defined(SYSV)
    {
	struct	linger	ld;

	ld.l_onoff  = 1;
	ld.l_linger = 1000;

	if ( setsockopt( fd, SOL_SOCKET, SO_DONTLINGER,
	(char *) &ld, sizeof(ld) ) < 0 )
	{
	    perror( "Init_socket: SO_DONTLINGER" );
	    close(fd);
	    exit( 1 );
	}
    }
#endif

    sa		    	= sa_zero;
    sa.sin_family   	= AF_INET;
    sa.sin_port	    	= htons( port );
#if defined(macintosh)
    sa.sin_addr.s_addr	= htonl(INADDR_ANY);
#else
    sa.sin_addr.s_addr	= htonl(INADDR_ANY);
//  sa.sin_addr.s_addr	= inet_addr("216.162.171.221");
#endif

    if ( bind( fd, (struct sockaddr *) &sa, sizeof(sa) ) < 0 )
    {
	perror("Init socket: bind" );
	close(fd);
	exit(1);
    }


    if ( listen( fd, 3 ) < 0 )
    {
	perror("Init socket: listen");
	close(fd);
	exit(1);
    }

    return fd;
}
#endif

#if defined(macintosh) || defined(MSDOS)
void game_loop_mac_msdos( void ) {
    struct timeval last_time;
    struct timeval now_time;
    static DESCRIPTOR_DATA dcon;

    gettimeofday( &last_time, NULL );
    current_time = (time_t) last_time.tv_sec;

    /*
     * New_descriptor analogue.
     */
    dcon.descriptor	= 0;
    dcon.connected	= CON_CHOOSE_TERM;
    dcon.host		= str_dup("localhost");
    dcon.outsize	= 2000;
    dcon.outbuf = (char *)alloc_mem(dcon.outsize);
    dcon.next		= descriptor_list;
    dcon.showstr_head	= NULL;
    dcon.showstr_point	= NULL;
    dcon.pEdit		= NULL;			/* OLC */
    dcon.pString	= NULL;			/* OLC */
    dcon.editor		= 0;			/* OLC */
    descriptor_list	= &dcon;

    /* Main loop */
    while ( !merc_down )
    {
	DESCRIPTOR_DATA *d;

	/*
	 * Process input.
	 */
	for ( d = descriptor_list; d != NULL; d = d_next )
	{
	    d_next	= d->next;
	    d->fcommand	= FALSE;

#if defined(MSDOS)
	    if ( kbhit( ) )
#endif
	    {
		if (d->character != NULL)
		    d->character->timer = 0;
		if (!read_from_descriptor(d))
		{
		    if (d->character != NULL && d->connected == CON_PLAYING)
			save_char_obj(d->character);
		    d->outtop	= 0;
		    close_socket( d );
		    continue;
		}
	    }

	    if (d->character != NULL && d->character->daze > 0)
		--d->character->daze;

	    if ( d->character != NULL && d->character->wait > 0 )
	    {
		--d->character->wait;
		continue;
	    }

	    read_from_buffer( d );
	    if ( d->incomm[0] != '\0' )
	    {
		d->fcommand	= TRUE;
		stop_idling( d->character );

	        /* OLC */
	        if ( d->showstr_point )
	            show_string( d, d->incomm );
	        else
	        if ( d->pString )
	            string_add( d->character, d->incomm );
	        else
	            switch ( d->connected )
	            {
	                case CON_PLAYING:
			    if ( !run_olc_editor( d ) )
				substitute_alias( d, d->incomm );
			    break;
	                default:
			    nanny( d, d->incomm );
			    break;
	            }

		d->incomm[0]	= '\0';
	    }
	}



	/*
	 * Autonomous game motion.
	 */
	update_handler( );

	/*
	 * Output.
	 */
	for ( d = descriptor_list; d != NULL; d = d_next )
	{
	    d_next = d->next;

	    if ( ( d->fcommand || d->outtop > 0 ) )
	    {
		if ( !process_output( d, TRUE ) )
		{
		    if ( d->character != NULL && d->connected == CON_PLAYING)
			save_char_obj( d->character );
		    d->outtop	= 0;
		    close_socket( d );
		}
	    }
	}



	/*
	 * Synchronize to a clock.
	 * Busy wait (blargh).
	 */
	now_time = last_time;
	for ( ; ; )
	{
	    int delta;

#if defined(MSDOS)
	    if ( kbhit( ) )
#endif
	    {
		if ( dcon.character != NULL )
		    dcon.character->timer = 0;
		if ( !read_from_descriptor( &dcon ) )
		{
		    if ( dcon.character != NULL && d->connected == CON_PLAYING)
			save_char_obj( d->character );
		    dcon.outtop	= 0;
		    close_socket( &dcon );
		}
#if defined(MSDOS)
		break;
#endif
	    }

	    gettimeofday( &now_time, NULL );
	    delta = ( now_time.tv_sec  - last_time.tv_sec  ) * 1000 * 1000
		  + ( now_time.tv_usec - last_time.tv_usec );
	    if ( delta >= 1000000 / PULSE_PER_SECOND )
		break;
	}
	last_time    = now_time;
	current_time = (time_t) last_time.tv_sec;
    }

    return;
}
#endif



#if defined(unix)
void game_loop_unix( int control ) {
    static struct timeval null_time;
    struct timeval last_time;

    signal( SIGPIPE, SIG_IGN );
    gettimeofday( &last_time, NULL );
    current_time = (time_t) last_time.tv_sec;

    /* Main loop */
    while ( !merc_down )
    {
	fd_set in_set;
	fd_set out_set;
	fd_set exc_set;
	DESCRIPTOR_DATA *d;
	int maxdesc;

#if defined(MALLOC_DEBUG)
	if ( malloc_verify( ) != 1 )
	    abort( );
#endif

	/*
	 * Poll all active descriptors.
	 */
	FD_ZERO( &in_set  );
	FD_ZERO( &out_set );
	FD_ZERO( &exc_set );
	FD_SET( control, &in_set );
	maxdesc	= control;
	for ( d = descriptor_list; d; d = d->next )
	{
	    maxdesc = UMAX( maxdesc, d->descriptor );
	    FD_SET( d->descriptor, &in_set  );
	    FD_SET( d->descriptor, &out_set );
	    FD_SET( d->descriptor, &exc_set );
	}

	if ( select( maxdesc+1, &in_set, &out_set, &exc_set, &null_time ) < 0 )
	{
	    perror( "Game_loop: select: poll" );
	    exit( 1 );
	}

	/*
	 * New connection?
	 */
	if (FD_ISSET(control, &in_set))
	    init_descriptor( control );

	/*
	 * Kick out the freaky folks.
	 */
	for ( d = descriptor_list; d != NULL; d = d_next )
	{
	    d_next = d->next;   
	    if ( FD_ISSET( d->descriptor, &exc_set ) )
	    {
		FD_CLR( d->descriptor, &in_set  );
		FD_CLR( d->descriptor, &out_set );
		if ( d->character && d->connected == CON_PLAYING)
		    save_char_obj( d->character );
		d->outtop	= 0;
		close_socket( d );
	    }
	}

	/* Kick out the freaky folks in CON_DISCONNECT state */
	for (d = descriptor_list; d != NULL; d = d_next) {
	    d_next = d->next;
	    if (STATE(d) == CON_DISCONNECT) {
		extract_char(d->character);
		close_socket(d);
	    }
	}

	/*
	 * Process input.
	 */
	for ( d = descriptor_list; d != NULL; d = d_next )
	{
	    d_next	= d->next;
	    d->fcommand	= FALSE;

	    if ( FD_ISSET( d->descriptor, &in_set ) )
	    {
		if ( d->character != NULL )
		    d->character->timer = 0;
		if ( !read_from_descriptor( d ) )
		{
		    FD_CLR( d->descriptor, &out_set );
		    if ( d->character != NULL && d->connected == CON_PLAYING)
			save_char_obj( d->character );
		    d->outtop	= 0;
		    close_socket( d );
		    continue;
		}
	    }

	    if (d->character != NULL && d->character->daze > 0)
		--d->character->daze;

	    if ( d->character != NULL && d->character->wait > 0 )
	    {
		--d->character->wait;
		continue;
	    }

	    read_from_buffer( d );
	    if ( d->incomm[0] != '\0' )
	    {
		d->fcommand	= TRUE;
		stop_idling( d->character );

	/* OLC */
	if ( d->showstr_point )
	    show_string( d, d->incomm );
	else
	if ( d->pString )
	    string_add( d->character, d->incomm );
	else
	    switch ( d->connected )
	    {
	        case CON_PLAYING:
		    if ( !run_olc_editor( d ) )
    		        substitute_alias( d, d->incomm );
		    break;
	        default:
		    nanny( d, d->incomm );
		    break;
	    }

		d->incomm[0]	= '\0';
	    }
	}



	/*
	 * Autonomous game motion.
	 */
	update_handler( );

	/*
	 * Output.
	 */
	for ( d = descriptor_list; d != NULL; d = d_next )
	{
	    d_next = d->next;

	    if ((d->fcommand || d->outtop > 0 || d->out_compress)
	    && FD_ISSET(d->descriptor, &out_set))
	    {
		bool ok = TRUE;

		if (d->fcommand || d->outtop > 0)
			ok = process_output(d, TRUE);

		if (ok && d->out_compress)
			ok = processCompressed(d);

		if (!ok)
		{
		    if ( d->character != NULL && d->connected == CON_PLAYING)
			save_char_obj( d->character );
		    d->outtop	= 0;
		    close_socket( d );
		}
	    }
	}



	/*
	 * Synchronize to a clock.
	 * Sleep( last_time + 1/PULSE_PER_SECOND - now ).
	 * Careful here of signed versus unsigned arithmetic.
	 */
	{
	    struct timeval now_time;
	    long secDelta;
	    long usecDelta;

	    gettimeofday( &now_time, NULL );
	    usecDelta	= ((int) last_time.tv_usec) - ((int) now_time.tv_usec)
			+ 1000000 / PULSE_PER_SECOND;
	    secDelta	= ((int) last_time.tv_sec ) - ((int) now_time.tv_sec );
	    while ( usecDelta < 0 )
	    {
		usecDelta += 1000000;
		secDelta  -= 1;
	    }

	    while ( usecDelta >= 1000000 )
	    {
		usecDelta -= 1000000;
		secDelta  += 1;
	    }

	    if ( secDelta > 0 || ( secDelta == 0 && usecDelta > 0 ) )
	    {
		struct timeval stall_time;

		stall_time.tv_usec = usecDelta;
		stall_time.tv_sec  = secDelta;
		if ( select( 0, NULL, NULL, NULL, &stall_time ) < 0 )
		{
		    perror( "Game_loop: select: stall" );
		    exit( 1 );
		}
	    }
	}

	gettimeofday( &last_time, NULL );
	current_time = (time_t) last_time.tv_sec;
    }

    return;
}
#endif



#if defined(unix)

void init_descriptor( int control ) {
    char buf[MAX_STRING_LENGTH];
    DESCRIPTOR_DATA *dnew;
    struct sockaddr_in sock;
    struct hostent *from;
    socket_t desc;
    socklen_t size;

    size = sizeof(sock);
    getsockname( control, (struct sockaddr *) &sock, &size );
    if ( ( desc = accept( control, (struct sockaddr *) &sock, &size) ) < 0 )
    {
	perror( "New_descriptor: accept" );
	return;
    }

#if !defined(FNDELAY)
#define FNDELAY O_NDELAY
#endif

    if ( fcntl( desc, F_SETFL, FNDELAY ) == -1 )
    {
	perror( "New_descriptor: fcntl: FNDELAY" );
	return;
    }

    /*
     * Cons a new descriptor.
     */
    dnew = new_descriptor(); /* new_descriptor now also allocates things*/
    dnew->descriptor = desc;

    size = sizeof(sock);
    if ( getpeername( desc, (struct sockaddr *) &sock, &size ) < 0 )
    {
	perror( "New_descriptor: getpeername" );
	dnew->host = str_dup( "(unknown)" );
    }
    else
    {
	/*
	 * Would be nice to use inet_ntoa here but it takes a struct arg,
	 * which ain't very compatible between gcc and system libraries.
	 */
	int addr;

	addr = ntohl( sock.sin_addr.s_addr );
	sprintf( buf, "%d.%d.%d.%d",
	    ( addr >> 24 ) & 0xFF, ( addr >> 16 ) & 0xFF,
	    ( addr >>  8 ) & 0xFF, ( addr       ) & 0xFF
	    );
	mudlogf(CMP, LVL_STAFF, TRUE, "Sock.sinaddr: %s", buf);
	from = gethostbyaddr( (char *) &sock.sin_addr,
	    sizeof(sock.sin_addr), AF_INET );
	dnew->host = str_dup( from ? from->h_name : buf );
    }
	
    /*
     * Swiftest: I added the following to ban sites.  I don't
     * endorse banning of sites, but Copper has few descriptors now
     * and some people from certain sites keep abusing access by
     * using automated 'autodialers' and leaving connections hanging.
     *
     * Furey: added suffix check by request of Nickel of HiddenWorlds.
     */
    if (check_ban(dnew->host,BAN_ALL))
    {
	write_to_descriptor_2(desc,
	    "Your site has been banned from this mud.\n\r", 0 );
	mudlogf(NRM, LVL_STAFF, TRUE, "Connection attempt denied from [%s]", dnew->host);
	close_socket(dnew);
	free_descriptor(dnew);
	return;
    }
    /*
     * Init descriptor data.
     */
    dnew->next			= descriptor_list;
    descriptor_list		= dnew;

    /*
     * Send client challenge.
     */
    negotiate_telopt(dnew);
    write_to_buffer(dnew, "This world is Pueblo 1.10 enhanced.\n\r"
			  "Would you like ANSI color? (Y/N) ",0);
    return;
}
#endif



void close_socket( DESCRIPTOR_DATA *dclose ) {
    CHAR_DATA *ch;

    if (dclose->outtop > 0)
	process_output(dclose, FALSE);

    if (dclose->snoop_by != NULL) {
	write_to_buffer(dclose->snoop_by,
	    "Your victim has left the game.\n\r", 0 );
    }

    {
	DESCRIPTOR_DATA *d;

	for (d = descriptor_list; d != NULL; d = d->next) {
	    if (d->snoop_by == dclose)
		d->snoop_by = NULL;
	}
    }

    if ((ch = dclose->character) != NULL) {
	if (ch->pet && ch->pet->in_room == NULL) {
	    char_to_room(ch->pet, get_room_index(ROOM_VNUM_LIMBO));
	    extract_char(ch->pet);
	}

	/* cut down on spam when rebooting
	 * If ch is writing note or playing, just lose link otherwise
	 * clear the char */
	if ((dclose->connected == CON_PLAYING && !merc_down)
	||((dclose->connected >= CON_NOTE_TO)
	&& (dclose->connected <= CON_NOTE_FINISH)))
	{
	    act( "$n has lost $s link.", ch, NULL, NULL, TO_ROOM );
	    mudlogf(NRM, LVL_STAFF, TRUE, "Closing link to: %s.", RealName(ch));

	    if (ch->lasthost)
		free_string(ch->lasthost);
	    ch->lasthost = str_dup(ch->desc->host);

	    ch->desc = NULL;
	} else {
	    free_char(dclose->original ? dclose->original : dclose->character);
	}
    }

    if (d_next == dclose)
	d_next = d_next->next;   

    if (dclose == descriptor_list) {
	descriptor_list = descriptor_list->next;
    } else {
	DESCRIPTOR_DATA *d;

	for (d = descriptor_list; d && d->next != dclose; d = d->next);
	if (d != NULL)
	    d->next = dclose->next;
	else
	    mudlogf(CMP, LVL_STAFF, TRUE, "Losing descriptor without char.");
    }

    if (dclose->out_compress) {
	deflateEnd(dclose->out_compress);
	free_mem(dclose->out_compress_buf, COMPRESS_BUF_SIZE);
	free_mem(dclose->out_compress, sizeof(z_stream));
	if (!compressEnd(dclose))
	    write_to_descriptor(dclose, "Failed to stop compression.\n\r",0);
    }

    close(dclose->descriptor);
    free_descriptor(dclose);
#if defined(MSDOS) || defined(macintosh)
    exit(1);
#endif
    return;
}



bool read_from_descriptor( DESCRIPTOR_DATA *d )
{
    int iStart;

    /* Hold horses if pending command already. */
    if ( d->incomm[0] != '\0' )
	return TRUE;

    /* Check for overflow. */
    iStart = strlen(d->inbuf);
    if ( iStart >= sizeof(d->inbuf) - 10 )
    {
	mudlogf(NRM, LVL_SRSTAFF, TRUE, "%s input overflow!", d->host);
	write_to_descriptor(d, "\n\r*** PUT A LID ON IT!!! ***\n\r", 0 );
	return FALSE;
    }

    /* Snarf input. */
#if defined(macintosh)
    for ( ; ; )
    {
	int c;
	c = getc( stdin );
	if ( c == '\0' || c == EOF )
	    break;
	putc( c, stdout );
	if ( c == '\r' )
	    putc( '\n', stdout );
	d->inbuf[iStart++] = c;
	if ( iStart > sizeof(d->inbuf) - 10 )
	    break;
    }
#endif

#if defined(MSDOS) || defined(unix)
    for ( ; ; )
    {
	int nRead;

	nRead = read( d->descriptor, d->inbuf + iStart,
	    sizeof(d->inbuf) - 10 - iStart );
	if ( nRead > 0 )
	{
	    iStart += nRead;
	    if ( d->inbuf[iStart-1] == '\n' || d->inbuf[iStart-1] == '\r' )
		break;
	}
	else if ( nRead == 0 )
	{
	    log_string( "EOF encountered on read." );
	    return FALSE;
	}
	else if ( errno == EWOULDBLOCK )
	    break;
	else
	{
	    perror( "Read_from_descriptor" );
	    return FALSE;
	}
    }
#endif

    d->inbuf[iStart] = '\0';
    return TRUE;
}



/*
 * Transfer one line from input buffer to input line.
 */
void read_from_buffer(DESCRIPTOR_DATA *d) {
    int i, j, k;

    /*
     * Hold horses if pending command already.
     */
    if ( d->incomm[0] != '\0' )
	return;

    /*
     * Look for incoming telnet negotiation
     */

    /*
     * Look for at least one new line.
     */
    for (i = 0; d->inbuf[i] != '\n' && d->inbuf[i] != '\r'; i++) {
	if ((unsigned char)d->inbuf[i] == IAC)
	    process_telopt(d, i);

	if (d->inbuf[i] == '\0')
	    return;
    }

    /*
     * Canonical input processing.
     */
    for ( i = 0, k = 0; d->inbuf[i] != '\n' && d->inbuf[i] != '\r'; i++ )
    {
	if ( k >= MAX_INPUT_LENGTH - 2 )
	{
	    write_to_descriptor(d, "Line too long.\n\r", 0 );

	    /* skip the rest of the line */
	    for ( ; d->inbuf[i] != '\0'; i++ )
	    {
		if ( d->inbuf[i] == '\n' || d->inbuf[i] == '\r' )
		    break;
	    }
	    d->inbuf[i]   = '\n';
	    d->inbuf[i+1] = '\0';
	    break;
	}

	if (d->inbuf[i] == '\b' && k > 0)
	    --k;
	else if (isascii(d->inbuf[i]) && isprint(d->inbuf[i]))
	    d->incomm[k++] = d->inbuf[i];
    }

    /*
     * Finish off the line.
     */
    if ( k == 0 )
	d->incomm[k++] = ' ';
    d->incomm[k] = '\0';

    /*
     * Deal with bozos with #repeat 1000 ...
     */
    if ( k > 1 || d->incomm[0] == '!' )
    {
    	if ( d->incomm[0] != '!' && strcmp( d->incomm, d->inlast ) )
	{
	    d->repeat = 0;
	}
	else
	{
	    if (++d->repeat >= 25 && d->character
	    &&  d->connected == CON_PLAYING)
	    {
		mudlogf(NRM, LVL_STAFF, TRUE, "%s input overflow, nuking the spammer.", RealName(d->character));
		d->repeat = 0;
		write_to_descriptor(d,
		    "\n\r*** PUT A LID ON IT!!! ***\n\r", 0 );
		if (!IS_STAFF(d->character))
			close_socket(d);
	    }
	}
    }

    /*
     * Do '!' substitution.
     */
    if ( d->incomm[0] == '!' )
	strcpy( d->incomm, d->inlast );
    else
	strcpy( d->inlast, d->incomm );

    /*
     * Shift the input buffer.
     */
    while ( d->inbuf[i] == '\n' || d->inbuf[i] == '\r' )
	i++;
    for ( j = 0; ( d->inbuf[j] = d->inbuf[i+j] ) != '\0'; j++ )
	;
    return;
}



/*
 * Low level output function.
 */
bool process_output( DESCRIPTOR_DATA *d, bool fPrompt )
{
    extern bool merc_down;

    /*
     * Bust a prompt.
     */
    if ( !merc_down ) {
	if (d->showstr_point)
	    write_to_buffer( d, "[Hit Return to continue]\n\r", 0 );
	else if (STATE(d) == CON_NOTE_TEXT)
	    write_to_buffer(d, "> ", 2);
	else if (fPrompt && d->pString)
	    write_to_buffer(d, "> ", 2);
	else if (fPrompt && STATE(d) == CON_PLAYING)
	{
	    CHAR_DATA *ch, *victim;

	ch = d->character;

        /* battle prompt */
        if ((victim = ch->fighting) != NULL && can_see(ch,victim))
        {
            int percent;
            char wound[100];
	    char *pbuff;
	    char buf[MAX_STRING_LENGTH];
	    char buffer[MAX_STRING_LENGTH*2];
 
            if (victim->max_hit > 0)
                percent = victim->hit * 100 / victim->max_hit;
            else
                percent = -1;
 
            if (percent >= 100)
                sprintf(wound,"is in excellent condition.");
            else if (percent >= 90)
                sprintf(wound,"has a few scratches.");
            else if (percent >= 75)
                sprintf(wound,"has some small wounds and bruises.");
            else if (percent >= 50)
                sprintf(wound,"has quite a few wounds.");
            else if (percent >= 30)
                sprintf(wound,"has some big nasty wounds and scratches.");
            else if (percent >= 15)
                sprintf(wound,"looks pretty hurt.");
            else if (percent >= 0)
                sprintf(wound,"is in awful condition.");
            else
                sprintf(wound,"is bleeding to death.");
 
            sprintf(buf,"%s %s \n\r", 
	            IS_NPC(victim) ? victim->short_descr : victim->name,wound);
	    buf[0]	= UPPER( buf[0] );
	    pbuff	= buffer;
	    colourconv(pbuff, buf, d->character);
            write_to_buffer(d, buffer, 0);
        }


	ch = d->original ? d->original : d->character;
	if (!IS_SET(ch->comm, COMM_COMPACT))
	    write_to_buffer(d, "\n\r", 2);

        if (IS_SET(ch->comm, COMM_PROMPT))
            bust_a_prompt(d->character);

	if (IS_SET(ch->comm,COMM_TELNET_GA))
	    write_to_buffer(d,go_ahead_str,0);
    }
}
    /*
     * Short-circuit if nothing to write.
     */
    if ( d->outtop == 0 )
	return TRUE;

    /*
     * Snoop-o-rama.
     */
    if (d->snoop_by != NULL) {
	if (d->character != NULL)
	    write_to_buffer( d->snoop_by, d->character->name,0);
	write_to_buffer(d->snoop_by, "> ", 2);
	write_to_buffer(d->snoop_by, d->outbuf, d->outtop);
    }

    /*
     * OS-dependent output.
     */
    if (!write_to_descriptor(d, d->outbuf, d->outtop))
    {
	d->outtop = 0;
	return FALSE;
    }
    else
    {
	d->outtop = 0;
	return TRUE;
    }
}

/*
 * Bust a prompt (player settable prompt)
 * coded by Morgenes for Aldara Mud
 *
 * Better battle by Mendanbar %b
 */
void bust_a_prompt( CHAR_DATA *ch ) {
    CHAR_DATA *victim;
    char buf[MAX_STRING_LENGTH];
    char buf2[MAX_STRING_LENGTH];
    const char *str;
    const char *i;
    char *clr;
    char *point;
    char *pbuff;
    char buffer[ MAX_STRING_LENGTH*2 ];
    char doors[MAX_INPUT_LENGTH];
    EXIT_DATA *pexit;
    bool found;
    const char *dir_name[] = {"n","e","s","w","u","d"};
    int door;
    int percent;
 
    point = buf;
    str = ch->prompt;
    if( !str || str[0] == '\0')
    { 
	send_to_char("`YROGUE`n: `cSet your prompt (see `n'`Cdisplay`n'`c)`W>`n",ch);
	return;
    }
    if (ch->invis_level > 0) {
	sprintf(buf, "`gw%d`n ", ch->invis_level);
	send_to_char(buf, ch);
    }
    if (ch->incog_level > 0) {
	sprintf(buf, "`gi%d`n ", ch->incog_level);
	send_to_char(buf, ch);
    }

   if (IS_SET(ch->comm,COMM_AFK))
	send_to_char("`C[AFK]`n",ch);
   if (ch->desc->editor) {
	ch->Send("`r%s`R: `c<`r%s`c> %s`n> ",
	olc_ed_name(ch), olc_ed_vnum(ch), olc_ed_desc(ch));
	return;
   }

   while( *str != '\0' )
   {
      if( *str != '%' )
      {
         *point++ = *str++;
         continue;
      }
      ++str;
      switch( *str )
      {
         default:
            i = " "; break;
	case 'e':
	    found = FALSE;
	    doors[0] = '\0';
	    for (door = 0; door < 6; door++)
	    {
		if ((pexit = ch->in_room->exit[door]) != NULL
		&&  pexit ->u1.to_room != NULL
		&&  can_see_room(ch,pexit->u1.to_room)
		&&  can_see_ex_hidden(ch, ch->in_room->exit[door]))
		{
		    found = TRUE;
		    sprintf(doors + strlen(doors), "%s",
			!IS_SET(pexit->exit_info, EX_CLOSED) ?
			capitalize(dir_name[door]) : dir_name[door]);
		}
	    }
	    if (!found)
	 	strcat(doors,"none");
	    sprintf(buf2,"%s",doors);
	    i = buf2; break;
 	 case 'c' :
	    sprintf(buf2,"%s","\n\r");
	    i = buf2; break;
         case 'h' :
            sprintf( buf2, "%d", ch->hit );
            i = buf2; break;
         case 'H' :
            sprintf( buf2, "%d", ch->max_hit );
            i = buf2; break;
         case 'm' :
            sprintf( buf2, "%d", ch->mana );
            i = buf2; break;
         case 'M' :
            sprintf( buf2, "%d", ch->max_mana );
            i = buf2; break;
         case 'v' :
            sprintf( buf2, "%d", ch->move );
            i = buf2; break;
         case 'V' :
            sprintf( buf2, "%d", ch->max_move );
            i = buf2; break;
         case 'x' :
            sprintf( buf2, "%d", ch->exp );
            i = buf2; break;
	 case 'X' :
	    sprintf(buf2, "%d", IS_NPC(ch) ? 0 :
		xp_table[UMIN(20, ch->level + 1)]);
	    i = buf2; break;
         case 'g' :
            sprintf( buf2, "%ld", ch->gold);
            i = buf2; break;
	 case 's' :
	    sprintf( buf2, "%ld", ch->silver);
	    i = buf2; break;
         case 'a' :
            if( ch->level > 9 )
               sprintf( buf2, "%d", ch->alignment );
            else
               sprintf( buf2, "%s", IS_GOOD(ch) ? "good" : IS_EVIL(ch) ?
                "evil" : "neutral" );
            i = buf2; break;
         case 'r' :
            if( ch->in_room != NULL )
               sprintf( buf2, "%s", 
		((!IS_NPC(ch) && IS_SET(ch->act,PLR_HOLYLIGHT)) ||
		 (!IS_AFFECTED(ch,AFF_BLIND) && !room_is_dark( ch->in_room )))
		? ch->in_room->name : "darkness");
            else
               sprintf( buf2, " " );
            i = buf2; break;
         case 'R' :
            if( IS_IMMORTAL( ch ) && ch->in_room != NULL )
               sprintf( buf2, "%d", ch->in_room->vnum );
            else
               sprintf( buf2, " " );
            i = buf2; break;
         case 'z' :
            if( IS_IMMORTAL( ch ) && ch->in_room != NULL )
               sprintf( buf2, "%s", ch->in_room->area->name );
            else
               sprintf( buf2, " " );
            i = buf2; break;
         case '%' :
            sprintf( buf2, "%%" );
            i = buf2; break;
         case 'o' :
            sprintf( buf2, "%s", olc_ed_name(ch) );
            i = buf2; break;
	 case 'O' :
	    sprintf( buf2, "%s", olc_ed_vnum(ch) );
	    i = buf2; break;
	 case 'b':
		if ((victim = ch->fighting) != NULL)
		{
			if (victim->max_hit > 0)
				percent = victim->hit * 100 / victim->max_hit;
			else
				percent = -1;
			if (percent >= 65)			clr = "`g";
			else if (percent >= 25 && percent < 65)	clr = "`Y";
			else					clr = "`r";
	
			sprintf(buf2, "`w(`r%s`w) [%s%d%%`w]`n ", PERS(victim,ch),clr,percent);
			i = buf2;
		} else	i = ""; /* i = "(none) [X] "; */
		break;
      }
      ++str;
      while( (*point = *i) != '\0' )
         ++point, ++i;
   }
   *point	= '\0';
   pbuff	= buffer;
   colourconv( pbuff, buf, ch );
   write_to_buffer( ch->desc, buffer, 0 );

   if (ch->prefix[0] != '\0')
        write_to_buffer(ch->desc,ch->prefix,0);
   return;
}



/*
 * Append onto an output buffer.
 */
void write_to_buffer(DESCRIPTOR_DATA *d, const char *txt, int length) {
    int origlength;

    /*
     * Find length in case caller didn't.
     */
    if (length <= 0)
	length = strlen(txt);

    origlength = length;
    length += count_mxp_tags(DESC_FLAGGED(d, DESC_MXPON), txt, length);

    /*
     * Initial \n\r if needed.
     */
    if ( d->outtop == 0 && !d->fcommand )
    {
	d->outbuf[0]	= '\n';
	d->outbuf[1]	= '\r';
	d->outtop	= 2;
    }

    /*
     * Expand the buffer as needed.
     */
    while ( d->outtop + length >= d->outsize )
    {
	char *outbuf;

        if (d->outsize >= 32000)
	{
	    mudlogf(NRM, LVL_STAFF, TRUE, "Buffer overflow. Closing socket.");
	    close_socket(d);
	    return;
 	}
	outbuf = (char *)alloc_mem(2 * d->outsize);
	strncpy( outbuf, d->outbuf, d->outtop );
	free_mem( d->outbuf, d->outsize );
	d->outbuf   = outbuf;
	d->outsize *= 2;
    }

    /*
     * Copy.
     */
    strncpy(d->outbuf + d->outtop, txt, length);
    convert_mxp_tags(DESC_FLAGGED(d, DESC_MXPON), d->outbuf + d->outtop, txt, origlength);
    d->outtop += length;
    return;
}



/*
 * Lowest level output function.
 * Write a block of text to the file descriptor.
 * If this gives errors on very long blocks (like 'ofind all'),
 *   try lowering the max block size.
 */
bool write_to_descriptor_2(int desc, char *txt, int length)
{
    int iStart;
    int nWrite;
    int nBlock;

#if defined(macintosh) || defined(MSDOS)
    if ( desc == 0 )
	desc = 1;
#endif

    if ( length <= 0 )
	length = strlen(txt);

    for ( iStart = 0; iStart < length; iStart += nWrite )
    {
	nBlock = UMIN( length - iStart, 4096 );
	if ( ( nWrite = write( desc, txt + iStart, nBlock ) ) < 0 )
	    { perror( "Write_to_descriptor" ); return FALSE; }
    } 

    return TRUE;
}

bool write_to_descriptor(DESCRIPTOR_DATA *d, char *txt, int length) {
    if (d->out_compress)
	return writeCompressed(d, txt, length);
    else
	return write_to_descriptor_2(d->descriptor, txt, length);
}


/*
 * Deal with sockets that haven't logged in yet.
 */
void nanny( DESCRIPTOR_DATA *d, char *argument ) {
    DESCRIPTOR_DATA *d_old, *d_next;
    char buf[MAX_STRING_LENGTH];
    char arg[MAX_INPUT_LENGTH];
    CHAR_DATA *ch;
    char *pwdnew, *p;
    int iClass, race, deity, i, weapon;
    bool fOld, found;

    int get_player_database();
    void set_player_database(int num);

    /* Delete leading spaces UNLESS character is writing a note */
    if (d->connected != CON_NOTE_TEXT) {
	while ( isspace(*argument) )
		argument++;
    }

    ch = d->character;

    switch ( d->connected )
    {

    default:
	mudlogf(BRF, LVL_STAFF, TRUE, "SYSERR: nanny: bad d->connected %d.", STATE(d));
	close_socket( d );
	return;

    case CON_GET_NAME:
	if ( argument[0] == '\0' )
	{
	    close_socket( d );
	    return;
	}

	argument[0] = UPPER(argument[0]);
	if ( !check_parse_name( argument ) )
	{
	    write_to_buffer( d, "Illegal name, try another.\n\rName: ", 0 );
	    return;
	}

	fOld = load_char_obj( d, argument, FALSE );
	ch   = d->character;

	if (check_ban(d->host,BAN_PERMIT) && !IS_SET(ch->act,PLR_PERMIT))
	{
	    write_to_buffer(d,"Your site has been banned from this mud.\n\r",0);
	    mudlogf(NRM, LVL_STAFF, TRUE, "Connection attempt for %s denied from %s", RealName(ch), d->host);
	    close_socket(d);
	    return;
	}

	if (check_reconnect(d, argument, FALSE)) {
	    fOld = TRUE;
	} else {
	    if (wizlock && !IS_IMMORTAL(ch)) {
		write_to_buffer( d, "The game is wizlocked.\n\r", 0 );
		mudlogf(NRM, LVL_STAFF, TRUE, "Request for login denied for %s [%s] (wizlock)", RealName(ch), d->host);
		close_socket( d );
		return;
	    }
	}

	if ( fOld )
	{
	    /* Old player */
	    write_to_buffer( d, "Password: ", 0 );
	    write_to_buffer( d, echo_off_str, 0 );
	    d->connected = CON_GET_OLD_PASSWORD;
	    return;
	}
	else
	{
	    /* New player */
 	    if (newlock)
	    {
                write_to_buffer( d, "The game is newlocked.\n\r", 0 );
		mudlogf(NRM, LVL_STAFF, TRUE, "Request for login denied for %s [%s] (newlock)", RealName(ch), d->host);
                close_socket( d );
                return;
            }

	    if (check_ban(d->host,BAN_NEWBIES))
	    {
		write_to_buffer(d,
		    "New players are not allowed from your site.\n\r",0);
		mudlogf(NRM, LVL_STAFF, TRUE, "Request for new char %s denied from [%s] (siteban)",
			RealName(d->character), d->host);
		close_socket(d);
		return;
	    }
	
	    sprintf( buf, "Did I get that right, %s (Y/N)? ", argument );
	    write_to_buffer( d, buf, 0 );
	    d->connected = CON_CONFIRM_NEW_NAME;
	    return;
	}
	break;

    case CON_GET_OLD_PASSWORD:
#if defined(unix)
	write_to_buffer( d, "\n\r", 2 );
#endif

	if (strcmp(CRYPT(argument, ch->pcdata->pwd), ch->pcdata->pwd))
	{
	    write_to_buffer( d, "Wrong password.\n\r", 0 );
	    mudlogf(NRM, LVL_STAFF, TRUE, "Bad PW: %s [%s]", RealName(d->character), d->host);
	    close_socket(d);
	    return;
	}
 
	write_to_buffer( d, echo_on_str, 0 );


	if (check_playing(d, ch->name))
	    return;

	if (check_reconnect(d, ch->name, TRUE))
	    return;

	mudlogf(NRM, UMAX(LVL_CODER, ch->invis_level), TRUE, 
	"%s [%s] has connected.", RealName(ch), d->host);

	ch->logon = time(0);

	if (IS_IMMORTAL(ch))
	    do_function(ch, &do_help, "imotd", 0);
	else
	    do_function(ch, &do_help, "motd", 0);

	send_to_char("\n\n\r*** Hit Return to Continue: ",ch);
	STATE(d) = CON_READ_MOTD;
	break;

/* RT code for breaking link */
 
    case CON_BREAK_CONNECT:
	switch( *argument )
	{
	case 'y' : case 'Y':
            for ( d_old = descriptor_list; d_old != NULL; d_old = d_next )
	    {
		d_next = d_old->next;
		if (d_old == d || d_old->character == NULL)
		    continue;

		if (str_cmp(ch->name,d_old->original ?
		    d_old->original->name : d_old->character->name))
		    continue;

		close_socket(d_old);
	    }
	    if (check_reconnect(d,ch->name, TRUE))
	    	return;
	    write_to_buffer(d,"Reconnect attempt failed.\n\rName: ",0);
            if ( d->character != NULL )
            {
                free_char( d->character );
                d->character = NULL;
            }
	    d->connected = CON_GET_NAME;
	    break;

	case 'n' : case 'N':
	    write_to_buffer(d,"Name: ",0);
            if ( d->character != NULL )
            {
                free_char( d->character );
                d->character = NULL;
            }
	    d->connected = CON_GET_NAME;
	    break;

	default:
	    write_to_buffer(d,"Please type Y or N? ",0);
	    break;
	}
	break;

    case CON_CONFIRM_NEW_NAME:
	switch ( *argument )
	{
	case 'y': case 'Y':
	    sprintf( buf, "New character.\n\rGive me a password for %s: %s",
		ch->name, echo_off_str );
	    write_to_buffer( d, buf, 0 );
	    d->connected = CON_GET_NEW_PASSWORD;
	    break;

	case 'n': case 'N':
	    write_to_buffer( d, "Ok, what IS it, then? ", 0 );
	    free_char( d->character );
	    d->character = NULL;
	    d->connected = CON_GET_NAME;
	    break;

	default:
	    write_to_buffer( d, "Please type Yes or No? ", 0 );
	    break;
	}
	break;

    case CON_CHPWD_GETNEW:
    case CON_GET_NEW_PASSWORD:
#if defined(unix)
	write_to_buffer( d, "\n\r", 2 );
#endif

	if ( strlen(argument) < 5 )
	{
	    write_to_buffer( d,
		"Password must be at least five characters long.\n\rPassword: ",
		0 );
	    return;
	}

	pwdnew = CRYPT(argument, ch->name);
	for ( p = pwdnew; *p != '\0'; p++ )
	{
	    if ( *p == '~' )
	    {
		write_to_buffer( d,
		    "New password not acceptable, try again.\n\rPassword: ",
		    0 );
		return;
	    }
	}

	free_string( ch->pcdata->pwd );
	ch->pcdata->pwd	= str_dup( pwdnew );
	write_to_buffer( d, "Please retype password: ", 0 );
	STATE(d) = (STATE(d) == CON_GET_NEW_PASSWORD) ? CON_CONFIRM_NEW_PASSWORD : CON_CHPWD_VERIFY;
	break;

    case CON_CHPWD_VERIFY:
    case CON_CONFIRM_NEW_PASSWORD:
#if defined(unix)
	write_to_buffer( d, "\n\r", 2 );
#endif

	if (strcmp(CRYPT(argument, ch->pcdata->pwd), ch->pcdata->pwd))
	{
	    write_to_buffer( d, "Passwords don't match.\n\rRetype password: ",
		0 );
	    STATE(d) = (STATE(d) == CON_CONFIRM_NEW_PASSWORD) ?  CON_GET_NEW_PASSWORD : CON_CHPWD_GETNEW;
	    return;
	}
	write_to_buffer(d, echo_on_str, 0);
	write_to_buffer(d, "\n\r", 0);
	if (STATE(d) == CON_CHPWD_VERIFY) {
		save_char_obj(ch);
		send_to_desc("Done.\n\r", d);
		send_to_desc(MENU, d);
		STATE(d) = CON_MENU;
	} else {
		write_to_buffer(d, "What is your last name? (name or none): ", 0);
		d->connected = CON_GET_LAST_NAME;
	}
	break;

    case CON_CHANGE_LNAME:
	if (!str_cmp(argument, "none")) {
		free_string(ch->lname);
		ch->lname = str_dup("");
	} else if (!check_parse_name(argument)) {
		send_to_desc("Illegal last name. What is your last name: ",d);
		return;
	} else {
		sprintf(buf, " %s", argument);
		free_string(ch->lname);
		ch->lname = str_dup(buf);
	}
	send_to_desc(MENU, d);
	STATE(d) = CON_MENU;
	break;

    case CON_GET_LAST_NAME:
	if (str_cmp(argument, "none")) {
		char buf[14];
		argument[0] = UPPER(argument[0]);
		if (!check_parse_name(argument)) {
			write_to_buffer(d, "Illegal last name.\n\r"
			   "What is your last name: ", 0);
			return;
		}

		sprintf(buf, " %s", argument);
		free_string(ch->lname);
		ch->lname = str_dup(buf);
	}
	write_to_buffer(d,"The following races are available:\n\r  ",0);
	for ( race = 1; race_table[race].name != NULL; race++ )
	{
	    if (!race_table[race].pc_race)
		break;
	    write_to_buffer(d,race_table[race].name,0);
	    write_to_buffer(d," ",1);
	}
	write_to_buffer(d,"\n\r",0);
	write_to_buffer(d,"What is your race (help for more information)? ",0);
	d->connected = CON_GET_NEW_RACE;
	break;

    case CON_GET_NEW_RACE:
	one_argument(argument,arg);

	if (!strcmp(arg,"help"))
	{
	    argument = one_argument(argument,arg);
	    if (argument[0] == '\0')
		do_function(ch, &do_help, "race help", 0);
	    else
		do_function(ch, &do_help, argument, 0);
            write_to_buffer(d,
		"What is your race (help for more information)? ",0);
	    break;
  	}

	race = race_lookup(argument);

	if (race == 0 || !race_table[race].pc_race)
	{
	    write_to_buffer(d,"That is not a valid race.\n\r",0);
            write_to_buffer(d,"The following races are available:\n\r  ",0);
            for ( race = 1; race_table[race].name != NULL; race++ )
            {
            	if (!race_table[race].pc_race)
                    break;
            	write_to_buffer(d,race_table[race].name,0);
            	write_to_buffer(d," ",1);
            }
            write_to_buffer(d,"\n\r",0);
            write_to_buffer(d,
		"What is your race? (help for more information) ",0);
	    break;
	}

        ch->race = race;
	ch->affected_by = ch->affected_by|race_table[race].aff;
	ch->affected2_by= ch->affected2_by|race_table[race].aff2;
	ch->imm_flags	= ch->imm_flags|race_table[race].imm;
	ch->res_flags	= ch->res_flags|race_table[race].res;
	ch->vuln_flags	= ch->vuln_flags|race_table[race].vuln;
	ch->form	= race_table[race].form;
	ch->parts	= race_table[race].parts;
	ch->size	= pc_race_table[race].size;

	if (pc_race_table[ch->race].has_subrace) {
	    write_to_buffer(d, "\n\r", 0);
	    write_to_buffer(d, "The following sub-races are available:\n\r  ", 0);
	    for (race = 1; pc_subrace_table[race].race != NULL; race++) {
		if (str_cmp(pc_subrace_table[race].race, pc_race_table[ch->race].name))
		    continue;
		write_to_buffer(d, pc_subrace_table[race].name, 0);
		write_to_buffer(d, " ", 1);
	    }
	    write_to_buffer(d, "\n\r", 0);
	    write_to_buffer(d, "What is your sub-race? ", 0);
	    STATE(d) = CON_GET_NEW_SUBRACE;
	} else {
	    write_to_buffer(d, "What is your sex (M/F)? ", 0);
	    STATE(d) = CON_GET_NEW_SEX;
	}
	break;

    case CON_GET_NEW_SUBRACE:
	one_argument(argument, arg);

	if (!*arg) {
	    write_to_buffer(d, "What is your sub-race? ", 0);
	    return;
	}
	if (!strcmp(arg, "help")) {
	    argument = one_argument(argument, arg);
	    if (argument[0] == '\0')
		do_function(ch, &do_help, "subrace help", 0);
	    else
		do_function(ch, &do_help, argument, 0);
	    write_to_buffer(d, "What is your sub-race? ", 0);
	    break;
	}

	for (i = 0; pc_subrace_table[i].race != NULL; i++) {
	    if (str_cmp(pc_subrace_table[i].race, pc_race_table[ch->race].name))
		continue;
	    if (!str_prefix(arg, pc_subrace_table[i].name))
		break;
	}

	if (pc_subrace_table[i].race == NULL) {
	    write_to_buffer(d, "\n\r", 0);
	    write_to_buffer(d, "That is not a valid sub-race.\n\r", 0);
	    write_to_buffer(d, "The following sub-races are available:\n\r  ", 0);
	    for (race = 1; pc_subrace_table[race].race != NULL; race++) {
		if (str_cmp(pc_subrace_table[race].race, pc_race_table[ch->race].name))
		    continue;
		write_to_buffer(d, pc_subrace_table[race].name, 0);
		write_to_buffer(d, " ", 1);
	    }
	    write_to_buffer(d, "\n\r", 0);
	    write_to_buffer(d, "What is your sub-race? ", 0);
	    break;
	}
	ch->subrace = i;

	write_to_buffer( d, "What is your sex (M/F)? ", 0 );
	d->connected = CON_GET_NEW_SEX;
	break;

    case CON_GET_NEW_SEX:
	switch (argument[0]) {
	case 'm': case 'M': ch->sex = SEX_MALE;    
			    ch->pcdata->true_sex = SEX_MALE;
			    break;
	case 'f': case 'F': ch->sex = SEX_FEMALE; 
			    ch->pcdata->true_sex = SEX_FEMALE;
			    break;
	default:
	    write_to_buffer( d, "That's not a sex.\n\rWhat IS your sex? ", 0 );
	    return;
	}

	strcpy(buf, "\n\rThe Gods of Krynn are:\n\r");
	sprintf(buf+strlen(buf),
		"  %-12.12s %-17.17s %s\n\r"
		"  ------------ ----------------- -----------------------------------------\n\r",
			"Deity", "Alignments", "Domains");
	for (deity = 0; deity_table[deity].name != NULL; deity++) {
		sprintf(buf+strlen(buf), "  %-12.12s %-17.17s %s\n\r",
		deity_table[deity].name,
		flag_string(align_flags, deity_table[deity].align),
		deity_table[deity].domains);
	}
	strcat(buf, "Which God will you follow? ");
	write_to_buffer(d, buf, 0);
	d->connected = CON_GET_NEW_DEITY;
	break;

    case CON_GET_NEW_DEITY:
	one_argument(argument, arg);

	if (!strcmp(arg, "help")) {
	    argument = one_argument(argument, arg);
	    if (!*argument)
		do_function(ch, &do_help, "deity help", 0);
	    else
		do_function(ch, &do_help, argument, 0);
	    write_to_buffer(d, "Who is your deity (help for more information? ", 0);
	    break;
	}
	if (!strcmp(arg, "list")) {
	    strcpy(buf, "\n\rThe Gods of Krynn are:\n\r");
	    sprintf(buf+strlen(buf),
		"  %-12.12s %-17.17s %s\n\r"
		"  ------------ ----------------- -----------------------------------------\n\r",
			"Deity", "Alignments", "Domains");
	    for (deity = 0; deity_table[deity].name != NULL; deity++) {
		sprintf(buf+strlen(buf), "  %-12.12s %-17.17s %s\n\r",
			deity_table[deity].name,
			flag_string(align_flags, deity_table[deity].align),
			deity_table[deity].domains);
	    }
	    strcat(buf, "Which God will you follow? ");
	    write_to_buffer(d, buf, 0);
	    break;
	}

	if ((deity = deity_lookup(argument)) == -1) {
	    write_to_buffer(d,	"That is not a valid Deity.\n\r"
				"What is your Deity? (or type list): ", 0);
	    break;
	}
	ch->deity = deity;

	strcpy(buf, "Select a class [");
	for (iClass = 0; iClass < MAX_CLASS; iClass++) {
	    if (!IS_SET(class_table[iClass].align, ALIGN_ANY)
	    && !IS_SET(deity_table[ch->deity].align, class_table[iClass].align))
		continue;
	    if (iClass > 0)
		strcat(buf, " ");
	    strcat(buf, class_table[iClass].name);
	}
	strcat(buf, "]: ");
	write_to_buffer(d, buf, 0);
	d->connected = CON_GET_NEW_CLASS;
	break;

    case CON_GET_NEW_CLASS:
	iClass = class_lookup(argument);

	if (iClass == -1) {
	    write_to_buffer(d, "That's not a class.\n\r", 0);
	    write_to_buffer(d, "What IS your class? ", 0);
	    return;
	}
	if (!IS_SET(class_table[iClass].align, ALIGN_ANY)
	&& !IS_SET(deity_table[ch->deity].align, class_table[iClass].align)) {
	    write_to_buffer(d, "You may not choose that class.\n\r", 0);
	    write_to_buffer(d, "What IS your class? ", 0);
	    return;
	}
        ch->Class = iClass;

	mudlogf(NRM, LVL_STAFF, FALSE, "Newbie alert! %s sighted.", RealName(ch));
	mudlogf(NRM, LVL_STAFF, TRUE, "%s [%s] new player.", RealName(ch), d->host);

	sprintf(buf,
		"\n\r"
		"\x1B[H\x1B[J"
		"You may be: %s\n\r"
		"What is your alignment? ",
		sprintbit_dash(
		(IS_SET(class_table[ch->Class].align, ALIGN_ANY) ?
		deity_table[ch->deity].align : class_table[ch->Class].align),
		align_names));
	write_to_buffer(d, buf, 0);
	d->connected = CON_GET_ALIGNMENT;
	break;

    case CON_GET_BODY:
	if ((i = search_block(argument, body_type, FALSE)) == -1) {
	    send_to_desc("Sorry that is not a valid body type.\n\r", d);
	    return;
	}
	GET_BODY(ch) = (1 << i);

	strcpy(buf,	"\n\r"
			"\x1B[H\x1B[J"
			"Following facial types are available:\n\r");
	for (i = 0; *facial_style[i] != '\n'; i++)
	    sprintf(buf+strlen(buf), "  %s\n\r", capitalize(facial_style[i]));
	strcat(buf, "What is your facial type? ");
	write_to_buffer(d, buf, 0);
	STATE(d) = CON_GET_FACE;
	break;

    case CON_GET_FACE:
	if ((i = search_block(argument, facial_style, FALSE)) == -1) {
	    send_to_desc("Sorry that is not a valid facial style.\n\r", d);
	    return;
	}
	GET_FACE(ch) = (1 << i);

	strcpy(buf,	"\n\r"
			"\x1B[H\x1B[J"
			"Following eye colors are available:\n\r");
	for (i = 0; *eye_color[i] != '\n'; i++)
	    sprintf(buf+strlen(buf), "  %s\n\r", capitalize(eye_color[i]));
	strcat(buf, "What is your eye color? ");
	write_to_buffer(d, buf, 0);
	STATE(d) = CON_GET_EYES;
	break;

    case CON_GET_EYES:
	if ((i = search_block(argument, eye_color, FALSE)) == -1) {
	    send_to_desc("Sorry that is not a valid eye color.\n\r", d);
	    return;
	}
	GET_EYES(ch) = (1 << i);

	strcpy(buf,	"\n\r"
			"\x1B[H\x1B[J"
			"Following skin colors are available:\n\r");
	for (i = 0; *skin_color[i] != '\n'; i++)
	    sprintf(buf+strlen(buf), "  %s\n\r", capitalize(skin_color[i]));
	strcat(buf, "What is your skin color? ");
	write_to_buffer(d, buf, 0);
	STATE(d) = CON_GET_SKIN;
	break;

    case CON_GET_SKIN:
	if ((i = search_block(argument, skin_color, FALSE)) == -1) {
	    send_to_desc("Sorry that is not a valid skin color.\n\r", d);
	    return;
	}
	GET_SKIN(ch) = (1 << i);

	strcpy(buf,	"\n\r"
			"\x1B[H\x1B[J"
			"Following hair colors are available:\n\r");
	for (i = 0; *hair_color[i] != '\n'; i++)
	    sprintf(buf+strlen(buf), "  %s\n\r", capitalize(hair_color[i]));
	strcat(buf, "What is your hair color? ");
	write_to_buffer(d, buf, 0);
	STATE(d) = CON_GET_HAIR_COLOR;
	break;

    case CON_GET_HAIR_COLOR:
	if ((i = search_block(argument, hair_color, FALSE)) == -1) {
	    send_to_desc("Sorry that is not a valid hair color.\n\r", d);
	    return;
	}
	GET_HAIR_COLOR(ch) = (1 << i);

	strcpy(buf,	"\n\r"
			"\x1B[H\x1B[J"
			"Following hair lengths are available:\n\r");
	for (i = 0; *hair_length[i] != '\n'; i++)
	    sprintf(buf+strlen(buf), "  %s\n\r", capitalize(hair_length[i]));
	strcat(buf, "What is your hair length? ");
	write_to_buffer(d, buf, 0);
	STATE(d) = CON_GET_HAIR_LENGTH;
	break;

    case CON_GET_HAIR_LENGTH:
	if ((i = search_block(argument, hair_length, FALSE)) == -1) {
	    send_to_desc("Sorry that is not a valid hair length.\n\r", d);
	    return;
	}
	GET_HAIR_LENGTH(ch) = (1 << i);

	strcpy(buf,	"\n\r"
			"\x1B[H\x1B[J"
			"Following hair type are available:\n\r");
	for (i = 0; *hair_type[i] != '\n'; i++)
	    sprintf(buf+strlen(buf), "  %s\n\r", capitalize(hair_type[i]));
	strcat(buf, "What is your hair style? ");
	write_to_buffer(d, buf, 0);
	STATE(d) = CON_GET_HAIR_TYPE;
	break;

    case CON_GET_HAIR_TYPE:
	if ((i = search_block(argument, hair_type, FALSE)) == -1) {
	    send_to_desc("Sorry that is not a valid hair type.\n\r", d);
	    return;
	}
	GET_HAIR_TYPE(ch) = (1 << i);

	write_to_buffer(d,"\n\r", 2);
	do_function(ch, &do_help, "motd", 0);
	send_to_char("\n\r*** Hit Return to Continue: ",ch);
	d->connected = CON_READ_MOTD;
	break;

    case CON_GET_ALIGNMENT:
	if ((i = search_block(argument, align_names, FALSE)) == -1
	|| !IS_SET((IS_SET(class_table[ch->Class].align, ALIGN_ANY) ?
	deity_table[ch->deity].align : class_table[ch->Class].align), (1 << i)))
	{
	    send_to_desc("That's not a valid alignment.\n\r"
			 "What is your alignment? ", d);
	    return;
	}
	ch->alignment = (1 << i);

	/* Initialize stats */
	roll_temp_abils(ch);
	sprintf(buf,
		"\x1B[H\x1B[J"
		"Your stats are:\n\r\n\r"
		"      Current Stat    Mod\n\r"
		"Strength    : (%2d)     %2d\n\r"
		"Intelligence: (%2d)     %2d\n\r"
		"Wisdom      : (%2d)     %2d\n\r"
		"Dexterity   : (%2d)     %2d\n\r"
		"Constitution: (%2d)     %2d\n\r"
		"Charisma    : (%2d)     %2d\n\r"
		"\n\r"
		"Your roll: %2d, %2d, %2d, %2d, %2d, %2d\n\r"
		"Type <attribute> <number> to assign a number to an attribute.\n\r"
		"Choices are: reroll, clear, and done. ",
		ch->perm_stat[STAT_STR], pc_race_table[ch->race].stats[STAT_STR],
		ch->perm_stat[STAT_INT], pc_race_table[ch->race].stats[STAT_INT],
		ch->perm_stat[STAT_WIS], pc_race_table[ch->race].stats[STAT_WIS],
		ch->perm_stat[STAT_DEX], pc_race_table[ch->race].stats[STAT_DEX],
		ch->perm_stat[STAT_CON], pc_race_table[ch->race].stats[STAT_CON],
		ch->perm_stat[STAT_CHA], pc_race_table[ch->race].stats[STAT_CHA],
		ch->roll_stat[0], ch->roll_stat[1], ch->roll_stat[2],
		ch->roll_stat[3], ch->roll_stat[4], ch->roll_stat[5]);
	send_to_desc(buf, d);
	STATE(d) = CON_STAT_CNFRM;
	break;

    case CON_STAT_CNFRM:
	if (!str_cmp(argument, "done")) {
	    bool cango = TRUE;
	    for (i = 0; i < MAX_STATS; i++)
		if (ch->roll_stat[i] > 0)
		    cango = FALSE;

	    if (!cango) {
		send_to_desc("You still have attributes to assign.\n\r", d);
		send_to_desc("Choices are: reroll, clear, and done. ", d);
		break;
	    }
	    /* Apply racial modifiers */
	    ch->perm_stat[STAT_STR] += pc_race_table[ch->race].stats[STAT_STR];
	    ch->perm_stat[STAT_INT] += pc_race_table[ch->race].stats[STAT_INT];
	    ch->perm_stat[STAT_WIS] += pc_race_table[ch->race].stats[STAT_WIS];
	    ch->perm_stat[STAT_DEX] += pc_race_table[ch->race].stats[STAT_DEX];
	    ch->perm_stat[STAT_CON] += pc_race_table[ch->race].stats[STAT_CON];
	    ch->perm_stat[STAT_CHA] += pc_race_table[ch->race].stats[STAT_CHA];

	    strcpy(buf, "\n\rFollowing body types are available:\n\r");
	    for (i = 0; *body_type[i] != '\n'; i++)
		sprintf(buf+strlen(buf), "  %s\n\r", capitalize(body_type[i]));
	    strcat(buf, "What is your body type? ");
	    write_to_buffer(d, buf, 0);
	    STATE(d) = CON_GET_BODY;
	    break;
	}
	argument = one_argument(argument, arg);

	if (!str_cmp(arg, "clear")) {
	    for (i = 0; i < MAX_STATS; i++)
		ch->perm_stat[i] = 0;
	    ch->roll_stat = ch->temp_stat;
	} else if (!str_cmp(arg, "reroll")) {
	    int b = 0, c = 0;

	    for (i = 0; i < MAX_STATS; i++) {
		if (ch->temp_stat[i] > 13)
		    b++;
		if (get_abil_mod(ch->temp_stat[i]))
		    c += get_abil_mod(ch->temp_stat[i]);
	    }

	    if (b || c > 0) {
		send_to_desc("You cannot reroll, total ability modifiers above zero.\n\r", d);
		send_to_desc("Choices are: reroll, clear, and done. ", d);
		break;
	    }
	    roll_temp_abils(ch);
	} else if ((i = search_block(arg, ability_type, FALSE)) != -1) {
	    int b = 0;
	    found = FALSE;
	    one_argument(argument, arg);

	    if (!isdigit(*arg)) {
		send_to_desc("Please select a number from your rolls.\n\r", d);
		send_to_desc("Choices are: reroll, clear, and done. ", d);
		break;
	    }

	    for (b = 0; b < MAX_STATS; b++) {
		if (atoi(arg) == ch->roll_stat[b] && ch->roll_stat[b] > 0) {
		    found = TRUE;
		    break;
		}
	    }

	    if (found) {
		ch->perm_stat[i] = ch->roll_stat[b];
		ch->roll_stat[b] = 0;
	    } else {
		send_to_desc("That number is not available.\n\r", d);
		send_to_desc("Choices are: reroll, clear, and done. ", d);
		break;
	    }
	}

	sprintf(buf,
		"\x1B[H\x1B[J"
		"Your stats are:\n\r\n\r"
		"      Current Stat    Mod\n\r"
		"Strength    : (%2d)     %2d\n\r"
		"Intelligence: (%2d)     %2d\n\r"
		"Wisdom      : (%2d)     %2d\n\r"
		"Dexterity   : (%2d)     %2d\n\r"
		"Constitution: (%2d)     %2d\n\r"
		"Charisma    : (%2d)     %2d\n\r"
		"\n\r"
		"Your roll: %2d, %2d, %2d, %2d, %2d, %2d\n\r"
		"Type <attribute> <number> to assign a number to an attribute.\n\r"
		"Choices are: reroll, clear, and done. ",
		ch->perm_stat[STAT_STR], pc_race_table[ch->race].stats[STAT_STR],
		ch->perm_stat[STAT_INT], pc_race_table[ch->race].stats[STAT_INT],
		ch->perm_stat[STAT_WIS], pc_race_table[ch->race].stats[STAT_WIS],
		ch->perm_stat[STAT_DEX], pc_race_table[ch->race].stats[STAT_DEX],
		ch->perm_stat[STAT_CON], pc_race_table[ch->race].stats[STAT_CON],
		ch->perm_stat[STAT_CHA], pc_race_table[ch->race].stats[STAT_CHA],
		ch->roll_stat[0], ch->roll_stat[1], ch->roll_stat[2],
		ch->roll_stat[3], ch->roll_stat[4], ch->roll_stat[5]);
	send_to_desc(buf, d);
	break;	    

    case CON_GEN_GROUPS:
	send_to_char("\n\r", ch);
	if (!str_cmp(argument, "done")) {
	    if (ch->pcdata->points < 40) {
		ch->Send("You must take at least %d points of skills and groups ",
			40);
		break;
	    }
	    found = FALSE;
	    for (i = 0; weapon_table[i].name != NULL; i++) {
		if (ch->pcdata->learned[*weapon_table[i].gsn] > 0)
		    found = TRUE;
	    }
	    if (!found) {
		ch->Send("You must choose a weapon skill.\n\r");
		break;
	    }
	    ch->Send("Creation points: %d\n\r", ch->pcdata->points);
	    ch->Send("Experience per level: %d\n\r",
		exp_per_level(ch, ch->gen_data->points_chosen));
	    if (ch->pcdata->points < 40)
		ch->train = (40 - ch->pcdata->points + 1) / 2;
	    free_gen_data(ch->gen_data);
	    ch->gen_data = NULL;
	    write_to_buffer(d, "\n\r", 2);
	    write_to_buffer(d,
		"Please pick a weapon from the following choices:\n\r", 0);
	    buf[0] = '\0';
	    for (i =0; weapon_table[i].name != NULL; i++)
		if (ch->pcdata->learned[*weapon_table[i].gsn] > 0) {
		    strcat(buf, weapon_table[i].name);
		    strcat(buf, " ");
		}
	    strcat(buf, "\n\rYour choice? ");
	    write_to_buffer(d, buf, 0);
	    d->connected = CON_READ_MOTD;
	    break;
	}

	if (!parse_gen_groups(ch, argument))
	    ch->Send("Choices are: list, learned, premise, add, drop, info, help, and done.\n\r");
	do_function(ch, &do_help, "menu choice", 0);
	break;


    case CON_CHOOSE_TERM:
	if (!strncmp(argument, "PUEBLOCLIENT", 12)) {
		SET_BIT(DESC_FLAGS(d), DESC_ANSI | DESC_PUEBLO);
		send_to_desc("\n\r`yPueblo Enabled...`n\n\r", d);
        } else {
	    switch (argument[0]) {
		case 'y': case 'Y':
		    SET_BIT(DESC_FLAGS(d), DESC_ANSI);
		    REMOVE_BIT(DESC_FLAGS(d), DESC_PUEBLO);
		    send_to_desc("\n\r", d);
		    break;
		case 'n': case 'N':
		    REMOVE_BIT(DESC_FLAGS(d), DESC_ANSI | DESC_PUEBLO);
		    send_to_desc("\n\r", d);
		    break;
		default:
		    send_to_desc("Please answer (Y/N)? ", d);
		    return;
	    }
	}

        /*
         * Send the greeting.
         */
	{
            extern char * help_greeting1;
	    extern char * help_greeting2;
	    extern char * help_greeting3;
	    extern char * help_greeting4;
	    // You put a dot on the first line of the help so it doesn't
	    // skip the leading spaces in the greeting. Define makes it easy.
	    #define DOTHELP(st)	((st)[0] == '.' ? (st)+1 : (st))

	    switch (number_range(1, 4)) {
		case 1:
			send_to_desc(DOTHELP(help_greeting1), d);
			break;
		case 2:
			send_to_desc(DOTHELP(help_greeting2), d);
			break;
		case 3:
			send_to_desc(DOTHELP(help_greeting3), d);
			break;
		case 4:
			send_to_desc(DOTHELP(help_greeting4), d);
			break;
		default: // Woops, greetings got fubar
			send_to_desc(DOTHELP(help_greeting1), d);
			break;
	    }
	}
        d->connected = CON_GET_NAME;
        break;

    case CON_READ_MOTD:
	ch->next  = char_list;
	char_list = ch;
	reset_char(ch);

	mudlogf(NRM, UMAX(LVL_CODER,ch->invis_level), FALSE, "%s entering game.", RealName(ch));

	if (!COMM_FLAGGED(ch, COMM_NOPUEBLO))
		sound(PUEBLO_START, ch, 0, 0, TO_CHAR, POS_DEAD);
	if (DESC_FLAGGED(ch->desc, DESC_PUEBLO))
		image_to_char(ch, PUEBLO_S_IMG);
	else
		send_to_char("\n\r",ch);

	STATE(d) = CON_PLAYING;
	char_to_room(ch, StartRoom(ch));
	if (ch->level == 0) {
		do_start(ch);
		do_function(ch, &do_help, "newbie info", 0);
		set_player_database(get_player_database()+1);
	}
	act("$n has entered the game.", ch, NULL, NULL, TO_ROOM);
	look_at_room(ch, 0);
	info(ch, 0, "`y[`bINFO`y] %s has entered the game!`n\n\r",ch->name);
	REMOVE_BIT(PLR_FLAGS(ch), PLR_WRITING);

	if (ch->pet != NULL) {
	    char_to_room(ch->pet,ch->in_room);
	    act("$n has entered the game.",ch->pet,NULL,NULL,TO_ROOM);
	}

	do_checknote(ch, "", 0);
	break;

    case CON_NOTE_TO:
	handle_con_note_to(d, argument);
	break;

    case CON_NOTE_SUBJECT:
	handle_con_note_subject(d, argument);
	break;
	
    case CON_NOTE_EXPIRE:
	handle_con_note_expire(d, argument);
	break;

    case CON_NOTE_TEXT:
	handle_con_note_text(d, argument);
	break;
		
    case CON_NOTE_FINISH:
	handle_con_note_finish(d, argument);
	break;

    case CON_MENU:
	    switch (argument[0]) {
		case '0':
			send_to_desc("\n\rAlas, all good things must come to an end.\n\r", d);
			STATE(d) = CON_DISCONNECT;
			break;
		case '1':
			STATE(d) = CON_PLAYING;
			act("$n has entered the game.", ch, NULL, NULL, TO_ROOM);
			ch->Send("\n\r");
			look_at_room(ch, 0);
			break;
		case '2':
			string_append(ch, &ch->description);
			STATE(d) = CON_EXDESC;
			break;
		case '3':
			send_to_desc("\n\rEnter your new last name or 'none': ", d);
			STATE(d) = CON_CHANGE_LNAME;
			break;
		case '4':
			send_to_desc("\n\rEnter your old password: ", d);
			send_to_desc(echo_off_str, d);
			STATE(d) = CON_CHPWD_GETOLD;
			break;
		case '5':
			send_to_desc("\n\rEnter your password for verification: ", d);
			send_to_desc(echo_off_str, d);
			STATE(d) = CON_DELETE_CONF1;
			break;
		default:
			send_to_desc("\n\rThat's not a menu choice.\n\r", d);
			send_to_desc(MENU, d);
			break;
	    }
	    break;
	case CON_CHPWD_GETOLD:
	    if (strcmp(CRYPT(argument, ch->pcdata->pwd), ch->pcdata->pwd)) {
		send_to_desc(echo_on_str, d);
		send_to_desc("\n\rIncorrect password.\n\r", d);
		send_to_desc(MENU, d);
		STATE(d) = CON_MENU;
	    } else {
		send_to_desc("\n\rEnter a new password: ", d);
		STATE(d) = CON_CHPWD_GETNEW;
	    }
	    break;
	case CON_DELETE_CONF1:
	    send_to_desc(echo_on_str, d);
	    if (strcmp(CRYPT(argument, ch->pcdata->pwd), ch->pcdata->pwd)) {
		send_to_desc("\n\rIncorrect password.\n\r", d);
		send_to_desc(MENU, d);
		STATE(d) = CON_MENU;
	    } else {
		send_to_desc("\r\nYOU ARE ABOUT TO DELETE THIS CHARACTER PERMANENTLY.\r\n"
				"ARE YOU ABSOLUTELY SURE?\r\n\r\n"
				"Please type \"yes\" to confirm: ", d);
		STATE(d) = CON_DELETE_CONF2;
	    }
	    break;
	case CON_DELETE_CONF2:
	    if (!str_cmp(argument, "yes")) {
		if (PLR_FLAGGED(ch, PLR_FREEZE)) {
		    send_to_desc("You try to kill yourself, but the ice stops you.\r\n", d);
		    send_to_desc("Character not deleted.\n\r", d);
		    STATE(d) = CON_MENU;
		} else {
		    char buf[MAX_INPUT_LENGTH];
		    save_char_obj(ch);
		    ch->Send("Character '%s' deleted!\n\r"
				"Goodbye.\n\r", RealName(ch));
		    mudlogf(NRM, LVL_STAFF, TRUE, "%s (lev %d) has self-deleted.", RealName(ch), ch->level);
		    sprintf(buf, "%s%s", PLAYER_DIR, capitalize(ch->name));
		    unlink(buf);
		    STATE(d) = CON_DISCONNECT;
		}
	    } else {
		send_to_desc("Character not deleted.\n\r", d);
		send_to_desc(MENU, d);
		STATE(d) = CON_MENU;
	    }
	    break;
    }

    return;
}



/*
 * Parse a name for acceptability.
 */
bool check_parse_name( char *name )
{
    int clan;
    DESCRIPTOR_DATA *d, *dnext;

    /*
     * Reserved words.
     */
    if (is_exact_name(name,
	"all auto immortal self someone something the you demise "
	"balance circle honor none unlinked west east north south down "
	"me eas wes nor sou dow"))
	return FALSE;

    /*
     * Length restrictions.
     */
    if (strlen(name) <  3)
	return FALSE;

#if defined(MSDOS)
    if (strlen(name) >  8)
	return FALSE;
#endif

#if defined(macintosh) || defined(unix)
    if (strlen(name) > 12)
	return FALSE;
#endif

    /*
     * Alphanumerics only.
     * Lock out IllIll twits.
     */
    {
	char *pc;
	bool fIll,
	adjcaps = FALSE,
	cleancaps = FALSE;
 	int total_caps = 0;

	fIll = TRUE;
	for ( pc = name; *pc != '\0'; pc++ )
	{
	    if ( !isalpha(*pc) )
		return FALSE;

	    if (isupper(*pc)) /* ugly anti-caps hack */
	    {
		if (adjcaps)
		    cleancaps = TRUE;
		total_caps++;
		adjcaps = TRUE;
	    }
	    else
		adjcaps = FALSE;

	    if ( LOWER(*pc) != 'i' && LOWER(*pc) != 'l' )
		fIll = FALSE;
	}

	if ( fIll )
	    return FALSE;

	if (cleancaps || (total_caps > 1))
	    return FALSE;
    }

    /*
     * Prevent players from naming themselves after mobs.
     */
    {
	extern MOB_INDEX_DATA *mob_index_hash[MAX_KEY_HASH];
	MOB_INDEX_DATA *pMobIndex;
	int iHash;

	for ( iHash = 0; iHash < MAX_KEY_HASH; iHash++ )
	{
	    for ( pMobIndex  = mob_index_hash[iHash];
		  pMobIndex != NULL;
		  pMobIndex  = pMobIndex->next )
	    {
		if ( is_name( name, pMobIndex->player_name ) )
		    return FALSE;
	    }
	}
    }

    return TRUE;
}



/*
 * Look for link-dead player to reconnect.
 */
bool check_reconnect(DESCRIPTOR_DATA *d, char *name, bool fConn) {
    CHAR_DATA *ch;

    for ( ch = char_list; ch != NULL; ch = ch->next )
    {
	if ( !IS_NPC(ch)
	&&   (!fConn || ch->desc == NULL)
	&&   !str_cmp( d->character->name, ch->name ) )
	{
	    if (fConn == FALSE) {
		free_string( d->character->pcdata->pwd );
		d->character->pcdata->pwd = str_dup( ch->pcdata->pwd );
	    } else {
		free_char( d->character );
		d->character = ch;
		ch->desc	 = d;
		ch->timer	 = 0;
		send_to_char(
		    "Reconnecting. Type replay to see missed tells.\n\r", ch );
		act( "$n has reconnected.", ch, NULL, NULL, TO_ROOM );
		mudlogf(NRM, LVL_STAFF, TRUE, "%s [%s] reconnecting.",
			RealName(ch), d->host);
		REMOVE_BIT(PLR_FLAGS(ch), PLR_WRITING);
		d->connected = CON_PLAYING;
		if (ch->pcdata->in_progress)
		    ch->Send("You have a note in progress. Type 'note write' to continue it.\n\r");
	    }
	    return TRUE;
	}
    }

    return FALSE;
}



/*
 * Check if already playing.
 */
bool check_playing(DESCRIPTOR_DATA *d, char *name) {
    DESCRIPTOR_DATA *dold;

    for (dold = descriptor_list; dold; dold = dold->next) {
	if ( dold != d
	&&   dold->character != NULL
	&&   dold->connected != CON_GET_NAME
	&&   dold->connected != CON_GET_OLD_PASSWORD
	&&   !str_cmp( name, dold->original
	         ? dold->original->name : dold->character->name ) )
	{
	    write_to_buffer( d, "That character is already playing.\n\r",0);
	    write_to_buffer( d, "Do you wish to connect anyway (Y/N)?",0);
	    d->connected = CON_BREAK_CONNECT;
	    return TRUE;
	}
    }

    return FALSE;
}

void sig_handler(int sig) {
    pid_t fpid;

    signal(sig, SIG_DFL);
    switch((fpid = fork())) {
	case 0:
	    mudlogf(BRF, LVL_STAFF, TRUE, "sig_handler: Crash Detected");
	    wait(NULL);
	    crash_copyover();
	    break;
	case -1:
	    perror("sig_handler: fork");
	    break;
	default:
	    raise(sig);
    }
}

void init_signals(void) {
    signal(SIGBUS, sig_handler);
    signal(SIGTERM, sig_handler);
    signal(SIGABRT, sig_handler);
    signal(SIGSEGV, sig_handler);
}

void crash_copyover(void) {
    FILE *fp;
    SInt32 i = 0;
    time_t ct = time(0);
    char buf[100], buf2[100];
    DESCRIPTOR_DATA *d, *d_next;
    char *time_s = asctime(localtime(&ct));

    *(time_s + strlen(time_s) - 1) = '\0';

    fclose(fpReserve);
    if ((fp = fopen(LCMD_FILE, "a")) != NULL) {
	fprintf(fp, "%-19.19s :: Last Command: %s\n", time_s, *last_command ? last_command : "BOOT ERROR");
	fclose(fp);
    }
    fpReserve = fopen(NULL_FILE, "r");

    if (!(fp = fopen(COPYOVER_FILE, "w"))) {
	for (d = descriptor_list; d != NULL; d = d_next) {
	    if (d->character) {
		save_char_obj(d->character);
		write_to_descriptor(d, "\n\r*** WARNING *** The mud has crashing, saving and rebooting.\n\r", 0);
	    }
	    d_next = d->next;
	    close_socket(d);
	}
	exit(1);
    }

    for (d = descriptor_list; d != NULL; d = d_next) {
	CHAR_DATA *ch = Original(d);
	d_next = d->next;

	if (!d->character || STATE(d) > CON_PLAYING) {
	    write_to_descriptor(d, "\n\rSorry, we are rebooting. Come back in a few minutes.\n\r", 0);
	    close_socket(d);
	} else {
	    write_to_descriptor(d, "\n\r*** WARNING *** The mud has crashed, saving and attempting copyover.\n\r", 0);
	    fprintf(fp, "%d %d %s %s\n", d->descriptor, d->flags, ch->name, d->host);
	    save_char_obj(ch);
	    if (d->out_compress)
		toggle_compression(d);
	}
    }

    fprintf(fp, "-1");
    fclose(fp);
    fclose(fpReserve);

    sprintf(buf, "%d", port);
    sprintf(buf2, "%d", control);
    execl(EXE_FILE, "rogue", buf, "cboot", buf2, (char *)NULL);
    exit(1);
}

void stop_idling( CHAR_DATA *ch ) {
    if ( ch == NULL
    ||   ch->desc == NULL
    ||   ch->desc->connected != CON_PLAYING
    ||   ch->was_in_room == NULL 
    ||   ch->in_room != get_room_index(ROOM_VNUM_LIMBO))
	return;

    ch->timer = 0;
    char_from_room( ch );
    char_to_room( ch, ch->was_in_room );
    ch->was_in_room	= NULL;
    act( "$n has returned from the void.", ch, NULL, NULL, TO_ROOM );
    return;
}

void send_to_desc(const char *txt, DESCRIPTOR_DATA *d) {
    const char	*point;
    char	*point2;
    char	buf[MAX_STRING_LENGTH*4];
    int		skip = 0;

    buf[0] = '\0';
    point2 = buf;
 
    if (txt && d) {
	if (DESC_FLAGGED(d, DESC_ANSI)) {
	    for (point = txt; *point; point++) {
		if (*point == '`') {
		    point++;
		    skip = colour(*point, NULL, point2);
		    while (skip-- > 0)
			++point2;
		    continue;
		}
		    *point2 = *point;
		    *++point2 = '\0';
	    }
	    *point2 = '\0';
	    write_to_buffer(d, buf, point2 - buf);
	} else {
	    for (point = txt; *point; point++) {
		if (*point == '`') {
		    point++;
		    continue;
		}
		*point2 = *point;
		*++point2 = '\0';
	    }
	    *point2 = '\0';
	    write_to_buffer(d, buf, point2 - buf);
	}
    }
    return;
}

/*
 * Write to one char.
 */
void send_to_all(const char *txt)
{
	DESCRIPTOR_DATA *d;

	if (!txt || !*txt)
	 return;

	for ( d = descriptor_list; d != NULL; d = d->next ) {
		if ( d->character != NULL && d->connected == CON_PLAYING)
//			write_to_buffer(d, txt, strlen(txt) );
			send_to_desc(txt, d);
	}
}

void send_to_char_bw( const char *txt, CHAR_DATA *ch )
{
    if ( txt != NULL && ch->desc != NULL )
        write_to_buffer( ch->desc, txt, strlen(txt) );
    return;
}

/*
 * Write to one char, new colour version, by Lope.
 */
void send_to_char(const char *txt, CHAR_DATA *ch) {
    const	char 	*point;
    		char 	*point2;
    		char 	buf[ MAX_STRING_LENGTH*4 ];
		int	skip = 0;

    buf[0] = '\0';
    point2 = buf;

    if (txt && ch->desc) {
	if (DESC_FLAGGED(ch->desc, DESC_ANSI)) {
	    for (point = txt; *point; point++) {
		if (*point == '`') {
		    point++;
		    skip = colour(*point, ch, point2);
		    while(skip-- > 0)
			++point2;
		    continue;
		}
		*point2 = *point;
		*++point2 = '\0';
	    }			
	    *point2 = '\0';
            write_to_buffer(ch->desc, buf, point2 - buf);
	} else {
	    for (point = txt; *point; point++) {
		if (*point == '`') {
		    point++;
		    continue;
		}
		*point2 = *point;
		*++point2 = '\0';
	    }
	    *point2 = '\0';
            write_to_buffer( ch->desc, buf, point2 - buf );
	}
    }
    return;
}

/*
 * Send a page to one char.
 */
void page_to_char_bw( const char *txt, CHAR_DATA *ch )
{
    if ( txt == NULL || ch->desc == NULL)
	return;

    if (ch->lines == 0 )
    {
	send_to_char(txt,ch);
	return;
    }
	
#if defined(macintosh)
	send_to_char(txt,ch);
#else
    ch->desc->showstr_head = (char *)alloc_mem(strlen(txt)+1);
    strcpy(ch->desc->showstr_head,txt);
    ch->desc->showstr_point = ch->desc->showstr_head;
    show_string(ch->desc,"");
#endif
}

/*
 * Page to one char, new colour version, by Lope.
 */
void page_to_char( const char *txt, CHAR_DATA *ch )
{
    const	char	*point;
    		char	*point2;
    		char	buf[ MAX_STRING_LENGTH * 4 ];
		int	skip = 0;

    buf[0] = '\0';
    point2 = buf;
    if( txt && ch->desc )
	{
	    if (DESC_FLAGGED(ch->desc, DESC_ANSI))
	    {
		for( point = txt ; *point ; point++ )
	        {
		    if( *point == '`' )
		    {
			point++;
			skip = colour( *point, ch, point2 );
			while( skip-- > 0 )
			    ++point2;
			continue;
		    }
		    *point2 = *point;
		    *++point2 = '\0';
		}			
		*point2 = '\0';
		ch->desc->showstr_head = (char *)alloc_mem(strlen(buf)+1);
		strcpy( ch->desc->showstr_head, buf );
		ch->desc->showstr_point = ch->desc->showstr_head;
		show_string( ch->desc, "" );
	    }
	    else
	    {
		for( point = txt ; *point ; point++ )
	        {
		    if( *point == '`' )
		    {
			point++;
			continue;
		    }
		    *point2 = *point;
		    *++point2 = '\0';
		}
		*point2 = '\0';
		ch->desc->showstr_head = (char *)alloc_mem(strlen(buf)+1);
		strcpy( ch->desc->showstr_head, buf );
		ch->desc->showstr_point = ch->desc->showstr_head;
		show_string( ch->desc, "" );
	    }
	}
    return;
}


/* string pager */
void show_string(struct descriptor_data *d, char *input)
{
    char buffer[4*MAX_STRING_LENGTH];
    char buf[MAX_INPUT_LENGTH];
    register char *scan, *chk;
    int lines = 0, toggle = 1;
    int show_lines;

    one_argument(input,buf);
    if (buf[0] != '\0')
    {
	if (d->showstr_head)
	{
	    free_mem(d->showstr_head,strlen(d->showstr_head));
	    d->showstr_head = 0;
	}
    	d->showstr_point  = 0;
	return;
    }

    if (d->character)
	show_lines = d->character->lines;
    else
	show_lines = 0;

    for (scan = buffer; ; scan++, d->showstr_point++)
    {
	if (((*scan = *d->showstr_point) == '\n' || *scan == '\r')
	    && (toggle = -toggle) < 0)
	    lines++;

	else if (!*scan || (show_lines > 0 && lines >= show_lines))
	{
	    *scan = '\0';
	    write_to_buffer(d,buffer,strlen(buffer));
	    for (chk = d->showstr_point; isspace(*chk); chk++);
	    {
		if (!*chk)
		{
		    if (d->showstr_head)
        	    {
            		free_mem(d->showstr_head,strlen(d->showstr_head));
            		d->showstr_head = 0;
        	    }
        	    d->showstr_point  = 0;
    		}
	    }
	    return;
	}
    }
    return;
}
	

/* quick sex fixer */
void fix_sex(CHAR_DATA *ch)
{
    if (ch->sex < 0 || ch->sex > 2)
    	ch->sex = IS_NPC(ch) ? 0 : ch->pcdata->true_sex;
}

/*
 * The following two functions are real annoying but useful.
 * They help with color counting by either returning the number
 * of color codes or the length of the string without color.
 * These are useful when you want the raw number of a string
 * that will be passed through colorconv which turns `n into an
 * ASCI escape color code, or if color is disabled they are stripped.
 * The annoying part is that every time you think of an easy way to
 * code it so it's not going through 100 if/elses you find another case.
 */

int colorcount( char *string )
{
    int i, color=0;
    check_color_string(string);

    for (i=0; i < strlen(string); i++) {
	if (string[i] == '`' && string[i+1] == '`')
		i++;
	else if (string[i] == '`' && string[i+1] != '`' && string[i+1] != '\0')
		color++;
    }
    return (color*2); // return actual length
}

int rstrlen( char *string )
{
    int i, count=0;
    check_color_string(string);

    for (i=0; i < strlen(string); i++) {
	if (string[i] != '`') {
		count++;
	} else if (string[i] == '`' && string[i+1] == '`') {
		i++;
		count++;
	} else if (string[i] == '`' && string[i+1] != '\0') {
		i++;
	}
    }
    return count;
}

/*
 * Checks the end of a string for single color codes.
 */
void check_color_string(char *string)
{
    int i=strlen(string)-1;

    if (IS_NULLSTR(string))
	return;

    if (string[i] == '`' && string[i-1] != '`' && string[i+1] == '\0')
	string[i] = '\0';
    return;
}

char *strip_color(const char *txt) {
    const char	*point;
    char	*point2;
    char	buf[MAX_STRING_LENGTH*4];

    buf[0] = '\0';
    point2 = buf;
    if (txt) {
	for (point = txt; *point; point++) {
	    if (*point == '`') {
		point++;
		continue;
	    }
	    *point2 = *point;
	    *++point2 = '\0';
	}
	*point2 = '\0';
	buf[point2 - buf] = '\0';
	return str_dup(buf);
    }
    return "(NULL)";
}
    
char *strip_color2(const char *stxt) {
    int i=0, c=0;
    char buf[MAX_STRING_LENGTH*2];

    if (stxt[0] != '\0')
    {
	for (i=0;i<strlen(stxt);i++)
	{
		if (stxt[i] == '`' && stxt[i+1] != '`' && stxt[i-1] != '`')
		{
		    i++;
		    continue;
		}
		buf[c] = stxt[i];
		c++;
	}
	buf[c] = '\0';
	return str_dup(buf);
    }
    return "(NULL)";
}


void perform_act(const char *orig, CHAR_DATA *ch, const void *arg1,
	const void *arg2, CHAR_DATA *to, bool Relation, bool RName)
{
    static char * const he_she  [] = { "it",  "he",  "she" };
    static char * const him_her [] = { "it",  "him", "her" };
    static char * const his_her [] = { "its", "his", "her" };

    OBJ_DATA *obj1 = (OBJ_DATA *) arg1;
    OBJ_DATA *obj2 = (OBJ_DATA *) arg2;
    CHAR_DATA *vch = (CHAR_DATA *) arg2;
    int relation = RELATION_NONE;
    extern char *relation_colors;
    const char *str, *i = NULL;
    char *point, *pbuff,
	 buffer[MAX_STRING_LENGTH*2], buf[MAX_STRING_LENGTH];

    point = buf;
    str   = orig;
    while (*str != '\0') {
	if (*str != '$') {
	    *point++ = *str++;
	    continue;
	}
	++str;
	i = "<@@@>";
	if (!arg2 && *str >= 'A' && *str <= 'Z') {
	    mudlogf(BRF, LVL_STAFF, TRUE, "SYSERR: missing arg2 for code %d in act().", *str);
	    i = "<@@@>";
	} else {
	    switch (*str) {
		case 't':	i = (char *) arg1;	break;
		case 'T':	i = (char *) arg2;	break;
		case 'n':
			if (Relation)
				relation = ch->GetRelation(to);
			if (!RName)
				i = PERS(ch, to);
			else
				i = PERS2(ch, to);
			break;
		case 'N':
			if (Relation)
				relation = vch->GetRelation(to);
			if (!RName)
				i = PERS(vch, to);
			else
				i = PERS2(vch, to);
			break;
		case 'e':	i = he_she[URANGE(0, ch->sex, 2)];	break;
		case 'E':	i = he_she[URANGE(0,vch->sex, 2)];	break;
		case 'm':	i = him_her[URANGE(0, ch->sex, 2)];	break;
		case 'M':	i = him_her[URANGE(0,vch->sex, 2)];	break;
		case 's':	i = his_her[URANGE(0, ch->sex, 2)];	break;
		case 'S':	i = his_her[URANGE(0,vch->sex, 2)];	break;
		case 'o':	i = can_see_obj(to, obj1)
					? fname(obj1->name) : "something";
				break;
		case 'O':	i = can_see_obj(to, obj2)
					? fname(obj2->name) : "something";
				break;
		case 'p':
			i = can_see_obj(to, obj1) 
				? obj1->short_descr : "something";
			break;
		case 'P':
			i = can_see_obj(to, obj2)
				? obj2->short_descr : "something";
			break;
		case 'd':
			if (arg2 == NULL || ((char *) arg2)[0] == '\0')
				i = "door";
			else {
				char fname[MAX_INPUT_LENGTH];
				one_argument((char *)arg2, fname);
				i = fname;
			}
			break;
		default:
			i = "<@@@>";
			mudlogf(BRF, LVL_STAFF, TRUE,
			"SYSERR: Illegal $-code to perform_act(): %c", *str);
			break;
	    }
	}
	if (relation != RELATION_NONE) {
		*point++ = '`';
		*point++ = relation_colors[relation];
	}

	++str;
	while ((*point = *(i++)))
		point++;

	if (relation != RELATION_NONE) {
		*point++ = '`';
		*point++ = 'n';
		relation = RELATION_NONE;
	}
    }

    *point++ = '\n';
    *point++ = '\r';
    *point   = '\0';
    buf[0] = UPPER(buf[0]);
    pbuff = buffer;
    colourconv(pbuff, buf, to);

    if (to->desc) {
    if (STATE(to->desc) == CON_PLAYING)
	write_to_buffer(to->desc, buffer, 0);
    } else if (MOBtrigger)
	mp_act_trigger(buf, to, ch, arg1, arg2, TRIG_ACT);
    return;
}

#define SENDOK(ch)	\
	((IS_NPC(ch) || ((ch)->desc && (STATE(ch->desc) == CON_PLAYING))) && \
	((ch)->position >= min_pos))

void act_new( const char *format, CHAR_DATA *ch, const void *arg1, 
	      const void *arg2, int type, int min_pos, bool Rel, bool RName)
{
    DESCRIPTOR_DATA *d;
    ROOM_INDEX_DATA *room;
    CHAR_DATA *to = (CHAR_DATA *)arg2;

    if(!format || !*format)
	return;

    if (IS_SET(type, TO_CHAR)) {
	if (ch && SENDOK(ch))
		perform_act(format, ch, arg1, arg2, ch, Rel, RName);
    }

    if (IS_SET(type, TO_VICT)) {
	if (to && SENDOK(to) && to != ch)
		perform_act(format, ch, arg1, arg2, to, Rel, RName);
    }

    if (IS_SET(type, TO_ALLNOTVICT)) {
	for (d = descriptor_list; d; d = d->next) {
		CHAR_DATA *vch = Original(d);
		if (vch && SENDOK(vch) && (vch != ch) && (vch != to))
			perform_act(format, ch, arg1, arg2, vch, Rel, RName);
	}
    }

    if (IS_SET(type, TO_ZONE | TO_ALL)) {
	for (d = descriptor_list; d; d = d->next) {
		CHAR_DATA *vch = Original(d);
		if (vch && SENDOK(vch) && (vch != ch) &&
		((IS_SET(type, TO_ALL) || (IN_ROOM(vch)->area == IN_ROOM(ch)->area))))
			perform_act(format, ch, arg1, arg2, vch, Rel, RName);
	}
    }

    if (IS_SET(type, TO_ROOM | TO_NOTVICT | TO_ALLROOM)) {
	OBJ_DATA *obj1 = (OBJ_DATA *)arg1;
	OBJ_DATA *obj2 = (OBJ_DATA *)arg2;
	if (ch && IN_ROOM(ch) != NULL)
		room = IN_ROOM(ch);
	else if (obj1 && IN_ROOM(obj1) != NULL)
		room = IN_ROOM(obj1);
	else if (obj2 && IN_ROOM(obj2) != NULL)
		room = IN_ROOM(obj2);
	else {
		mudlogf(BRF, LVL_STAFF, TRUE, "SYSERR: no valid target to act()");
		return;
	}
	for (to = room->people; to; to = to->next_in_room) {
		if (SENDOK(to) && (IS_SET(type, TO_ALLROOM) || (to != ch))
		&& (IS_SET(type, TO_ROOM | TO_ALLROOM)
		|| (to != (CHAR_DATA *)arg2)))
			perform_act(format, ch, arg1, arg2, to, Rel, RName);
	}
    }
    return;
}

/*
 * Macintosh support functions.
 */
#if defined(macintosh)
int gettimeofday( struct timeval *tp, void *tzp )
{
    tp->tv_sec  = time( NULL );
    tp->tv_usec = 0;
}
#endif

SInt32 CHAR_DATA::Send(const char *messg, ...) {
    va_list args;
    char send_buf[MAX_STRING_LENGTH];
    SInt32 length = 0;

    if (!messg || !*messg)
	return 0;

    va_start(args, messg);
    length += vsprintf(send_buf, messg, args);
    va_end(args);

    if (this->desc)	send_to_char(send_buf, this);
    else 		act(send_buf, this, 0, 0, TO_CHAR);

    return length;
}

SInt32 ROOM_INDEX_DATA::Send(const char *messg, ...) {
    CHAR_DATA *i;
    va_list args;
    SInt32 length = 0;
    DESCRIPTOR_DATA *d;
    char send_buf[MAX_STRING_LENGTH];

    if (!messg || !*messg || !this || !this->people)
	return 0;

    va_start(args, messg);
    length += vsprintf(send_buf, messg, args);
    va_end(args);

    for (i = this->people; i != NULL; i = i->next_in_room) {
	d = i->desc;
	if (d && (STATE(d) == CON_PLAYING) && i->position > POS_SLEEPING)
		send_to_char(send_buf, i);
    }
    return length;
}

void log(const char *format, ...) {
    va_list args;
    time_t ct = time(0);
    char *time_s = asctime(localtime(&ct));

    *(time_s + strlen(time_s) - 1) = '\0';

   fprintf(stderr, "%-19.19s :: ", time_s);

    va_start(args, format);
    vfprintf(stderr, format, args);
    va_end(args);

    fprintf(stderr, "\n");
    fflush(stderr);
}

void Free_Error(char * file, int line) {
	mudlogf(BRF, LVL_SRSTAFF, TRUE, "CODEERR: NULL pointer in file %s:%d", file, line);
}

void mudlogf(SInt8 type, UInt32 level, bool file, const char *format, ...) {
    va_list args;
    CHAR_DATA *ch;
    DESCRIPTOR_DATA *d;
    time_t ct = time(0);
    char tp, *time_s = asctime(localtime(&ct));
    char *mudlog_buf = (char *)malloc(MAX_STRING_LENGTH);

    *(time_s + strlen(time_s) - 1) = '\0';

    if (file)
	fprintf(stderr, "%-19.19s :: ", time_s);

    va_start(args, format);
    if (file)
	vfprintf(stderr, format, args);
    vsprintf(mudlog_buf, format, args);
    va_end(args);

    if (file)	fprintf(stderr, "\n");
    fflush(stderr);

    for (d = descriptor_list; d != NULL; d = d->next) {
	ch = d->original ? d->original : d->character;
	if (STATE(d) == CON_PLAYING) {
		tp = ((PLR_FLAGGED(ch, PLR_LOG1) ? 1 : 0) +
			(PLR_FLAGGED(ch, PLR_LOG2) ? 2 : 0));
		if ((ch->level >= level) && (tp >= type))
			ch->Send("`g[ %s ]`n\n\r", mudlog_buf);
	}
    }
    FREE(mudlog_buf);
}

int colour(char type, CHAR_DATA *ch, char *string) {
    char	code[ 20 ];
    char	*p = '\0';

    if (ch && IS_NPC(ch))
	return( 0 );

    switch( type )
    {
	default:
	    sprintf( code, CLEAR );
	    break;
	case 'n':
	    sprintf( code, CLEAR );
	    break;
	case 'b':
	    sprintf( code, C_BLUE );
	    break;
	case 'c':
	    sprintf( code, C_CYAN );
	    break;
	case 'g':
	    sprintf( code, C_GREEN );
	    break;
	case 'm':
	    sprintf( code, C_MAGENTA );
	    break;
	case 'r':
	    sprintf( code, C_RED );
	    break;
	case 'w':
	    sprintf( code, C_WHITE );
	    break;
	case 'y':
	    sprintf( code, C_YELLOW );
	    break;
	case 'k':
	    sprintf( code, C_BLACK );
	    break;
	case 'B':
	    sprintf( code, C_B_BLUE );
	    break;
	case 'C':
	    sprintf( code, C_B_CYAN );
	    break;
	case 'G':
	    sprintf( code, C_B_GREEN );
	    break;
	case 'M':
	    sprintf( code, C_B_MAGENTA );
	    break;
	case 'R':
	    sprintf( code, C_B_RED );
	    break;
	case 'W':
	    sprintf( code, C_B_WHITE );
	    break;
	case 'Y':
	    sprintf( code, C_B_YELLOW );
	    break;
	case 'K':
	    sprintf( code, C_B_GREY );
	    break;
	case '*':
	    sprintf( code, "%c", 007 );
	    break;
	case '-':
            sprintf( code, "%c", '~' );
            break;
	case '/':
	    sprintf( code, "%c", 012 );
	    break;
	case 'f':
		sprintf( code, FLASHING );
		break;
	case 'i':
		sprintf( code, INVERSE );
		break;
	case '0':
		sprintf( code, BKBLK );
		break;
	case '1':
		sprintf( code, BKRED );
		break;
	case '2':
		sprintf( code, BKGRN );
		break;
	case '3':
		sprintf( code, BKYEL );
		break;
	case '4':
		sprintf( code, BKBLU );
		break;
	case '5':
		sprintf( code, BKMAG );
		break;
	case '6':
		sprintf( code, BKCYN );
		break;
	case '7':
		sprintf( code, BKWHT );
		break;
	case '`':
	    sprintf( code, "%c", '`' );
	    break;
	case '.':
	switch(number_range(1,14)) {
	    default:
        	sprintf( code, CLEAR );
        	break;
	    case 1:
		sprintf( code, C_BLUE );
		break;
	    case 2:
		sprintf( code, C_CYAN );
		break;
	    case 3:
		sprintf( code, C_GREEN );
		break;
	    case 4:
		sprintf( code, C_MAGENTA );
		break;
	    case 5:
		sprintf( code, C_RED );
		break;
	    case 6:
		sprintf( code, C_WHITE );
		break;
	    case 7:
		sprintf( code, C_YELLOW );
		break;
	    case 8:
		sprintf( code, C_B_BLUE );
		break;
	    case 9:
		sprintf( code, C_B_CYAN );
		break;
	    case 10:
		sprintf( code, C_B_GREEN );
		break;
	    case 11:
		sprintf( code, C_B_MAGENTA );
		break;
	    case 12:
		sprintf( code, C_B_RED );
		break;
	    case 13:
		sprintf( code, C_B_WHITE );
		break;
	    case 14:
		sprintf( code, C_B_YELLOW );
		break;
	}
    }

    p = code;
    while (*p != '\0') {
	*string = *p++;
	*++string = '\0';
    }
    return(strlen(code));
}

void colourconv( char *buffer, const char *txt, CHAR_DATA *ch )
{
    const	char	*point;
		int	skip = 0;

    if( ch->desc && txt )
    {
	if (DESC_FLAGGED(ch->desc, DESC_ANSI))
	{
	    for( point = txt ; *point ; point++ )
	    {
		if( *point == '`' )
		{
		    point++;
		    skip = colour( *point, ch, buffer );
		    while( skip-- > 0 )
			++buffer;
		    continue;
		}
		*buffer = *point;
		*++buffer = '\0';
	    }			
	    *buffer = '\0';
	}
	else
	{
	    for( point = txt ; *point ; point++ )
	    {
		if( *point == '`' )
		{
		    point++;
		    continue;
		}
		*buffer = *point;
		*++buffer = '\0';
	    }
	    *buffer = '\0';
	}
    }
    return;
}

#define MIN_PWD_LENGTH	8

/***********************************************************************
 * Genetate Key/Password                                               *
 * This thing has a bug somewhere but I'm too stupid to figure it out. *
 * I started it out as a (char *) but for some reason it wont print it.*
 * I got tired of it and resolved that it works by converting the buf  *
 * so let that be that, and hoooya!
 * - Mendanbar                                                         *
 ***********************************************************************/

void generate_key(char *buf) {
    UInt16 count;
    const char letters[63]="aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ1234567890";

    buf[0] = '\0';
    for (count = 0; count < MIN_PWD_LENGTH; count++) {
	*buf = letters[number_range(0,61)];
	*++buf = '\0';
    }
    *buf = '\0';
    return;
}