improve handle handling and fix memory leak