refactored algorithm

made algorithm simpler and more consistent