refactored and now working