refactored into this file, so that all relevant code is grouped together.