if you really want to understand what the effect of a certain code is, use the debugger.
Go line by line, look what's the content of the variables, and may be start all over again. That's what I'm doing if I don't understand a certain code entirely.
It is work, but it pays...
So I suggest to start with the code presented here. The next step would be modifying/extending the code
I presented working code so you could play around with it and get a feel for what's involved.