Complete refactoring of the code

Much cleaner and less duplication. Added docstrings and comments.