Fix i/o and optimise code