double buffer optimization and some general refactoring