Refactored the code into more functions and added a -main to avoid having to run it from the REPL all the time