Massive code clean up (with some small code changes too)