Tweaked finalize_data for robustness