algorithm refactored and continued