correct logic and refactor code