replace terminal recursive call by loop