refactor to share some code between the two parsing algorithms