Refactoring using ideas from Mityo's solution on task 3.
Copied Georgi Angelov's last task.