refactored stdout/err processing

This fixes the problem with stdout copying goroutines
being terminated when main ends: they are now being waited on.