#include "player.h"
#include "utilities.h"

static int scitzbot(int, int, int*);

static int hm2()
{
    int i, best, length;
    
    best = length = 0;
    for (i = my_history[0]-1; i > length ; i--)
    {   int j;
	for (j = 0; j < i && opp_history[i-j] == opp_history[my_history[0]-j]
		 ; j++)
	  {    }
	if (j > length)
	{  length = j;
	   best = i;
	}
    }
    if (best)
	return opp_history[best+1];
    else
	return -1;
}

int scitzbotXY()
{
    static int s;
    return scitzbot(15, 15, &s);
}

static int scitzbot(int x, int y, int *S)
{
    int hm;
    int last;
    
    if (my_history[0] == 0)
    {	
	*S = 1;
	return random() % 3;
    }
    hm = hm2();
    if (hm == -1) 
	return random() % 3;
    else
    {	
	last = (my_history[my_history[0]] - opp_history[my_history[0]] + 3) % 3
;
	if (last == 2) 
	{ 
	   if (random() % 100 < x) *S = (*S + 2) % 3; 
	}
	else if (last == 0)
	{ 
	   if (random() % 100 < y) *S = (*S + 1) % 3; 
	}
	return (hm + *S) % 3;
    }
}

/* "Mandelbot" roshambo bot.
 *  Check history of its moves.  If lost last time, play to beat what
 *  lost to.  If didn't lose, play HistoryBot.
 *  Outperforms History Bot, gets kicked by Iocaine.
 */

static int hidx(int hist[])
{
   int i, best, len;

   best = len = 0;
   for (i = hist[0]-1; i > len; i--)
   {   int j;
       for (j = 0; j < i && hist[i-j] == hist[hist[0]-j]
				; j++)
	 { }
       if (j > len)
       {  len = j;
	  best = i;
       }
   }
   return best;
}

#if 0
int mandelbot()
{
   int i;
   static int record, gorand;
   int last;

   if (my_history[0] == 0)
	record = gorand = 0;
   else
   {	last = (my_history[my_history[0]] - opp_history[my_history[0]] + 3) % 3
;
	if (last == 2)
	    record--;
	else record += last;
   }
   if (record < -37) gorand = 1;
   if (gorand) return random()%3;

   i = hidx(my_history) + 1;
   if (i == 1)
	return historybot();
   if ((my_history[i] - opp_history[i] + 3) % 3 == 2)
	return will_beat(opp_history[i]);
   return historybot();
}
#endif
