/*
 *
 * smain.c -- main program
 *
 * This code is copyright 1994 by James A. Cherry, jac@doe.carleton.ca.
 * It is not to be redistributed or modified without his permission.
 *
 */

#include "scrab.h"
#include "globals.h"
#include "socket.h"
#include "botutil.h"
#include "proto.h"

int main()
{
	int leave, status;
	int i;

	set_up_window();
#ifdef LOGFILE
#ifdef POSLDOOM
	logfile = fopen( "plogfile", "w" );
#else
	logfile = fopen( "mlogfile", "w" );
#endif
#endif
	print_version();

	read_words();
	dict_changed = 0;
	read_blacklist();
	init_stuff();

#ifdef CURSES
	printw( "Trying to establish socket...\n" );
	refresh();
#endif
#ifdef POSLDOOM
	sockp = client_init( "riemann.math.utoronto.ca", 7777, 2 );
#else
	sockp = client_init( "seabass.st.usm.edu", 7777, 2 );
#endif
	if( sockp == -1 ) {
#ifdef CURSES
		printw( "%s\n", socket_error );
#endif
#ifdef LOGFILE
		fprintf( logfile, "%s\n", socket_error ); fflush( logfile );
#endif
		exit_window();
		exit( 20 );
	} else {
#ifdef CURSES
		printw( "Socket established\n" );
#endif
	}
	leave = 0;

	print_version();
	init_board();
	print_board();

	while( leave == 0 ) {
		usleep( 500000 );
		currticks++;
		if( currstate > IDLE_FOR_GAME && currticks == 3000 )
			warn_of_expiry();
		if( currstate > IDLE_FOR_GAME && currticks == 3600 )
			expire();
		status = do_read( sockp );
		if( status < 0 && status != READ_NODATA ) {
			if( status == READ_EOF ) {
				leave = 1;
				continue;
			} else {
#ifdef CURSES
				move( 17, 0 );
				printw( "*** Socket error: %s\n", socket_error );
				printw( "*** Read error, code %d\n", status );
				refresh();
#endif
#ifdef LOGFILE
				fprintf( logfile, "*** Socket error: %s\n", socket_error );
				fprintf( logfile, "*** Read error, code %d\n", status );
				fflush( logfile );
#endif
			}
		} else if( status != READ_NODATA ) {
			process_read_data();
		}
		check_command_queue();
		if( lookingforboard != LFB_NONE ) {
			look_for_board();
			goto skipstates;
		}
		if( currstate >= IDLE_FOR_GAME )
			generic_message_check();
		for( i = 0; i < NUM_STATES; i++ ) {
			if( state_table[i].state == currstate ) {
				(*state_table[i].function)();
			}
		}
skipstates:
	}

#ifdef LOGFILE
	fprintf( logfile, "Closing socket\n" ); fflush( logfile );
#endif
	close( sockp );
	exit_window();
	return( 0 );
}

