Refactored some code to be more robust