Error checking + some rearranging of the code