Early Media Implementation

Hi,
I want to implement early media on my system.
My system works in a way that a call is thrown to agents , and then agent transfers it to pitcher , if the callee is available. In our system, the agents cannot hear the ringing of callee’s phone and is automatically bridged, when the callee picks up the call. Now I want that the agent can spy on the callee’s channel, and listen to ringing or any thing that is being said, or rather earlymedia.So, I have implemented a code, which takes in the agent’s channel , and stores in a variable CHAN, and used Chanspy() application to spy on the callee’s channel. AMI is used to send call origination commands to asterisk. When the call is answered by callee, we want the spying to stop, otherwise the agent channel remains busy, and agent cannot talk.So, I want to access the CHAN variable in that context and hang the channel in the variable.
But the thing is that , the variable is not available in the context, and so for it I use global variable to set it.
This works fine for a single agent logged in, but when multiple agents are logged in, and multiple calls are being received, the system fails to work as CHAN is global variable, and hangs up different channels when called from the other context.

The code for the two contexts are-
[spy-channel]
exten => s,1,Answer()
same => n,Verbose({CHANNEL}) same => n,Set(GLOBAL(Chan)={CHANNEL})
same => n,ChanSpy({SPY_ON_CHANNEL},qwE) same => n,SoftHangup({CHAN})
same => n,Return()

[tempinbound-1](The channel called when callee answers the call]
exten => s,1,Answer()
same => n,GoSub(spy-channel,s,5)
same => n,Set(__IS_QUEUES_ENABLED=${UseQueues})

Can anyone please suggest how to share the variable and hang up the right channel?

Please mark up your quotations as preformatted text, using </.>

This is the reason why you cant use global variables for variables where the value will be dynamic

Yes exactly thats what the problem is

Use Multiple Inheritance exten = 1234,1,Set(__FOO=bar)

Hi, I had one question regarding multiple inheritance.
In my system, when the callee answers the call, the agents are assigned randomly, depending on who is free. So, in this case, if I set the agent channel in a variable using multiple inheritance, it will definitely be received by the context triggered when callee answers the call. But when there are multiple agents, and multiple calls, how can the system understand, for which channel, which value of the variable needs to be used