Cleans up a little bit of code and adds some null checks.