Oh sorry, missed this.  The loop just loops over axis so it's pretty self evident.  I commented what the complicated parts do and the purpose of the function is documented in doxygen.