rewrite code base on q