Corrected error processing, moved it into the loop