rearranges some code for better error handling.