refactoring query and cleanup.