Final working solution with full documentation and clean-ish code