Extremely large code cleanup and some misc bug fixes (no clue if it compiles)