revised rewrite logic.
updated rewrite logic.
refactored.