refactored code for maintainability, added lots of validation