Memory optimizations/ leak fixes

Substantial ones, at that.