Added parameter optimization and better thresholding