Fix bug in rebuild and add tests
Fix bug in rebuild and add tests