Fix flush, refactor code