Refactoring: move stdin/out up to __main__

Use explicit stream variable in inner functions,
sys streams are thus only in use in the upper layer.