Need help with command block Capture the Flag

As stated in the title, I need help with making a capture the flag system. I have pretty much everything down, but the one thing i need is a command system to make flag carriers who die lose the flag, while placing it back at the flag spawn. I have the teams down and a sensor for returning the flag and getting a point for your team if your flag is home.

But what I want is when a player dies with a flag in their inventory, they respawn at the team spawnpoint, while losing the flag from their inventory, and placing the flag back at the enemy base.

This has been the only issue for me so far. Any help would be greatly appreciated

You can detect dead players with a scoreboard and tag them if they have the flag (if keepInventory is set to true). If they have the tag, you can execute from them to run a /setblock command and clear it from their inventory: