Fix potential NULL deref and other minor changes