refactored write_stats