Lots of code cleanup, formatting and commenting.