changes as per review, refactored huge functions into smaller ones