Corrected the time loop for query; general cleanup