Rewriting recursive functions as iterative

To avoid Maximum Call stack size exceeded messahges