sort and write to file