Added terminating condition