Better error logs and pulled some stuff out of the loop that only needs to execute once