finished algorithm needs some refactoring to make it look cleaner