Fix a bunch of potential NPEs. Improve code style.