Added unit test,  replaced the while loop with a tailrec