Removed infinity loop
Added explicit closing of file streams