Documented the code and refactored it to be simpler