write output to file and some cleanup