changed die function to free resources properly