Rewrote code to be much shorter and (I think) more clear.