added ps_finish() to write the remainder out (if any), split writing into a couple of helpers
fixed empty goto