comments added, accounted for some edge cases