Fix potential segfault and improve handling of cpout files and determining when
they are finished.