use collections.deque, clean up the code