refactored code - corrected setting prev