Refactor stdio handling