re-structured main loop