Bridging a new dial with existing channel doesn't work

Hi,

I am new to Asterisk. I am trying to bridge an outgoing call (using dial) to the existing channel it seems to work most of the time. Sometimes I get lots of hangups.

Here is my code. Can anyone point out any problems with this line of code or suggest another way of doing it? I also want to know if this is the most efficient way of doing this. Am I using a lot of resources when I execute this code?

static int csi_dial(struct ast_channel *chan, char *number,struct leave_vm_options *options, char *bridgeIPAddress, char *company)
{

int res = -1;

struct ast_module_user *u;

struct ast_dial *dial = NULL;

char *tmp = NULL, *tech = NULL, *device = NULL;

struct ast_channel *answered = NULL;

struct ast_bridge_config bridge_config;  

enum ast_dial_result result=0;

u = ast_module_user_add(chan);


/* Create a dialing structure */

if (!(dial = ast_dial_create())) {

	ast_log(LOG_WARNING, "Failed to create dialing structure.\n");

	ast_module_user_remove(u);

	return -1;

}

ast_dial_append(dial, "SIP", number);

memset(&bridge_config, 0, sizeof(bridge_config));

ast_stream_and_wait(chan, "TransferWait", chan->language, AST_DIGIT_ANY);

/* Attempt to dial all the channels and bridge to the one that answered */
result = ast_dial_run(dial, chan, 0);

if ((result == AST_DIAL_RESULT_ANSWERED) && (answered = ast_dial_answered(dial)))  {

// ast_log(LOG_DEBUG, “Bridging call\n”);
ast_bridge_call(chan, answered, &bridge_config);
}else {
csi_take_a_message(chan, CSIBRIDGE_GENERAL_MESSAGE, options,
bridgeIPAddress, company);
}

ast_log(LOG_DEBUG, "Dial Result [%d] number [%s]\n", result, number);

/* Hangup all calls in the dialing structure */

ast_dial_hangup(dial);


/* Perform cleanup on dial structure */

ast_dial_destroy(dial);


ast_module_user_remove(u);

return res;

}

Thanks
Best Wishes,
Allen