Refactored main function and added simple error handling