fix logic and add comments