/*	tsumelst.c
 * routines to manipulate move list cells
 */

#include "tsume.h"
#include "tsumedat.h"


/* joins the list of cells whose head is 'add' to the end of the
/* list pointed to by 'base'. It also sets the 'from' coordinates
/* to those in 'base'.
 */
join ( add, base )
STEM	add, *base;
{	STEM	pointer;

	if ( (int) add <= NULL )	return;

	if ( *base == NULL )
	{	*base = add;
		return;
	}

	pointer = *base;
	while ( pointer->next != NULL )		pointer = pointer->next;

	pointer->next = add;
	add->prev = pointer;
	add->loc_from_x = (*base)->loc_from_x;
	add->loc_from_y = (*base)->loc_from_y;

	while ( add->next != NULL )
	{	add = add->next;
		add->loc_from_x = (*base)->loc_from_x;
		add->loc_from_y = (*base)->loc_from_y;
	}
}


/* joins the list of cells whose head is 'add' to the end of the
/* list pointed to by 'base'.
 */
tie ( add, base )
STEM	add, *base;
{	STEM	pointer;

	if ( (int) add <= NULL )	return;

	if ( *base == NULL )
	{	*base = add;
		return;
	}

	pointer = *base;
	while ( pointer->next != NULL )		pointer = pointer->next;

	pointer->next = add;
	add->prev = pointer;
}


/* frees the list pointed to by base, and all lists pointed to by elements
/* of base.
 */
discard ( base )
STEM	base;
{	STEM	pointer, free_it;

	if ( ( int ) base == TREE )	return;

	pointer = base;
	while ( pointer != NULL )
	{	free_it = pointer;
		pointer = pointer->next;
		if ( free_it->next_level != NULL )
			discard ( free_it->next_level );
		free ( free_it );
	}
}


/* Used to create an additional cell if a piece can, but need not, promote.
/* It replicates the original cell but with the 'promote' flag set. The
/* replicted cell is chained to the original.
 */
p_repl ( extra )
STEM	extra;
{	extra->prev = ( STEM ) malloc ( sizeof ( LEAF ) );
	extra->prev->prev         = NULL;
	extra->prev->next         = extra;
	extra->prev->piece_moving = extra->piece_moving;
	extra->prev->loc_from_x   = extra->loc_from_x;
	extra->prev->loc_to_x     = extra->loc_to_x;
	extra->prev->loc_from_y   = extra->loc_from_y;
	extra->prev->loc_to_y     = extra->loc_to_y;
	extra->prev->promo_now    = YES;
	extra->prev->capture      = extra->capture;
	extra->prev->next_level   = NULL;

	return;
}


/* Makes a copy of a board array */
brdcpy ( out, in )
char	*out, *in;
{	int	i;

	for ( i = 0; i < 91; i++ )	*out++ = *in++;
}


/* Tests if the two game states are identical. This is to allow the
/* result tree to be simplified. ( See use of mate_twig.)
 */
int same_state ( state_a, state_b )
I_STATE	state_a, state_b;
{	int	i, j;

	i = 0;

	if ( state_b == NULL )	return 1;

	while ( state_a->att_h[i] != NULL )
	{	if ( state_a->att_h[i] != state_b->att_h[i] )
			return 1;
		i++;
	};

	if ( state_b->att_h[i] != NULL )
		return 1;

	i = 9;
	while ( ++i < 91 )
		if ( state_a->board[i] != state_b->board[i] )
			return 1;

	return 0;
}
