Moved main loop, and some bugfixes