works, but code needs refactoring