cleaned up adaptive thresholding implementation