#include <stdio.h>
#include "sudoku.h"

extern char *dirs[];
extern int root;

void check(struct state *state) {
  int i, e = 0, next = 0, prev = 0;
  struct cell *cell = null;
  struct ref *ref = null;
  for (cell = state->cells, i = 0; i < SIZE*SIZE; i++, cell++) {
	if (cell->count != bitsSet(cell->mask)) {
	  printf("Error in cell %d, mask is %x but count is %d\n", i, cell->mask, cell->count);
	  e++;
	}
  }
  if (state->list != -1) {
	for (i = 0, ref = state->refs + state->list; (i < 3*SIZE*SIZE + 1) && (ref->next != -1); i++, ref = &state->refs[ref->next]);
	if (i == 3*SIZE*SIZE + 1) {
	  printf("Loop in reference list\n");
	  e++;
	}
	while (i-- && ref->prev != -1) {
	  ref = &state->refs[ref->prev];
	}
	if (i >= 0 || ref->prev != -1) {
	  printf("problem in reference reverse list\n");
	  e++;
	}
  }
  for (ref = state->refs, next = prev = i = 0; i < 3*SIZE*SIZE; i++, ref++) {
	if (ref->next == -1) {
	  if (next++) {
		printf("More than one end of list\n");
		e++;
	  }
	}
	else if ((ref->next < -2) || (ref->next >= SIZE*SIZE)) {
	  printf("Bad value on refs[%d]->next: %d\n", i, ref->next);
	  e++;
	}
	if (ref->prev == -1) {
	  if (prev++) {
		printf("More than one start of list\n");
		e++;
	  }
	}
	else if ((ref->prev < -2) || (ref->prev >= SIZE*SIZE)) {
	  printf("Bad value on refs[%d]->prev: %d\n", i, ref->prev);
	  e++;
	}
  }
  if (prev != 1) {
	printf("No start of list\n");
	e++;
  }
  if (next != 1) {
	printf("No end of list\n");
	e++;
  }
	
  if (!e) {
	printf("All OK\n");
  }
}

void printList(struct state *state) {
  int i, r = state->list;
  struct ref *ref = null;
  printf("Potentials list:\n");
  for (i = 0, r = state->list; r >= 0; r = ref->next) {
	ref = state->refs + r;
	printf("%4d) %4d %4d %4d %4d %-8s %6d %4x\n", i++, r, ref->prev, ref->next, ref->cell, dirs[ref->dir], ref->level, state->cells[ref->cell].mask);
  }
}

void printRefs(struct state *state) {
  int i;
  struct ref *ref = null;
  for (i = 0; i < 3*SIZE*SIZE; i++) {
	ref = state->refs + i;
	printf("%3d) %2d %6s %d   %2d %2d\n", i, ref->cell, dirs[ref->dir], ref->level, ref->prev, ref->next);
  }
}

void printCells(struct state *state) {
  int i;
  struct cell *cell = null;
  for (i = 0; i < SIZE*SIZE; i++) {
	cell = state->cells + i;
	printf("%2d) %4x %d\n", i, cell->mask, cell->count);
  }
}


