move rebuild into its own class and simplify code