Now writes to file and has some improvements