This is massively complex for a callback. Maybe refactor it into smaller chunks.