refactor changesgenerate code

Eliminate code duplication and long functions.