Adding some null/error checks and cleaning up the code