Brotipped memory leaks fix.

Getting rid of memory leaks and applying some DRY principle.