Refactored code into functions

Also added some error handling.