moved buffer clearing and swapping to main loop