Reduced number of loops, corrected comments