How to stop an AGI script when other party hangsup

I have a Java program that originates a call to a client and, upon answer, connects it to an extension in the dialplan. That extension in turn runs an AGI script to do some interactions with the client. If the client keeps the line until the end, everything is perfect. But if he hangsup in the middle, the AGI script continues running. I would like it to stop at the moment the client hangsup.

Here is an extract of the originating java program:

[code]OriginateAction originateAction;
ManagerResponse originateResponse;
originateAction=new OriginateAction();
originateAction.setChannel(phoneNumber);
originateAction.setExten(“700”);
originateAction.setContext(“users”);
originateAction.setPriority(new Integer(1));

//connect to Asterisk and login
ManagerConnectionFactory factory = new ManagerConnectionFactory(“localhost”,"******","******");
managerConnection = factory.createManagerConnection();
managerConnection.login();
//send the originate action and wait for a maximum of 30 seconds to get a response
originateResponse=managerConnection.sendAction(originateAction, 30000);[/code]

An extract from the dialplan

exten =>700,1,Agi(agi://localhost/message.agi,${var1},${var2},${var3},${var4}); script to play

And an extract from the agi script

public void service(AgiRequest arg0, AgiChannel arg1) throws AgiException { setVariable("missedSteps","4"); verbose(" -------------- missed steps: 4 ----------------", 3); // Answer the channel and welcome answer(); streamFile("silence/1"); streamFile("welcome"); setVariable("missedSteps","3"); verbose(" -------------- missed steps: 3 ----------------", 3); //Read the file streamFile(fileName); setVariable("missedSteps","2"); verbose(" -------------- missed steps: 2 ----------------", 3); .......... .......... setVariable("missedSteps","1"); verbose(" -------------- missed steps: 1 ----------------", 3); .......... .......... setVariable("missedSteps","0"); verbose(" -------------- missed steps: 0 ----------------", 3); //hangup hangup();

So as you can see I am trying to keep a variable that traces the evolution within the script, and I want to keep that variable to store it in a log of the call. As you can see I have added some verbose commands for debugging, and what I see on the console is that the “missedSteps” variable keeps progressing from 4 to 0 whether the client has hung up or not.