initial code cleanup, removed dead code, added comments to describe various functions
improved query checking, removed dead code, started commenting the more confusing functions