fixed memory leaks and invalid writes.