refactored code, now fully working