refactor implemenation, clean up flag logic