Fix some memory leaks and other tweaks

Change-Id: I63ce9c6bd95f3d1849709badfce6058d6c07b4ee