refactor and smoothen flow