Refactored a bit, added some safeguards so setup goes cleanly.