First version of rewriting optimization part