Cleanup code, fix mem leak