recursive algorithm for terminal switching