/*
	Finds the direction we should walk in given
	the first boundary point we use to create teh boundary
*/
int FirstDirectionBoundary(int& x, int& y, CImg<float>& mag)
{
	//check whether this is a boundary pixel
	if(mag(x,y) <= 0) return -1;
	
	//Find first neighbor outside
	//Check for border pixels
	if(x+1 >= mag.dimx()) return 0;
	if(y+1 >= mag.dimy()) return 2;
	if(x == 0) return 4;
	if(y == 0) return 6;
	
	if(mag(x+1, y) <= 0)	return 0;
	if(mag(x+1, y+1) <= 0)	return 1;
	if(mag(x, y+1) <= 0)	return 2;
	if(mag(x-1, y+1) <= 0)	return 3;
	if(mag(x-1, y) <= 0)	return 4;
	if(mag(x-1, y-1) <= 0)	return 5;
	if(mag(x, y-1) <= 0)	return 6;
	if(mag(x+1, y-1) <= 0)	return 7;
	
	return -1; //no neighbors are outside this point
}

void GetNextEdgel(int& x, int& y, int& dir, 
	CImg<float>& mag, int nDimx, int nDimy)
{
	for( int k = 0; k < 8; ++k)
	{
		switch( (dir + k) % 8)
		{
			case 0:	//try at (x+1, y)
				if( x < nDimx && mag(x+1,y) > 0)
				{
					++x;
					dir = 5;
					return;
				}
			case 1:	//try at (x+1, y+1)
				if( x < nDimx && y < nDimy && mag(x+1,y+1) > 0)
				{
					++x;
					++y;
					dir = 6;
					return;
				}
			case 2:	//try at (x, y+1)
				if( y < nDimy && mag(x,y+1) > 0)
				{
					++y;
					dir = 7;
					return;
				}
			case 3:	//try at (x-1, y+1)
				if( x > 0 && y < nDimy && mag(x-1,y+1) > 0)
				{
					--x;
					++y;
					dir = 0;
					return;
				}
			case 4:	//try at (x-1, y)
				if( x > 0 && mag(x-1,y) > 0)
				{
					--x;
					dir = 1;
					return;
				}
			case 5:	//try at (x-1, y-1)
				if( x > 0 && y > 0 && mag(x-1,y-1) > 0)
				{
					--x;
					--y;
					dir = 2;
					return;
				}
			case 6:	//try at (x, y-1)
				if( y > 0 && mag(x,y-1) > 0)
				{
					--y;
					dir = 3;
					return;
				}
			case 7:	//try at (x+1, y-1)
				if( x < nDimx && y > 0 && mag(x+1,y-1) > 0)
				{
					++x;
					--y;
					dir = 4;
					return;
				}
		}
	}
}


bool HasBckGrndNbr(const CImg<float>& img, int x, int y)
{
	if(img(x,y) == 255)
		return false;
		
	for(int xi = x - 1; xi <= x + 1; xi++)
		for(int yi = y - 1; yi <= y + 1; yi++)
			if(xi != x || yi != y)
			{
				if(img(xi,yi) == 255)
					return true;
			}
	return false;
}

/*
	This function will mark all bndry points
	with a 255 and all other points with a 0
*/
int FindEdgels2(const CImg<float>& img, CImg<float>& bndry)
{
	int nNbrs = 0;
	
	//go over the image
	cimg_mapXY(img,x,y)
	{
		if(img(x,y) == 255) //background
			bndry(x,y) = 0;
		else //non background pixel
		{
			if(HasBckGrndNbr(img,x,y))
			{
				bndry(x,y) = 255;
				nNbrs++;
			}
			else
				bndry(x,y) = 0;
		}
	}
	
	return nNbrs;
}