optimized for space, and writing into output file