Refined alogrithm for rewriting