Fixed incorrect closing of stream