Fix potential memory leak and minor clean-up