query optimization and some cleanup