actually fixed the bug and refactored a little