Main for-loop rewritten as recursive function