Started the query-building logic. Laid out a rough algorithm in some comments.

Light reformatting and refactoring.