cleanup code; fix memory leak