Refactored and added more comments and exception handling