Fixed issue with memory access errors due to unclosed cursors.