Here is a much more clean, and documented code