MainForm: recursion rewritten to iteration