Add write to file method for task4. Pefactor some code.