modifying refine layers algorithm