Moved setting up of foreign keys to one place. Minor refactoring