Added better logging and error checking