Fix some memory management issues, closes #4 and #5.