Add writing to file and better threading