/* Copyright 1989, 1990 by James Aspnes, David Applegate, and Bennet Yee */
/* See the file COPYING for distribution information */
#include <stdio.h>
#include <ctype.h>

#include "interface.h"

int shutdown_flag = 0;

void notify(datum victim, const char *buf)
{
    printf("%d: %s\n", victim, buf);
}

void emergency_shutdown(void)
{
    puts("emergency_shutdown() called");
}

void force_disconnect(datum player)
{
    printf("force_disconnect(%d) called\n", player);
}

static void command_loop(void)
{
    char buf[MAX_COMMAND_LEN+1];
    datum connected_to = NOTHING;
    char *nl;
    char *name;
    char *password;

    while(!shutdown_flag) {
	fgets(buf, MAX_COMMAND_LEN, stdin);
	/* nuke that damned newline */
	if(*(nl = buf + strlen(buf)-1) == '\n') *nl = '\0';

	if(connected_to != NOTHING) {
	    if(!strcmp(buf, QUIT_COMMAND)) {
		printf("Disconnecting from %d\n", connected_to);
		disconnect_player(connected_to);
		connected_to = NOTHING;
	    } else {
		parse_command(connected_to, buf);
	    }
	} else {
	    /* get name and password */
	    for(name = buf; *name && isspace(*name); name++);
	    for(password = name; *password && !isspace(*password); password++);
	    if(*password) *password++ = '\0';
	    for(; *password && isspace(*password); password++);

	    connected_to = connect_player(name, password);
	    if(connected_to != NOTHING) {
		printf("Connected to %d\n", connected_to);
	    } else {
		puts("Failed connect.");
	    }
	}
    }

    return;
}

void main(int argc, char **argv)
{
    if (argc < 3) {
	fprintf (stderr, "Usage: %s infile dumpfile\n", *argv);
	exit (1);
    }
    if (init_game (argv[1], argv[2]) < 0) {
	fprintf (stderr, "Couldn't load %s!\n", argv[1]);
	exit (2);
    }

    command_loop();

    dump_database();
    exit (0);
}