refactored code to final version