struct cell 
{
	int nwall : 1;
	int ngap  : 1;
	int ewall : 1;
	int egap  : 1;
	int onroute : 1; /* Used for display route */
	unsigned score : 11;
};

#define NUM_CELLS 256
#define MAX_SCORE 0x7FF

struct cell cells[NUM_CELLS];


void Navigator_Init( void )
{
	int i=0;
	
	for ( i = 0 ; i < NUM_CELLS ; i++ ) {
		cells[i].nwall = cells[i].ngap =  cells[i].ewall = cells[i].egap = 0 ;  
		cells[i].score = MAX_SCORE;
	}
	cells[0].ewall = 1;
}



/*
 * Determine route from cell to cell
 * Centre cells are 0x77,0x78,0x87,0x88 
 * Cells are numbered:
 * 0xf0 .. .. 0xff
 * ..   87 88   ..
 * ..   77 78   ..
 * 0x00 .. .. 0x0f
 * Where 00==SouthWest, 0xff == NorthEast
 * 
 * Returns nothing
 * 
 */
void Navigator_Route( uint8_t from , uint8_t to )
{
	unsigned i,current_score = 0 ;
	uint8_t x , y , solving = true, unknown_gap=0 , nexti;
	
	for ( i = 0 ; i < NUM_CELLS ; i++ ) { // Preset max score in all cells
		cells[i].score   = MAX_SCORE;
		cells[i].onroute = 0;
	}
	if ( from == to ) { // Accept 4 centre cells as destination ?
		cells[0x77].score=cells[0x78].score = cells[0x87].score = cells[0x88].score = 0;
	} else {
		cells[to].score=0; // Set score in detination cells
	}
	while ( ( cells[from].score == MAX_SCORE ) && solving ) {
		solving = false; 
		for ( i = 0 ; i < NUM_CELLS ; i++ ) {
			if ( cells[i].score == current_score )
			{
				x = i & 0xf ; y = i >> 4 ;
				if ( y < 15 ) // Check North
					if ( cells[i].nwall == 0 )
				    	 if ( cells[i+16].score == MAX_SCORE ) {
				     		  cells[i+16].score  = current_score+1;
				     		  solving = true;
				    	 }
				if ( y > 0 ) // Check South
					if ( cells[i-16].nwall == 0 )
				    	 if ( cells[i-16].score == MAX_SCORE ) {
				     		  cells[i-16].score  = current_score+1;
				     		  solving = true;
				    	 }
				if ( x < 15 ) // Check East
					if ( cells[i].ewall == 0 )
				    	 if ( cells[i+1].score == MAX_SCORE ) {
				     		  cells[i+1].score  = current_score+1;
				     		  solving = true;
				    	 }
				if ( x > 0 ) { // Check West
					if ( cells[i-1].ewall == 0 ) {
				    	if ( cells[i-1].score == MAX_SCORE ) {
				     		 cells[i-1].score  = current_score+1;
				     		 solving = true;
				    	}
					}
				}
			}
	  	}
	  	current_score++;
	  	// printf("solving=%d, current Score=%d\n",solving,current_score);
	}
}


