Moved retrieval of length outside of all loops for speed