Add out function and refactoring