Fixes loss of output (premature close?) and partly fixes erroneous switching of order

Of course, I don't know what other effects the change might have, so I happily leave it to you to review and decide! :)