significant rewrite of function removing for-loop (Issues#2,#23)