Big improvements to the code and comments