working solution with some comments