move rebuild code onto separate functions