public int nLevelQuantize(int level, int pixel)
	{
		//edge cases
		if(pixel <= 0)
			return 0;
		if(pixel >= 255)
			return 255;
		
		int[] levels = new int[level];
		
		for(int i = 0; i < level; i++)
		{
			levels[i] = (int) 255.0/(level-1) * i;
		}
		levels[level-1] = 255;
		
		int max = 0; 
		int min = 0;
		
		for(int i = 0; i < level; i++)
		{
			if (pixel > levels[i])
			{
				min = levels[i];
				if(i+1 > level)
					max = levels[i];
				else
					max = levels[i+1];
			}
		}
		
		int halfDifference =  (int) java.lang.Math.floor(max - (max - min) / 2); 
		
		if (pixel < halfDifference)
			pixel =  min;
		else if (pixel >= halfDifference)
			pixel =  max;
	
		return pixel;
	}