refactored and added more comments