Please read my comments here and the commented code