Fix miscellaneous bugs

Memory leak, buffer overrun, efficiency.