Added helper functions and refactored code