#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include "libconq.h"

static int game_N=0;
static int st[MAX_N+1];

static int lib_usage = 0;
static char lib_txt[1024];

static void lib_error(int code, char *s)
{
    FILE *f;
    f=fopen("libconq.out","w");
    fprintf(f,"%s\n",s);
    fclose(f);
    exit(code);
}

void start(int *N, int *stairs)
{
    FILE *f;
    int i;

    if (lib_usage!=0) lib_error(1,"start() called too many times");
    lib_usage++;

    if ((f=fopen("libconq.dat","r"))==NULL)
    {
			  srand(time(NULL));
			  (*N)=2 + rand()%(MAX_N-2);
				stairs[1]=0;
			  for (i=2;i<=(*N);i++) stairs[i]=rand()%(i*i);
    }
    else
    {
				fscanf(f,"%d ",N);
				for (i=1;i<=(*N);i++) fscanf(f,"%d ",&stairs[i]);
				fclose(f);
    }
  
    game_N=(*N);
    for (i=1;i<=(*N);i++) st[i]=stairs[i];
}

static int decide(int *a)
{
    return (1+rand()%2);  
}

int step(int *subset)
{
    int choice,i,wrong,cnt;

    if (lib_usage==0) lib_error(1,"call start() first!");
    lib_usage++;

    /* check if a is a valid subset */
    wrong=0;
    for (i=1;i<=game_N;i++)
    {
	if ((subset[i]<0) || (subset[i]>st[i])) wrong=i;
	if (wrong) break;
    }
  
    if (wrong!=0)
    {
	sprintf(lib_txt,"wrong number of soldiers on stair %d: %d requested, %d available",wrong,subset[i],st[i]);
	lib_error(1,lib_txt);
    }
  
    /* decide */
    choice=decide(subset);
    
    /* choice 1: move subset one stair up, discard the rest */
    if (choice==1)
    {
	for (i=1;i<=game_N;i++) st[i]=subset[i];
	for (i=1;i<=game_N;i++) st[i-1]=st[i];
    }
    else  /* choice 2: discard subset, move complement one stair up */
    {
	for (i=1;i<=game_N;i++) st[i]-=subset[i];
	for (i=1;i<=game_N;i++) st[i-1]=st[i];
    }
  
    /* check if there are any soldiers left */
    /* check if there is any soldier at position 1 */
    cnt=0;
    for (i=1;i<=game_N;i++) cnt+=(!!st[i]);
  
    if (cnt==0)
    {
        sprintf(lib_txt,"You lost!");
	lib_error(0,lib_txt);
    }
  
    if (st[1])
    {
	sprintf(lib_txt,"You won!");
	lib_error(0,lib_txt);
    }

    return choice;
}

