refactored code to use states