Fixed stack overflow error and one-off main loop