Corrected some of the flaws in the earlier code