rewrite some queries & optimize code