Added Cj's script, and made a slight modification to the thresholding function which appears to have fixed the bug