refactored code and more modular implementation