
#ifndef __BOARD_H	
#define __BOARD_H	1

struct _board {
	int col;
	int row;
	int **cell;
};

typedef struct _board	board_t;

extern board_t make_board(int row, int col);
extern void del_board(board_t *board);
extern void print_board(board_t board);
extern board_t read_board_file(const char *str);
extern int cell_swap(board_t *board, int frow, int fcol, int trow, int tcol);
extern void board_position(board_t board,int val, int *row, int *col);

extern void num_swap(int*, int*);

board_t make_board(int row, int col)
{
	board_t	board;
	int	i;
	
	memset(&board,0,sizeof(board));
	board.cell = (int**) malloc(row*sizeof(int*));
	if(board.cell == NULL)
		return board;
	
	for(i=0;i<row;i++) {
		board.cell[i] = (int*) malloc(col*sizeof(int));
		if(board.cell[i] == NULL) {
			for(--i;i>=0;i--)
				free(board.cell[i]);
			free(board.cell);
			return board;
		}
	}

	board.row = row;
	board.col = col;
	
	return board;
}

void del_board(board_t *board)
{
	int i;
	for(i=0;i<board->row;i++) 
		if(board->cell[i])
			free(board->cell[i]);
	free(board->cell);
	memset(board,0,sizeof(board));
}

void print_board(board_t board)
{
	int i,j;
	printf("\n");
	for(i=0;i<board.row;i++) {
		for(j=0;j<board.col;j++) 
			printf("%5d",board.cell[i][j]);
		printf("\n");
	}
	printf("\n");
}

int cell_swap(board_t *board,int frow,int fcol, int trow, int tcol) 
{
	
	if(frow < 0 || frow >= board->row ||\
			fcol < 0 || fcol >= board->col ||\
			trow < 0 || trow >= board->row ||\
			tcol < 0 || tcol >= board->col )
		return -1;	/* Error */
	num_swap(&board->cell[frow][fcol], &board->cell[trow][tcol]);
}

void board_position(board_t board,int val, int *row, int *col)
{
	int i,j;
	
	*col = *row = -1;
	for(i=0;i<board.row;i++)
		for(j=0;j<board.col;j++)
			if(board.cell[i][j]==val) {
				*row = i;
				*col = j;
				return;
			}
}

void num_swap(int *a, int *b)
{
	int c;
	c=*a;
	*a=*b;
	*b=c;
}

board_t read_board_file(const char *str)
{
	FILE 	*fptr;
	int	i,j,row,col;
	board_t	board;

	//memset(&board,0,sizeof(board));
	fptr = fopen(str,"r");
	if(fptr==NULL)
		return board;
	fscanf(fptr,"%d",&row);
	col = row;
	board=make_board(row,col);
	board.row=board.col=0;
	for(i=0;i<row;i++) 
		for(j=0;j<col;j++)
			fscanf(fptr,"%d",&board.cell[i][j]);
	if(feof(fptr))
		return board;
	board.row = row;
	board.col = col;
	return board;
}	

#endif 
