Refactored some of the code to be safer