Fixed some memory leaks and bugs related to unchecked memory allocations. Simplified some APIs.