Rewrote the code for more structured