rewrite code and handle chunking