slightly refactored
finally solved