Added debug lines and fixed a resource leak