fixed some memory leaks
MERGE: included changes from dev branch