#include <rpc/rpc.h>
#include <stdio.h>
#include "remote.h"
#include "othello.h"
#include "global.h"
#include "io.h"


int   connected_progs = -1;
int   color_prog1;
int   color_prog2;
int   program_to_move;
int   move_exists = 0;
int   the_move;
State   playstate;

/* ================================================================ */


int *
connect_1(cd, rq)
connect_data   *cd;
struct svc_rec  *rq;
{
    static int result;
    int   foo = 1;
    char *bar = "bar";

    if (connected_progs == -1) {
	printf("Server initializing.\n");
	fflush(stdout);
	init_io(&foo, &bar);
	++connected_progs;
	printf("Server initialized\n");
	fflush(stdout);
    }
	
    if (++connected_progs == 1) {
	printf("First program connecting. \n");
	fflush(stdout);
	resetstate(&playstate);
	init_io_for_one_game();
	move_exists = 0;
	color_prog1 = cd->color;
	if (color_prog1 == BLACK) {
	    mycolor = BLACK;
	    yourcolor = WHITE;
	} else {
	    mycolor = WHITE;
	    yourcolor = BLACK;
	}
	result = 1;
    } else {
	printf("Second program connecting. \n");
	fflush(stdout);
	color_prog2 = cd->color;
	if (color_prog1 == color_prog2) {
	    --connected_progs;
	    result = 0;
	} else {
	    if (color_prog2 == BLACK)
		program_to_move = 2;
	    else
		program_to_move = 1;
	    result = 2;
	}
    }
    return &result;
}


void *
disconnect_1(pn, rq)
int             *pn;
struct svc_rec  *rq;
{
    printf("Program disconnecting. \n");
    fflush(stdout);
    --connected_progs;
    return (void *) disconnect_1;
}


void *
put_move_1(md, rq)
move_data   *md;
struct svc_rec  *rq;
{
    printf("Got move %d from %d. \n", md->square, md->progno);
    fflush(stdout);
    move_exists = 1;
    the_move = md->square;
    program_to_move = 3 - md->progno;
    do_move(&playstate, the_move, md->progno == 1 ? MYCOLOR : YOURCOLOR);
    print_state(&playstate);
    if (md->progno == 1)
	print_my_move(the_move);
    else
	print_your_move(the_move);
    
    return (void *) put_move_1;
}


int *
get_move_1(progno, rq)
int *progno;
struct svc_rec  *rq;
{
    static int result;


    if (move_exists && *progno == program_to_move) {
	printf("Giving out move %d. \n", the_move);
	fflush(stdout);
	result = the_move;
	move_exists = 0;
    } else {
	printf("Refused to give out move. \n");
	fflush(stdout);
	result = NOMOVE;
    }
    
    return &result;
}
