modified and clean up algorithm_intermediate