Fix order of opening file, getting stats, writing