Fixing a number of errors in my implementation pointed out by @xStrom and @mjibson