Code refactored (a little bit) and commented