Logic broken out, updated references
Unused references removed, formatting