Is there a reference or description of this algorithm?
I'm not very good in reading loops.

looks similar to mixed effects models (which I also have problems with in the variance decomposition). 
Is the underlying assumption that we have a random constant component for each nested level?