Rewrote some code for clarity.