Refactored code a bit. Added helper functions