First working version of rewrite