Fix problems with premature exits. Clean up on terminating signals

Not quite sure the clean up on terminating signals is doing the right thing
but it seems so.