Corrected serious logic error pointed out by @luismbo. Hopefully this version is "good enough" now.