create _finalize_output() to get rid of repeated code