Better logging of errors. Rearranged where things happen