improved main loop. fixed memory leaks