corrected algorithm (could use refactoring)
test file