Refactored some functions and added more comments