Added better error checking and cleaned up some formatting