Refactoring of the code for easier testing, and more documentation