We should split this function up if possible, it's getting unwieldy.