Major refactor of the code