Main loop revised