diff --git a/apps/app_adsiprog.c b/apps/app_adsiprog.c
index 40330152b03d79078657cb5cb2800ef310001b93..b07a950a26ec45e657563c46a1cbf6c0f2359e21 100644
--- a/apps/app_adsiprog.c
+++ b/apps/app_adsiprog.c
@@ -1384,11 +1384,11 @@ static struct adsi_script *compile_script(char *script)
 		break;
 	case STATE_INSUB:
 		ast_log(LOG_WARNING, "Missing ENDSUB at end of file %s\n", script);
-		free(scr);
+		ast_free(scr);
 		return NULL;
 	case STATE_INKEY:
 		ast_log(LOG_WARNING, "Missing ENDKEY at end of file %s\n", script);
-		free(scr);
+		ast_free(scr);
 		return NULL;
 	}
 	err = 0;
@@ -1414,7 +1414,7 @@ static struct adsi_script *compile_script(char *script)
 	}
 
 	if (err) {
-		free(scr);
+		ast_free(scr);
 		return NULL;
 	}
 	return scr;
@@ -1451,7 +1451,7 @@ static int adsi_prog(struct ast_channel *chan, char *script)
 		if (option_verbose > 2)
 			ast_verbose(VERBOSE_PREFIX_3 "User rejected download attempt\n");
 		ast_log(LOG_NOTICE, "User rejected download on channel %s\n", chan->name);
-		free(scr);
+		ast_free(scr);
 		return -1;
 	}
 
@@ -1538,10 +1538,10 @@ static int adsi_prog(struct ast_channel *chan, char *script)
 		if (option_verbose > 2)
 			ast_verbose(VERBOSE_PREFIX_3 "Download attempt failed\n");
 		ast_log(LOG_NOTICE, "Download failed on %s\n", chan->name);
-		free(scr);
+		ast_free(scr);
 		return -1;
 	}
-	free(scr);
+	ast_free(scr);
 	ast_adsi_unload_session(chan);
 	return 0;
 }
diff --git a/apps/app_alarmreceiver.c b/apps/app_alarmreceiver.c
index e74a7b46a4014c9783f3e4549ff900eea5f5766a..56f604f2774fdf1b7d8b747181202170e351c612 100644
--- a/apps/app_alarmreceiver.c
+++ b/apps/app_alarmreceiver.c
@@ -727,7 +727,7 @@ static int alarmreceiver_exec(struct ast_channel *chan, void *data)
 	for(elp = event_head; (elp != NULL);){
 		efree = elp;
 		elp = elp->next;
-		free(efree);
+		ast_free(efree);
 	}
 
 
diff --git a/apps/app_dial.c b/apps/app_dial.c
index f713f3375a2e3932166dceddd4dffa936feb07a5..0d30dc1189fdbb9a9cc8fc679c4e061b8ab2aa49 100644
--- a/apps/app_dial.c
+++ b/apps/app_dial.c
@@ -312,7 +312,7 @@ static void hanguptree(struct chanlist *outgoing, struct ast_channel *exception)
 			ast_hangup(outgoing->chan);
 		oo = outgoing;
 		outgoing=outgoing->next;
-		free(oo);
+		ast_free(oo);
 	}
 }
 
@@ -1327,7 +1327,7 @@ static int dial_exec_full(struct ast_channel *chan, void *data, struct ast_flags
 			handle_cause(cause, &num);
 			if (!rest)	/* we are on the last destination */
 				chan->hangupcause = cause;
-			free(tmp);
+			ast_free(tmp);
 			continue;
 		}
 		pbx_builtin_setvar_helper(tc, "DIALEDPEERNUMBER", numsubst);
@@ -1374,7 +1374,7 @@ static int dial_exec_full(struct ast_channel *chan, void *data, struct ast_flags
 			}
 			if (!tc) {
 				handle_cause(cause, &num);
-				free(tmp);
+				ast_free(tmp);
 				continue;
 			}
 		}
@@ -1436,7 +1436,7 @@ static int dial_exec_full(struct ast_channel *chan, void *data, struct ast_flags
 				ast_verbose(VERBOSE_PREFIX_3 "Couldn't call %s\n", numsubst);
 			ast_hangup(tc);
 			tc = NULL;
-			free(tmp);
+			ast_free(tmp);
 			continue;
 		} else {
 			senddialevent(chan, tc);
diff --git a/apps/app_directory.c b/apps/app_directory.c
index 8a62c65ebba94ea2685f13173ca4c491f23bf941..0346d64522e84cbf7a5c8aa19bc8707edf7dd4b1 100644
--- a/apps/app_directory.c
+++ b/apps/app_directory.c
@@ -463,14 +463,14 @@ static int do_directory(struct ast_channel *chan, struct ast_config *cfg, struct
 							if (!strncmp(conv, ext, strlen(ext))) {
 								/* Match! */
 								found++;
-								free(conv);
-								free(start);
+								ast_free(conv);
+								ast_free(start);
 								break;
 							}
-							free(conv);
+							ast_free(conv);
 						}
 					}
-					free(start);
+					ast_free(start);
 				}
 				v = v->next;
 			}
@@ -547,10 +547,10 @@ static int do_directory(struct ast_channel *chan, struct ast_config *cfg, struct
 							default:
 								break;
 							}
-							free(conv);
+							ast_free(conv);
 							break;
 						}
-						free(conv);
+						ast_free(conv);
 					}
 				}
 			}
diff --git a/apps/app_externalivr.c b/apps/app_externalivr.c
index 7f2071630d93b2024124f43deb48b5be5631cf26..f08e42ac29f242bfeb7f5c14cf1e24e955432200 100644
--- a/apps/app_externalivr.c
+++ b/apps/app_externalivr.c
@@ -136,7 +136,7 @@ static void gen_release(struct ast_channel *chan, void *data)
 	struct gen_state *state = data;
 
 	gen_closestream(state);
-	free(data);
+	ast_free(data);
 }
 
 /* caller has the playlist locked */
@@ -399,7 +399,7 @@ static int app_exec(struct ast_channel *chan, void *data)
 				AST_LIST_LOCK(&u->finishlist);
 				while ((entry = AST_LIST_REMOVE_HEAD(&u->finishlist, list))) {
 					send_child_event(child_events, 'F', entry->filename, chan);
-					free(entry);
+					ast_free(entry);
 				}
 				AST_LIST_UNLOCK(&u->finishlist);
 			}
@@ -422,7 +422,7 @@ static int app_exec(struct ast_channel *chan, void *data)
 						AST_LIST_LOCK(&u->playlist);
 						while ((entry = AST_LIST_REMOVE_HEAD(&u->playlist, list))) {
 							send_child_event(child_events, 'D', entry->filename, chan);
-							free(entry);
+							ast_free(entry);
 						}
 						if (!u->playing_silence)
 							u->abort_current_sound = 1;
@@ -467,7 +467,7 @@ static int app_exec(struct ast_channel *chan, void *data)
 					AST_LIST_LOCK(&u->playlist);
 					while ((entry = AST_LIST_REMOVE_HEAD(&u->playlist, list))) {
 						send_child_event(child_events, 'D', entry->filename, chan);
-						free(entry);
+						ast_free(entry);
 					}
 					if (!u->playing_silence)
 						u->abort_current_sound = 1;
@@ -569,7 +569,7 @@ static int app_exec(struct ast_channel *chan, void *data)
 		close(child_stderr[1]);
 
 	while ((entry = AST_LIST_REMOVE_HEAD(&u->playlist, list)))
-		free(entry);
+		ast_free(entry);
 
 	ast_module_user_remove(lu);
 
diff --git a/apps/app_festival.c b/apps/app_festival.c
index 22a799f6300678e8c600497d548d465294b96740..dbc9d62445306d3153a27e484216ebb8d8c48c74 100644
--- a/apps/app_festival.c
+++ b/apps/app_festival.c
@@ -525,7 +525,7 @@ static int festival_exec(struct ast_channel *chan, void *vdata)
 				ast_log(LOG_DEBUG,"Festival WV command\n");
 			waveform = socket_receive_file_to_buff(fd,&filesize);
 			res = send_waveform_to_channel(chan,waveform,filesize, intstr);
-			free(waveform);
+			ast_free(waveform);
 			break;
 		}
 		else if (strcmp(ack,"LP\n") == 0) {   /* receive an s-expr */
@@ -534,7 +534,7 @@ static int festival_exec(struct ast_channel *chan, void *vdata)
 			waveform = socket_receive_file_to_buff(fd,&filesize);
 			waveform[filesize]='\0';
 			ast_log(LOG_WARNING,"Festival returned LP : %s\n",waveform);
-			free(waveform);
+			ast_free(waveform);
 		} else if (strcmp(ack,"ER\n") == 0) {    /* server got an error */
 			ast_log(LOG_WARNING,"Festival returned ER\n");
 			res=-1;
diff --git a/apps/app_followme.c b/apps/app_followme.c
index 2e313d012c80f910bb797488df0101c8324f9e7e..37c81d136efd1e0a457d06439ea7d43af094e58e 100644
--- a/apps/app_followme.c
+++ b/apps/app_followme.c
@@ -172,17 +172,17 @@ static void free_numbers(struct call_followme *f)
 
 	while ((prev = AST_LIST_REMOVE_HEAD(&f->numbers, entry)))
 		/* Free the number */
-		free(prev);
+		ast_free(prev);
 	AST_LIST_HEAD_INIT_NOLOCK(&f->numbers);
 
 	while ((prev = AST_LIST_REMOVE_HEAD(&f->blnumbers, entry)))
 		/* Free the blacklisted number */
-		free(prev);
+		ast_free(prev);
 	AST_LIST_HEAD_INIT_NOLOCK(&f->blnumbers);
 
 	while ((prev = AST_LIST_REMOVE_HEAD(&f->wlnumbers, entry)))
 		/* Free the whitelisted number */
-		free(prev);
+		ast_free(prev);
 	AST_LIST_HEAD_INIT_NOLOCK(&f->wlnumbers);
 	
 }
@@ -815,7 +815,7 @@ static void findmeexec(struct fm_args *tpargs)
 			tmpuser = ast_calloc(1, sizeof(*tmpuser));
 			if (!tmpuser) {
 				ast_log(LOG_WARNING, "Out of memory!\n");
-				free(findme_user_list);
+				ast_free(findme_user_list);
 				return;
 			}
 					
@@ -872,7 +872,7 @@ static void findmeexec(struct fm_args *tpargs)
 			if (!fmuser->cleared && fmuser->ochan != winner)
 				clear_caller(fmuser);
 			AST_LIST_REMOVE_CURRENT(findme_user_list, entry);
-			free(fmuser);
+			ast_free(fmuser);
 		}
 		AST_LIST_TRAVERSE_SAFE_END
 		fmuser = NULL;
@@ -883,7 +883,7 @@ static void findmeexec(struct fm_args *tpargs)
 
 		if (!caller) {
 			tpargs->status = 1;
-			free(findme_user_list);
+			ast_free(findme_user_list);
 			return;	
 		}
 
@@ -893,7 +893,7 @@ static void findmeexec(struct fm_args *tpargs)
 				break;
 
 	}
-	free(findme_user_list);
+	ast_free(findme_user_list);
 	if (!winner) 
 		tpargs->status = 1;
 	else {
@@ -1012,7 +1012,7 @@ static int app_exec(struct ast_channel *chan, void *data)
 				
 		AST_LIST_TRAVERSE_SAFE_BEGIN(&targs.cnumbers, nm, entry) {
 			AST_LIST_REMOVE_CURRENT(&targs.cnumbers, entry);
-			free(nm);
+			ast_free(nm);
 		}
 		AST_LIST_TRAVERSE_SAFE_END
 	
@@ -1075,7 +1075,7 @@ static int unload_module(void)
 	AST_LIST_LOCK(&followmes);
 	while ((f = AST_LIST_REMOVE_HEAD(&followmes, entry))) {
 		free_numbers(f);
-		free(f);
+		ast_free(f);
 	}
 
 	AST_LIST_UNLOCK(&followmes);
diff --git a/apps/app_macro.c b/apps/app_macro.c
index 625c4543f12b8d5af6b6a87b70de31a5f6ca7442..21f65f1ab42b5cea49afe154742a17b18ceea4e2 100644
--- a/apps/app_macro.c
+++ b/apps/app_macro.c
@@ -422,7 +422,7 @@ static int _macro_exec(struct ast_channel *chan, void *data, int exclusive)
   		if (oldargs[x]) {
 			if (!dead)
 				pbx_builtin_setvar_helper(chan, varname, oldargs[x]);
-			free(oldargs[x]);
+			ast_free(oldargs[x]);
 		} else if (!dead) {
 			pbx_builtin_setvar_helper(chan, varname, NULL);
 		}
@@ -435,11 +435,11 @@ static int _macro_exec(struct ast_channel *chan, void *data, int exclusive)
 		pbx_builtin_setvar_helper(chan, "MACRO_PRIORITY", save_macro_priority);
 	}
 	if (save_macro_exten)
-		free(save_macro_exten);
+		ast_free(save_macro_exten);
 	if (save_macro_context)
-		free(save_macro_context);
+		ast_free(save_macro_context);
 	if (save_macro_priority)
-		free(save_macro_priority);
+		ast_free(save_macro_priority);
 
 	if (!dead && setmacrocontext) {
 		chan->macrocontext[0] = '\0';
@@ -470,7 +470,7 @@ static int _macro_exec(struct ast_channel *chan, void *data, int exclusive)
 	if (!dead)
 		pbx_builtin_setvar_helper(chan, "MACRO_OFFSET", save_macro_offset);
 	if (save_macro_offset)
-		free(save_macro_offset);
+		ast_free(save_macro_offset);
 
 	/* Unlock the macro */
 	if (exclusive) {
diff --git a/apps/app_meetme.c b/apps/app_meetme.c
index 91d5902564b0879757b99fb00eee08029df426a1..98510667fd1cbeb1d1abbecca17b7470a8b71af1 100644
--- a/apps/app_meetme.c
+++ b/apps/app_meetme.c
@@ -765,7 +765,7 @@ static struct ast_conference *build_conf(char *confno, char *pin, char *pinadmin
 		cnf->fd = open("/dev/zap/pseudo", O_RDWR);
 		if (cnf->fd < 0) {
 			ast_log(LOG_WARNING, "Unable to open pseudo device\n");
-			free(cnf);
+			ast_free(cnf);
 			cnf = NULL;
 			goto cnfout;
 		}
@@ -780,7 +780,7 @@ static struct ast_conference *build_conf(char *confno, char *pin, char *pinadmin
 			ast_hangup(cnf->chan);
 		else
 			close(cnf->fd);
-		free(cnf);
+		ast_free(cnf);
 		cnf = NULL;
 		goto cnfout;
 	}
@@ -1247,7 +1247,7 @@ static int conf_free(struct ast_conference *conf)
 	else
 		close(conf->fd);
 	
-	free(conf);
+	ast_free(conf);
 
 	return 0;
 }
@@ -2278,7 +2278,7 @@ bailoutandtrynormal:
 		snprintf(meetmesecs, sizeof(meetmesecs), "%d", (int) (time(NULL) - user->jointime));
 		pbx_builtin_setvar_helper(chan, "MEETMESECS", meetmesecs);
 	}
-	free(user);
+	ast_free(user);
 	AST_LIST_UNLOCK(&confs);
 
 	return ret;
@@ -3348,9 +3348,9 @@ static void sla_stop_ringing_trunk(struct sla_ringing_trunk *ringing_trunk)
 	sla_change_trunk_state(ringing_trunk->trunk, SLA_TRUNK_STATE_IDLE, ALL_TRUNK_REFS, NULL);
 
 	while ((station_ref = AST_LIST_REMOVE_HEAD(&ringing_trunk->timed_out_stations, entry)))
-		free(station_ref);
+		ast_free(station_ref);
 
-	free(ringing_trunk);
+	ast_free(ringing_trunk);
 }
 
 static void sla_stop_ringing_station(struct sla_ringing_station *ringing_station,
@@ -3385,7 +3385,7 @@ static void sla_stop_ringing_station(struct sla_ringing_station *ringing_station
 	}
 
 done:
-	free(ringing_station);
+	ast_free(ringing_station);
 }
 
 static void sla_dial_state_callback(struct ast_dial *dial)
@@ -3496,8 +3496,8 @@ static void sla_handle_dial_state_event(void)
 			args.station = ringing_station->station;
 			args.cond = &cond;
 			args.cond_lock = &cond_lock;
-			free(ringing_trunk);
-			free(ringing_station);
+			ast_free(ringing_trunk);
+			ast_free(ringing_station);
 			ast_mutex_init(&cond_lock);
 			ast_cond_init(&cond, NULL);
 			ast_mutex_lock(&cond_lock);
@@ -3551,7 +3551,7 @@ static int sla_check_failed_station(const struct sla_station *station)
 			continue;
 		if (ast_tvdiff_ms(ast_tvnow(), failed_station->last_try) > 1000) {
 			AST_LIST_REMOVE_CURRENT(&sla.failed_stations, entry);
-			free(failed_station);
+			ast_free(failed_station);
 			break;
 		}
 		res = 1;
@@ -3586,12 +3586,12 @@ static int sla_ring_station(struct sla_ringing_trunk *ringing_trunk, struct sla_
 
 	if (!sla.attempt_callerid && !ast_strlen_zero(ringing_trunk->trunk->chan->cid.cid_name)) {
 		cid_name = ast_strdupa(ringing_trunk->trunk->chan->cid.cid_name);
-		free(ringing_trunk->trunk->chan->cid.cid_name);
+		ast_free(ringing_trunk->trunk->chan->cid.cid_name);
 		ringing_trunk->trunk->chan->cid.cid_name = NULL;
 	}
 	if (!sla.attempt_callerid && !ast_strlen_zero(ringing_trunk->trunk->chan->cid.cid_num)) {
 		cid_num = ast_strdupa(ringing_trunk->trunk->chan->cid.cid_num);
-		free(ringing_trunk->trunk->chan->cid.cid_num);
+		ast_free(ringing_trunk->trunk->chan->cid.cid_num);
 		ringing_trunk->trunk->chan->cid.cid_num = NULL;
 	}
 
@@ -3753,7 +3753,7 @@ static void sla_hangup_stations(void)
 			ast_dial_join(ringing_station->station->dial);
 			ast_dial_destroy(ringing_station->station->dial);
 			ringing_station->station->dial = NULL;
-			free(ringing_station);
+			ast_free(ringing_station);
 		}
 	}
 	AST_LIST_TRAVERSE_SAFE_END
@@ -4018,7 +4018,7 @@ static void *sla_thread(void *data)
 				sla_handle_ringing_trunk_event();
 				break;
 			}
-			free(event);
+			ast_free(event);
 			ast_mutex_lock(&sla.lock);
 		}
 	}
@@ -4026,10 +4026,10 @@ static void *sla_thread(void *data)
 	ast_mutex_unlock(&sla.lock);
 
 	while ((ringing_station = AST_LIST_REMOVE_HEAD(&sla.ringing_stations, entry)))
-		free(ringing_station);
+		ast_free(ringing_station);
 
 	while ((failed_station = AST_LIST_REMOVE_HEAD(&sla.failed_stations, entry)))
-		free(failed_station);
+		ast_free(failed_station);
 
 	return NULL;
 }
@@ -4072,12 +4072,12 @@ static void *dial_trunk(void *data)
 
 	if (!sla.attempt_callerid && !ast_strlen_zero(trunk_ref->chan->cid.cid_name)) {
 		cid_name = ast_strdupa(trunk_ref->chan->cid.cid_name);
-		free(trunk_ref->chan->cid.cid_name);
+		ast_free(trunk_ref->chan->cid.cid_name);
 		trunk_ref->chan->cid.cid_name = NULL;
 	}
 	if (!sla.attempt_callerid && !ast_strlen_zero(trunk_ref->chan->cid.cid_num)) {
 		cid_num = ast_strdupa(trunk_ref->chan->cid.cid_num);
-		free(trunk_ref->chan->cid.cid_num);
+		ast_free(trunk_ref->chan->cid.cid_num);
 		trunk_ref->chan->cid.cid_num = NULL;
 	}
 
@@ -4389,7 +4389,7 @@ static int sla_trunk_exec(struct ast_channel *chan, void *data)
 	ast_mutex_unlock(&sla.lock);
 	if (ringing_trunk) {
 		sla_change_trunk_state(ringing_trunk->trunk, SLA_TRUNK_STATE_IDLE, ALL_TRUNK_REFS, NULL);
-		free(ringing_trunk);
+		ast_free(ringing_trunk);
 		pbx_builtin_setvar_helper(chan, "SLATRUNK_STATUS", "UNANSWERED");
 		/* Queue reprocessing of ringing trunks to make stations stop ringing
 		 * that shouldn't be ringing after this trunk stopped. */
@@ -4457,10 +4457,10 @@ static void destroy_trunk(struct sla_trunk *trunk)
 		ast_context_remove_extension(trunk->autocontext, "s", 1, sla_registrar);
 
 	while ((station_ref = AST_LIST_REMOVE_HEAD(&trunk->stations, entry)))
-		free(station_ref);
+		ast_free(station_ref);
 
 	ast_string_field_free_all(trunk);
-	free(trunk);
+	ast_free(trunk);
 }
 
 static void destroy_station(struct sla_station *station)
@@ -4483,10 +4483,10 @@ static void destroy_station(struct sla_station *station)
 	}
 
 	while ((trunk_ref = AST_LIST_REMOVE_HEAD(&station->trunks, entry)))
-		free(trunk_ref);
+		ast_free(trunk_ref);
 
 	ast_string_field_free_all(station);
-	free(station);
+	ast_free(station);
 }
 
 static void sla_destroy(void)
@@ -4549,7 +4549,7 @@ static int sla_build_trunk(struct ast_config *cfg, const char *cat)
 	if (!(trunk = ast_calloc(1, sizeof(*trunk))))
 		return -1;
 	if (ast_string_field_init(trunk, 32)) {
-		free(trunk);
+		ast_free(trunk);
 		return -1;
 	}
 
@@ -4654,7 +4654,7 @@ static void sla_add_trunk_to_station(struct sla_station *station, struct ast_var
 	}
 
 	if (!(station_ref = sla_create_station_ref(station))) {
-		free(trunk_ref);
+		ast_free(trunk_ref);
 		return;
 	}
 	ast_atomic_fetchadd_int((int *) &trunk->num_stations, 1);
@@ -4678,7 +4678,7 @@ static int sla_build_station(struct ast_config *cfg, const char *cat)
 	if (!(station = ast_calloc(1, sizeof(*station))))
 		return -1;
 	if (ast_string_field_init(station, 32)) {
-		free(station);
+		ast_free(station);
 		return -1;
 	}
 
diff --git a/apps/app_milliwatt.c b/apps/app_milliwatt.c
index 5a2a9e18d764ddc308d684323f4aa144227a58c2..31ded36d6dbd18c1d237158df6577b8867524a62 100644
--- a/apps/app_milliwatt.c
+++ b/apps/app_milliwatt.c
@@ -59,7 +59,7 @@ static void *milliwatt_alloc(struct ast_channel *chan, void *params)
 
 static void milliwatt_release(struct ast_channel *chan, void *data)
 {
-	free(data);
+	ast_free(data);
 	return;
 }
 
diff --git a/apps/app_minivm.c b/apps/app_minivm.c
index 95a2b10d8da93cb379c1da5ba0ec84ef15ee930c..62b589c808a367d033775b031209991ef0765dbc 100644
--- a/apps/app_minivm.c
+++ b/apps/app_minivm.c
@@ -470,7 +470,7 @@ static struct minivm_template *message_template_create(const char *name)
 {
 	struct minivm_template *template;
 
-	template = ast_calloc(1, sizeof(struct minivm_template));
+	template = ast_calloc(1, sizeof(*template));
 	if (!template)
 		return NULL;
 
@@ -488,9 +488,9 @@ static struct minivm_template *message_template_create(const char *name)
 static void message_template_free(struct minivm_template *template)
 {
 	if (template->body)
-		free(template->body);
+		ast_free(template->body);
 
-	free (template);
+	ast_free (template);
 }
 
 /*! \brief Build message template from configuration */
@@ -524,7 +524,7 @@ static int message_template_build(const char *name, struct ast_variable *var)
 			ast_copy_string(template->charset, var->value, sizeof(template->charset));
 		} else if (!strcasecmp(var->name, "templatefile")) {
 			if (template->body) 
-				free(template->body);
+				ast_free(template->body);
 			template->body = message_template_parse_filebody(var->value);
 			if (!template->body) {
 				ast_log(LOG_ERROR, "Error reading message body definition file %s\n", var->value);
@@ -532,7 +532,7 @@ static int message_template_build(const char *name, struct ast_variable *var)
 			}
 		} else if (!strcasecmp(var->name, "messagebody")) {
 			if (template->body) 
-				free(template->body);
+				ast_free(template->body);
 			template->body = message_template_parse_emailbody(var->value);
 			if (!template->body) {
 				ast_log(LOG_ERROR, "Error parsing message body definition:\n          %s\n", var->value);
@@ -727,7 +727,7 @@ static void free_user(struct minivm_account *vmu)
 {
 	if (vmu->chanvars)
 		ast_variables_destroy(vmu->chanvars);
-	free(vmu);
+	ast_free(vmu);
 }
 
 
@@ -793,7 +793,7 @@ static struct minivm_account *mvm_user_alloc(void)
 {
 	struct minivm_account *new;
 
-	new = calloc(1, sizeof(struct minivm_account));
+	new = ast_calloc(1, sizeof(*new));
 	if (!new)
 		return NULL;
 	populate_defaults(new);
@@ -808,7 +808,7 @@ static void vmaccounts_destroy_list(void)
 	struct minivm_account *this;
 	AST_LIST_LOCK(&minivm_accounts);
 	while ((this = AST_LIST_REMOVE_HEAD(&minivm_accounts, list))) 
-		free(this);
+		ast_free(this);
 	AST_LIST_UNLOCK(&minivm_accounts);
 }
 
@@ -877,7 +877,7 @@ static struct minivm_account *find_user_realtime(const char *domain, const char
 	var = ast_load_realtime("minivm", "username", username, "domain", domain, NULL);
 
 	if (!var) {
-		free(retval);
+		ast_free(retval);
 		return NULL;
 	}
 
@@ -2201,7 +2201,7 @@ static int create_vmaccount(char *name, struct ast_variable *var, int realtime)
 		ast_log(LOG_DEBUG, "Creating static account for user %s domain %s\n", username, domain);
 
 	/* Allocate user account */
-	vmu = ast_calloc(1, sizeof(struct minivm_account));
+	vmu = ast_calloc(1, sizeof(*vmu));
 	if (!vmu)
 		return 0;
 	
@@ -2277,7 +2277,7 @@ static int create_vmaccount(char *name, struct ast_variable *var, int realtime)
 /*! \brief Free Mini Voicemail timezone */
 static void free_zone(struct minivm_zone *z)
 {
-	free(z);
+	ast_free(z);
 }
 
 /*! \brief Clear list of timezones */
@@ -2299,21 +2299,21 @@ static int timezone_add(char *zonename, char *config)
 	struct minivm_zone *newzone;
 	char *msg_format, *timezone;
 
-	newzone = ast_calloc(1, sizeof(struct minivm_zone));
+	newzone = ast_calloc(1, sizeof(*newzone));
 	if (newzone == NULL)
 		return 0;
 
 	msg_format = ast_strdupa(config);
 	if (msg_format == NULL) {
 		ast_log(LOG_WARNING, "Out of memory.\n");
-		free(newzone);
+		ast_free(newzone);
 		return 0;
 	}
 
 	timezone = strsep(&msg_format, "|");
 	if (!msg_format) {
 		ast_log(LOG_WARNING, "Invalid timezone definition : %s\n", zonename);
-		free(newzone);
+		ast_free(newzone);
 		return 0;
 	}
 			
diff --git a/apps/app_mixmonitor.c b/apps/app_mixmonitor.c
index 542d323dc67fe0b41d883c33c680ed622fb4d07b..96782c53749e470b7e2d44c0651b5a4363b8c177 100644
--- a/apps/app_mixmonitor.c
+++ b/apps/app_mixmonitor.c
@@ -220,7 +220,7 @@ static void *mixmonitor_thread(void *obj)
 	if (fs)
 		ast_closestream(fs);
 
-	free(mixmonitor);
+	ast_free(mixmonitor);
 
 
 	return NULL;
@@ -253,7 +253,7 @@ static void launch_monitor_thread(struct ast_channel *chan, const char *filename
 	}
 
 	/* Pre-allocate mixmonitor structure and spy */
-	if (!(mixmonitor = calloc(1, len))) {
+	if (!(mixmonitor = ast_calloc(1, len))) {
 		return;
 	}
 
@@ -291,7 +291,7 @@ static void launch_monitor_thread(struct ast_channel *chan, const char *filename
 			mixmonitor->spy.type, chan->name);
 		/* Since we couldn't add ourselves - bail out! */
 		ast_mutex_destroy(&mixmonitor->spy.lock);
-		free(mixmonitor);
+		ast_free(mixmonitor);
 		return;
 	}
 
diff --git a/apps/app_osplookup.c b/apps/app_osplookup.c
index 59e4fb0ed41eb4257e949b7c0152792563f297ec..c7ff964b57d9fdbe18484190eaa1d70d4bec56f3 100644
--- a/apps/app_osplookup.c
+++ b/apps/app_osplookup.c
@@ -328,7 +328,7 @@ static int osp_create_provider(
 	error = OSPPUtilLoadPEMPrivateKey((unsigned char*)p->privatekey, &privatekey);
 	if (error != OSPC_ERR_NO_ERROR) {
 		ast_log(LOG_WARNING, "OSP: Unable to load privatekey '%s', error '%d'\n", p->privatekey, error);
-		free(p);
+		ast_free(p);
 		return 0;
 	}
 
@@ -336,9 +336,9 @@ static int osp_create_provider(
 	if (error != OSPC_ERR_NO_ERROR) {
 		ast_log(LOG_WARNING, "OSP: Unable to load localcert '%s', error '%d'\n", p->localcert, error);
 		if (privatekey.PrivateKeyData) {
-			free(privatekey.PrivateKeyData);
+			ast_free(privatekey.PrivateKeyData);
 		}
-		free(p);
+		ast_free(p);
 		return 0;
 	}
 
@@ -354,16 +354,16 @@ static int osp_create_provider(
 			ast_log(LOG_WARNING, "OSP: Unable to load cacert '%s', error '%d'\n", p->cacerts[i], error);
 			for (j = 0; j < i; j++) {
 				if (cacerts[j].CertData) {
-					free(cacerts[j].CertData);
+					ast_free(cacerts[j].CertData);
 				}
 			}
 			if (localcert.CertData) {
-				free(localcert.CertData);
+				ast_free(localcert.CertData);
 			}
 			if (privatekey.PrivateKeyData) {
-				free(privatekey.PrivateKeyData);
+				ast_free(privatekey.PrivateKeyData);
 			}
-			free(p);
+			ast_free(p);
 			return 0;
 		}
 		pcacerts[i] = &cacerts[i];
@@ -394,7 +394,7 @@ static int osp_create_provider(
 				&p->handle);
 	if (error != OSPC_ERR_NO_ERROR) {
 		ast_log(LOG_WARNING, "OSP: Unable to create provider '%s', error '%d'\n", provider, error);
-		free(p);
+		ast_free(p);
 		res = -1;
 	} else {
 		if (option_debug)
@@ -408,14 +408,14 @@ static int osp_create_provider(
 
 	for (i = 0; i < p->cacount; i++) {
 		if (cacerts[i].CertData) {
-			free(cacerts[i].CertData);
+			ast_free(cacerts[i].CertData);
 		}
 	}
 	if (localcert.CertData) {
-		free(localcert.CertData);
+		ast_free(localcert.CertData);
 	}
 	if (privatekey.PrivateKeyData) {
-		free(privatekey.PrivateKeyData);
+		ast_free(privatekey.PrivateKeyData);
 	}
 
 	return res;
@@ -2009,7 +2009,7 @@ static int osp_unload(void)
 		while(p) {
 			next = p->next;
 			OSPPProviderDelete(p->handle, 0);
-			free(p);
+			ast_free(p);
 			p = next;
 		}
 		ospproviders = NULL;
diff --git a/apps/app_queue.c b/apps/app_queue.c
index 7d06d2df299926dd08333f2e470d36bb7fab0dc2..f0e6dae797d492d96b614f40191192eaef0cebec 100644
--- a/apps/app_queue.c
+++ b/apps/app_queue.c
@@ -831,7 +831,7 @@ static int remove_from_interfaces(const char *interface)
 				if (option_debug)
 					ast_log(LOG_DEBUG, "Removing %s from the list of interfaces that make up all of our queue members.\n", interface);
 				AST_LIST_REMOVE_CURRENT(&interfaces, list);
-				free(curint);
+				ast_free(curint);
 			}
 			break;
 		}
@@ -848,7 +848,7 @@ static void clear_and_free_interfaces(void)
 
 	AST_LIST_LOCK(&interfaces);
 	while ((curint = AST_LIST_REMOVE_HEAD(&interfaces, list)))
-		free(curint);
+		ast_free(curint);
 	AST_LIST_UNLOCK(&interfaces);
 }
 
@@ -1076,7 +1076,7 @@ static void free_members(struct call_queue *q, int all)
 			else
 				q->members = next;
 			remove_from_interfaces(curm->interface);
-			free(curm);
+			ast_free(curm);
 		} else
 			prev = curm;
 	}
@@ -1086,7 +1086,7 @@ static void destroy_queue(struct call_queue *q)
 {
 	free_members(q, 1);
 	ast_mutex_destroy(&q->lock);
-	free(q);
+	ast_free(q);
 }
 
 /*!\brief Reload a single queue via realtime.
@@ -1196,7 +1196,7 @@ static struct call_queue *find_queue_by_name_rt(const char *queuename, struct as
 				q->members = next_m;
 			}
 			remove_from_interfaces(m->interface);
-			free(m);
+			ast_free(m);
 		} else {
 			prev_m = m;
 		}
@@ -1546,7 +1546,7 @@ static void hangupcalls(struct callattempt *outgoing, struct ast_channel *except
 			ast_hangup(outgoing->chan);
 		oo = outgoing;
 		outgoing = outgoing->q_next;
-		free(oo);
+		ast_free(oo);
 	}
 }
 
@@ -1747,13 +1747,13 @@ static int ring_entry(struct queue_ent *qe, struct callattempt *tmp, int *busies
 	tmp->chan->data = "(Outgoing Line)";
 	tmp->chan->whentohangup = 0;
 	if (tmp->chan->cid.cid_num)
-		free(tmp->chan->cid.cid_num);
+		ast_free(tmp->chan->cid.cid_num);
 	tmp->chan->cid.cid_num = ast_strdup(qe->chan->cid.cid_num);
 	if (tmp->chan->cid.cid_name)
-		free(tmp->chan->cid.cid_name);
+		ast_free(tmp->chan->cid.cid_name);
 	tmp->chan->cid.cid_name = ast_strdup(qe->chan->cid.cid_name);
 	if (tmp->chan->cid.cid_ani)
-		free(tmp->chan->cid.cid_ani);
+		ast_free(tmp->chan->cid.cid_ani);
 	tmp->chan->cid.cid_ani = ast_strdup(qe->chan->cid.cid_ani);
 
 	/* Inherit specially named variables from parent channel */
@@ -2067,11 +2067,11 @@ static struct callattempt *wait_for_answer(struct queue_ent *qe, struct callatte
 					} else {
 						ast_channel_inherit_variables(in, o->chan);
 						if (o->chan->cid.cid_num)
-							free(o->chan->cid.cid_num);
+							ast_free(o->chan->cid.cid_num);
 						o->chan->cid.cid_num = ast_strdup(in->cid.cid_num);
 
 						if (o->chan->cid.cid_name)
-							free(o->chan->cid.cid_name);
+							ast_free(o->chan->cid.cid_name);
 						o->chan->cid.cid_name = ast_strdup(in->cid.cid_name);
 
 						ast_string_field_set(o->chan, accountcode, in->accountcode);
@@ -2079,11 +2079,11 @@ static struct callattempt *wait_for_answer(struct queue_ent *qe, struct callatte
 
 						if (in->cid.cid_ani) {
 							if (o->chan->cid.cid_ani)
-								free(o->chan->cid.cid_ani);
+								ast_free(o->chan->cid.cid_ani);
 							o->chan->cid.cid_ani = ast_strdup(in->cid.cid_ani);
 						}
 						if (o->chan->cid.cid_rdnis)
-							free(o->chan->cid.cid_rdnis);
+							ast_free(o->chan->cid.cid_rdnis);
 						o->chan->cid.cid_rdnis = ast_strdup(S_OR(in->macroexten, in->exten));
 						if (ast_call(o->chan, tmpchan, 0)) {
 							ast_log(LOG_NOTICE, "Failed to dial on local channel for call forward to '%s'\n", tmpchan);
@@ -2547,7 +2547,7 @@ static int try_calling(struct queue_ent *qe, const char *options, char *announce
 			if (outgoing->chan && (outgoing->chan->_state == AST_STATE_UP))
 				break;
 		} else {
-			free(tmp);
+			ast_free(tmp);
 		}
 	}
 	if (qe->expire && (!qe->parent->timeout || (qe->expire - now) <= qe->parent->timeout))
@@ -2964,7 +2964,7 @@ static int remove_from_queue(const char *queuename, const char *interface)
 				"Location: %s\r\n"
 				"MemberName: %s\r\n",
 				q->name, last_member->interface, last_member->membername);
-			free(last_member);
+			ast_free(last_member);
 			
 			if (queue_persistent_members)
 				dump_queue_members(q);
@@ -4087,7 +4087,7 @@ static int reload_queues(void)
 							} else {
 								q->members = newm;
 							}
-							free(cur);
+							ast_free(cur);
 						} else {
 							/* Add them to the master int list if necessary */
 							add_to_interfaces(interface);
@@ -4116,7 +4116,7 @@ static int reload_queues(void)
 						q->members = next;
 
 					remove_from_interfaces(cur->interface);
-					free(cur);
+					ast_free(cur);
 				}
 
 				if (new) {
diff --git a/apps/app_readfile.c b/apps/app_readfile.c
index 7e43a38064c89fc4059d9a771133547dd003580e..62221570c5010aaef00be5b6e51a9b9349832e51 100644
--- a/apps/app_readfile.c
+++ b/apps/app_readfile.c
@@ -94,7 +94,7 @@ static int readfile_exec(struct ast_channel *chan, void *data)
 				ast_log(LOG_WARNING, "%s is longer than %d, and %d \n", file, len, (int)strlen(returnvar));
 		}
 		pbx_builtin_setvar_helper(chan, varname, returnvar);
-		free(returnvar);
+		ast_free(returnvar);
 	}
 	ast_module_user_remove(u);
 	return res;
diff --git a/apps/app_rpt.c b/apps/app_rpt.c
index e59a7bbb58466977c8711bb747b4b710ffa8b658..cfded49c91d3c72bfb77d1690b7c26147e3202da 100644
--- a/apps/app_rpt.c
+++ b/apps/app_rpt.c
@@ -1353,7 +1353,7 @@ static int rpt_do_lstats(int fd, int argc, char *argv[])
 					l = l->next;
 					continue;
 				}
-				if ((s = (struct rpt_lstat *) ast_calloc(1, sizeof(struct rpt_lstat))) == NULL) {
+				if ((s = ast_calloc(1, sizeof(*s))) == NULL) {
 					ast_log(LOG_ERROR, "Malloc failed in rpt_do_lstats\n");
 					rpt_mutex_unlock(&myrpt->lock); /* UNLOCK */
 					return RESULT_FAILURE;
@@ -2186,7 +2186,7 @@ static void *rpt_tele_thread(void *this)
 				l = l->next;
 				continue;
 			}
-			m = ast_malloc(sizeof(struct rpt_link));
+			m = ast_malloc(sizeof(*m));
 			if (!m) {
 				ast_log(LOG_WARNING, "Cannot alloc memory on %s\n", mychannel->name);
 				remque((struct qelem *)mytele);
@@ -2453,7 +2453,7 @@ static void rpt_telemetry(struct rpt *myrpt, int mode, void *data)
 	struct rpt_link *mylink = (struct rpt_link *) data;
 	int res;
 
-	tele = ast_calloc(1, sizeof(struct rpt_tele));
+	tele = ast_calloc(1, sizeof(*tele));
 	if (!tele) {
 		ast_log(LOG_WARNING, "Unable to allocate memory\n");
 		pthread_exit(NULL);
@@ -2869,7 +2869,7 @@ static int function_ilink(struct rpt *myrpt, char *param, char *digits, int comm
 			rpt_mutex_unlock(&myrpt->lock);
 		ast_copy_string(myrpt->lastlinknode, digitbuf, MAXNODESTR);
 		/* establish call in monitor mode */
-		l = ast_calloc(1, sizeof(struct rpt_link));
+		l = ast_calloc(1, sizeof(*l));
 		if (!l) {
 			ast_log(LOG_WARNING, "Unable to malloc\n");
 			return DC_ERROR;
@@ -2979,7 +2979,7 @@ static int function_ilink(struct rpt *myrpt, char *param, char *digits, int comm
 			rpt_mutex_unlock(&myrpt->lock);
 		ast_copy_string(myrpt->lastlinknode, digitbuf, MAXNODESTR);
 		/* establish call in tranceive mode */
-		l = ast_calloc(1, sizeof(struct rpt_link));
+		l = ast_calloc(1, sizeof(*l));
 		if (!l) {
 			ast_log(LOG_WARNING, "Unable to malloc\n");
 			return DC_ERROR;
@@ -6982,7 +6982,7 @@ static int rpt_exec(struct ast_channel *chan, void *data)
 		} else 
 			rpt_mutex_unlock(&myrpt->lock);
 		/* establish call in tranceive mode */
-		l = ast_calloc(1, sizeof(struct rpt_link));
+		l = ast_calloc(1, sizeof(*l));
 		if (!l) {
 			ast_log(LOG_WARNING, "Unable to malloc\n");
 			pthread_exit(NULL);
diff --git a/apps/app_speech_utils.c b/apps/app_speech_utils.c
index 100b174d9c2409ac43c93db1c4d166f4d8fc861b..0956e0bab18bde8f82b3914f57fb426af5207dbc 100644
--- a/apps/app_speech_utils.c
+++ b/apps/app_speech_utils.c
@@ -511,7 +511,7 @@ static int speech_processing_sound(struct ast_channel *chan, void *data)
         }
 
 	if (speech->processing_sound != NULL) {
-		free(speech->processing_sound);
+		ast_free(speech->processing_sound);
 		speech->processing_sound = NULL;
 	}
 
diff --git a/apps/app_voicemail.c b/apps/app_voicemail.c
index 7c1c2d9cf5555fa3c04a49b7ed8c14c3296ae3b1..750bc5a414d6584294dc0ae99a04e1bba4d571f3 100644
--- a/apps/app_voicemail.c
+++ b/apps/app_voicemail.c
@@ -793,7 +793,7 @@ static struct ast_vm_user *find_user_realtime(struct ast_vm_user *ivm, const cha
 			ast_variables_destroy(var);
 		} else { 
 			if (!ivm) 
-				free(retval);
+				ast_free(retval);
 			retval = NULL;
 		}	
 	} 
@@ -2287,12 +2287,12 @@ static void free_user(struct ast_vm_user *vmu)
 	if (!ast_test_flag(vmu, VM_ALLOCED))
 		return;
 
-	free(vmu);
+	ast_free(vmu);
 }
 
 static void free_zone(struct vm_zone *z)
 {
-	free(z);
+	ast_free(z);
 }
 
 static const char *mbox(int id)
@@ -8047,10 +8047,9 @@ static int load_config(void)
 								AST_LIST_UNLOCK(&zones);
 							} else {
 								ast_log(LOG_WARNING, "Invalid timezone definition at line %d\n", var->lineno);
-								free(z);
+								ast_free(z);
 							}
 						} else {
-							free(z);
 							AST_LIST_UNLOCK(&users);
 							ast_config_destroy(cfg);
 							return -1;
@@ -8066,19 +8065,19 @@ static int load_config(void)
 		memset(emailtitle,0,sizeof(emailtitle));
 		strcpy(charset, "ISO-8859-1");
 		if (emailbody) {
-			free(emailbody);
+			ast_free(emailbody);
 			emailbody = NULL;
 		}
 		if (emailsubject) {
-			free(emailsubject);
+			ast_free(emailsubject);
 			emailsubject = NULL;
 		}
 		if (pagerbody) {
-			free(pagerbody);
+			ast_free(pagerbody);
 			pagerbody = NULL;
 		}
 		if (pagersubject) {
-			free(pagersubject);
+			ast_free(pagersubject);
 			pagersubject = NULL;
 		}
 		if ((s = ast_variable_retrieve(cfg, "general", "pbxskip")))
@@ -8938,7 +8937,7 @@ static struct ast_vm_user *find_user_realtime_imapuser(const char *imapuser)
 		ast_variables_destroy(var);
 		return vmu;
 	} else {
-		free(vmu);
+		ast_free(vmu);
 		return NULL;
 	}
 }
@@ -9320,7 +9319,7 @@ static void vmstate_delete(struct vm_state *vms)
 	AST_LIST_UNLOCK(&vmstates);
 	
 	if (vc)
-		free(vc);
+		ast_free(vc);
 	else
 		ast_log(LOG_ERROR, "No vmstate found for user:%s, mailbox %s\n", vms->imapuser, vms->username);
 }
diff --git a/cdr/cdr_adaptive_odbc.c b/cdr/cdr_adaptive_odbc.c
index c7a2826177c72322f3e4a9d8b319282d45fc780a..9814079a474b5f7ba914fa792d85bf5db0a89818 100644
--- a/cdr/cdr_adaptive_odbc.c
+++ b/cdr/cdr_adaptive_odbc.c
@@ -211,7 +211,7 @@ static int load_config(void)
 		if (AST_LIST_FIRST(&(tableptr->columns)))
 			AST_RWLIST_INSERT_TAIL(&odbc_tables, tableptr, list);
 		else
-			free(tableptr);
+			ast_free(tableptr);
 	}
 	return res;
 }
diff --git a/cdr/cdr_odbc.c b/cdr/cdr_odbc.c
index 6738aa6d9c1a32d3cd57bf4349b07c5d8d4a42e9..1a8b52143b5e948c34da4b8612ab0ffda75657d0 100644
--- a/cdr/cdr_odbc.c
+++ b/cdr/cdr_odbc.c
@@ -218,22 +218,22 @@ static int odbc_unload_module(void)
 	if (dsn) {
 		if (option_verbose > 10)
 			ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: free dsn\n");
-		free(dsn);
+		ast_free(dsn);
 	}
 	if (username) {
 		if (option_verbose > 10)
 			ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: free username\n");
-		free(username);
+		ast_free(username);
 	}
 	if (password) {
 		if (option_verbose > 10)
 			ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: free password\n");
-		free(password);
+		ast_free(password);
 	}
 	if (table) {
 		if (option_verbose > 10)
 			ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: free table\n");
-		free(table);
+		ast_free(table);
 	}
 
 	ast_cdr_unregister(name);
diff --git a/cdr/cdr_pgsql.c b/cdr/cdr_pgsql.c
index 34feca621093168b1cb4340cde6bd45d1ba7b7b2..39639bd702b8f7740353c259a97d10f085d8e331 100644
--- a/cdr/cdr_pgsql.c
+++ b/cdr/cdr_pgsql.c
@@ -184,17 +184,17 @@ static int my_unload_module(void)
 	if (conn)
 		PQfinish(conn);
 	if (pghostname)
-		free(pghostname);
+		ast_free(pghostname);
 	if (pgdbname)
-		free(pgdbname);
+		ast_free(pgdbname);
 	if (pgdbuser)
-		free(pgdbuser);
+		ast_free(pgdbuser);
 	if (pgpassword)
-		free(pgpassword);
+		ast_free(pgpassword);
 	if (pgdbport)
-		free(pgdbport);
+		ast_free(pgdbport);
 	if (table)
-		free(table);
+		ast_free(table);
 	ast_cdr_unregister(name);
 	return 0;
 }
diff --git a/cdr/cdr_sqlite.c b/cdr/cdr_sqlite.c
index bd232b450691e0fd7f9ece0bd16f1a20fa03fca2..b47dd350c7ce2c437f573d0a8130506a6e18585c 100644
--- a/cdr/cdr_sqlite.c
+++ b/cdr/cdr_sqlite.c
@@ -161,7 +161,7 @@ static int sqlite_log(struct ast_cdr *cdr)
 	
 	if (zErr) {
 		ast_log(LOG_ERROR, "cdr_sqlite: %s\n", zErr);
-		free(zErr);
+		ast_free(zErr);
 	}
 
 	ast_mutex_unlock(&sqlite_lock);
@@ -190,7 +190,7 @@ static int load_module(void)
 	db = sqlite_open(fn, AST_FILE_MODE, &zErr);
 	if (!db) {
 		ast_log(LOG_ERROR, "cdr_sqlite: %s\n", zErr);
-		free(zErr);
+		ast_free(zErr);
 		return -1;
 	}
 
@@ -200,7 +200,7 @@ static int load_module(void)
 		res = sqlite_exec(db, sql_create_table, NULL, NULL, &zErr);
 		if (res) {
 			ast_log(LOG_ERROR, "cdr_sqlite: Unable to create table 'cdr': %s\n", zErr);
-			free(zErr);
+			ast_free(zErr);
 			goto err;
 		}
 
diff --git a/cdr/cdr_tds.c b/cdr/cdr_tds.c
index b4d51729a3128657f4482cf0e0626f90871479c9..736199a4ad1b5592415dbf66c164bd41ca066b66 100644
--- a/cdr/cdr_tds.c
+++ b/cdr/cdr_tds.c
@@ -221,16 +221,16 @@ static int tds_log(struct ast_cdr *cdr)
 		}
 	} while (!connected && !retried);
 
-	free(accountcode);
-	free(src);
-	free(dst);
-	free(dcontext);
-	free(clid);
-	free(channel);
-	free(dstchannel);
-	free(lastapp);
-	free(lastdata);
-	free(uniqueid);
+	ast_free(accountcode);
+	ast_free(src);
+	ast_free(dst);
+	ast_free(dcontext);
+	ast_free(clid);
+	ast_free(channel);
+	ast_free(dstchannel);
+	ast_free(lastapp);
+	ast_free(lastdata);
+	ast_free(uniqueid);
 
 	ast_mutex_unlock(&tds_lock);
 
@@ -246,7 +246,7 @@ static char *anti_injection(const char *str, int len)
 	char *known_bad[] = {"select", "insert", "update", "delete", "drop", ";", "--", "\0"};
 	int idx;
 
-	if ((buf = malloc(len + 1)) == NULL)
+	if ((buf = ast_malloc(len + 1)) == NULL)
 	{
 		ast_log(LOG_ERROR, "cdr_tds:  Out of memory error\n");
 		return NULL;
@@ -413,13 +413,13 @@ static int tds_unload_module(void)
 
 	ast_cdr_unregister(name);
 
-	if (hostname) free(hostname);
-	if (dbname) free(dbname);
-	if (dbuser) free(dbuser);
-	if (password) free(password);
-	if (charset) free(charset);
-	if (language) free(language);
-	if (table) free(table);
+	if (hostname) ast_free(hostname);
+	if (dbname) ast_free(dbname);
+	if (dbuser) ast_free(dbuser);
+	if (password) ast_free(password);
+	if (charset) ast_free(charset);
+	if (language) ast_free(language);
+	if (table) ast_free(table);
 
 	return 0;
 }
diff --git a/channels/chan_agent.c b/channels/chan_agent.c
index 603b45482c816eb840912d2c2ceaf46b60455a4c..739c35dd1339dc59df65585abbf24c09b09ba43e 100644
--- a/channels/chan_agent.c
+++ b/channels/chan_agent.c
@@ -378,7 +378,7 @@ static int agent_cleanup(struct agent_pvt *p)
 	if (p->dead) {
 		ast_mutex_destroy(&p->lock);
 		ast_mutex_destroy(&p->app_lock);
-		free(p);
+		ast_free(p);
         }
 	return 0;
 }
@@ -810,7 +810,7 @@ static int agent_hangup(struct ast_channel *ast)
 	} else if (p->dead) {
 		ast_mutex_destroy(&p->lock);
 		ast_mutex_destroy(&p->app_lock);
-		free(p);
+		ast_free(p);
 	} else {
 		if (p->chan) {
 			/* Not dead -- check availability now */
@@ -1136,7 +1136,7 @@ static int read_agent_config(void)
 				if (!p->chan) {
 					ast_mutex_destroy(&p->lock);
 					ast_mutex_destroy(&p->app_lock);
-					free(p);
+					ast_free(p);
 				} else {
 					/* Cause them to hang up */
 					ast_softhangup(p->chan, AST_SOFTHANGUP_EXPLICIT);
@@ -2118,7 +2118,7 @@ static int __login_exec(struct ast_channel *chan, void *data, int callbackmode)
 						if (p->dead && !p->owner) {
 							ast_mutex_destroy(&p->lock);
 							ast_mutex_destroy(&p->app_lock);
-							free(p);
+							ast_free(p);
 						}
 					}
 					else {
@@ -2531,7 +2531,7 @@ static int unload_module(void)
 	while ((p = AST_LIST_REMOVE_HEAD(&agents, list))) {
 		if (p->owner)
 			ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
-		free(p);
+		ast_free(p);
 	}
 	AST_LIST_UNLOCK(&agents);
 	AST_LIST_HEAD_DESTROY(&agents);
diff --git a/channels/chan_gtalk.c b/channels/chan_gtalk.c
index d27e03109e7f4e0e436cfb7bd5cb312764de38bb..1402a5a2574cca504b6340c744372bb957b3332e 100644
--- a/channels/chan_gtalk.c
+++ b/channels/chan_gtalk.c
@@ -257,7 +257,7 @@ static struct gtalk_container gtalk_list;
 
 static void gtalk_member_destroy(struct gtalk *obj)
 {
-	free(obj);
+	ast_free(obj);
 }
 
 static struct gtalk *find_gtalk(char *name, char *connection)
@@ -817,9 +817,9 @@ static int gtalk_create_candidates(struct gtalk *client, struct gtalk_pvt *p, ch
 
 safeout:
 	if (ours1)
-		free(ours1);
+		ast_free(ours1);
 	if (ours2)
-		free(ours2);
+		ast_free(ours2);
 	if (iq)
 		iks_delete(iq);
 	if (gtalk)
@@ -1036,7 +1036,7 @@ static void gtalk_free_candidates(struct gtalk_candidate *candidate)
 	while (candidate) {
 		last = candidate;
 		candidate = candidate->next;
-		free(last);
+		ast_free(last);
 	}
 }
 
@@ -1064,7 +1064,7 @@ static void gtalk_free_pvt(struct gtalk *client, struct gtalk_pvt *p)
 	if (p->vrtp)
 		ast_rtp_destroy(p->vrtp);
 	gtalk_free_candidates(p->theircandidates);
-	free(p);
+	ast_free(p);
 }
 
 
diff --git a/channels/chan_iax2.c b/channels/chan_iax2.c
index ebad18fb3fe7124159f323c0e45c73dc2b200106..94ebdcf8b489e544f65edec1ad50efe60b6d8c93 100644
--- a/channels/chan_iax2.c
+++ b/channels/chan_iax2.c
@@ -968,7 +968,7 @@ static struct iax2_thread *find_idle_thread(void)
 	if (ast_pthread_create_detached_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
 		ast_cond_destroy(&thread->cond);
 		ast_mutex_destroy(&thread->lock);
-		free(thread);
+		ast_free(thread);
 		thread = NULL;
 	}
 
@@ -1160,7 +1160,7 @@ static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer, cons
 		return NULL;
 
 	if (ast_string_field_init(tmp, 32)) {
-		free(tmp);
+		ast_free(tmp);
 		tmp = NULL;
 		return NULL;
 	}
@@ -1444,7 +1444,7 @@ static void destroy_firmware(struct iax_firmware *cur)
 		munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
 	}
 	close(cur->fd);
-	free(cur);
+	ast_free(cur);
 }
 
 static int try_firmware(char *s)
@@ -1910,7 +1910,7 @@ retry:
 			jb_destroy(pvt->jb);
 			/* gotta free up the stringfields */
 			ast_string_field_free_pools(pvt);
-			free(pvt);
+			ast_free(pvt);
 		}
 	}
 	if (owner) {
@@ -3187,7 +3187,7 @@ static int iax2_setoption(struct ast_channel *c, int option, void *data, int dat
 		res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
 					  AST_CONTROL_OPTION, 0, (unsigned char *) h,
 					  datalen + sizeof(*h), -1);
-		free(h);
+		ast_free(h);
 		return res;
 	}
 }
@@ -5638,7 +5638,7 @@ static int iax2_append_register(const char *hostname, const char *username,
 		return -1;
 
 	if (ast_dnsmgr_lookup(hostname, &reg->addr.sin_addr, &reg->dnsmgr) < 0) {
-		free(reg);
+		ast_free(reg);
 		return -1;
 	}
 
@@ -6247,10 +6247,10 @@ static int timing_read(int *id, int fd, short events, void *cbdata)
 		   because by the time they could get tpeerlock, we've already grabbed it */
 		if (option_debug)
 			ast_log(LOG_DEBUG, "Dropping unused iax2 trunk peer '%s:%d'\n", ast_inet_ntoa(drop->addr.sin_addr), ntohs(drop->addr.sin_port));
-		free(drop->trunkdata);
+		ast_free(drop->trunkdata);
 		ast_mutex_unlock(&drop->lock);
 		ast_mutex_destroy(&drop->lock);
-		free(drop);
+		ast_free(drop);
 		
 	}
 
@@ -6306,8 +6306,8 @@ static void *dp_lookup_thread(void *data)
 	struct dpreq_data *dpr = data;
 	dp_lookup(dpr->callno, dpr->context, dpr->callednum, dpr->callerid, 0);
 	if (dpr->callerid)
-		free(dpr->callerid);
-	free(dpr);
+		ast_free(dpr->callerid);
+	ast_free(dpr);
 	return NULL;
 }
 
@@ -6344,7 +6344,7 @@ static void *iax_park_thread(void *stuff)
 	d = stuff;
 	chan1 = d->chan1;
 	chan2 = d->chan2;
-	free(d);
+	ast_free(d);
 	f = ast_read(chan1);
 	if (f)
 		ast_frfree(f);
@@ -6399,7 +6399,7 @@ static int iax_park(struct ast_channel *chan1, struct ast_channel *chan2)
 		if (!ast_pthread_create_detached_background(&th, NULL, iax_park_thread, d)) {
 			return 0;
 		}
-		free(d);
+		ast_free(d);
 	}
 	return -1;
 }
@@ -7299,7 +7299,7 @@ retryowner:
 									char tmp[256];
 									for (var = ies.vars; var; var = var->next) {
 										if (prev)
-											free(prev);
+											ast_free(prev);
 										prev = var;
 										snprintf(tmp, sizeof(tmp), "__~IAX2~%s", var->name);
 										pbx_builtin_setvar_helper(c, tmp, var->value);
@@ -8016,7 +8016,7 @@ static void iax2_process_thread_cleanup(void *data)
 	struct iax2_thread *thread = data;
 	ast_mutex_destroy(&thread->lock);
 	ast_cond_destroy(&thread->cond);
-	free(thread);
+	ast_free(thread);
 	ast_atomic_dec_and_test(&iaxactivethreadcount);
 }
 
@@ -8359,7 +8359,7 @@ static void free_context(struct iax2_context *con)
 	while(con) {
 		conl = con;
 		con = con->next;
-		free(conl);
+		ast_free(conl);
 	}
 }
 
@@ -8539,10 +8539,11 @@ static void *network_thread(void *ignore)
 
 static int start_network_thread(void)
 {
+	struct iax2_thread *thread;
 	int threadcount = 0;
 	int x;
 	for (x = 0; x < iaxthreadcount; x++) {
-		struct iax2_thread *thread = ast_calloc(1, sizeof(struct iax2_thread));
+		thread = ast_calloc(1, sizeof(*thread));
 		if (thread) {
 			thread->type = IAX_THREAD_TYPE_POOL;
 			thread->threadnum = ++threadcount;
@@ -8550,7 +8551,7 @@ static int start_network_thread(void)
 			ast_cond_init(&thread->cond, NULL);
 			if (ast_pthread_create_detached(&thread->threadid, NULL, iax2_process_thread, thread)) {
 				ast_log(LOG_WARNING, "Failed to create new thread!\n");
-				free(thread);
+				ast_free(thread);
 				thread = NULL;
 			}
 			AST_LIST_LOCK(&idle_list);
@@ -8726,7 +8727,7 @@ static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, st
 			peer->pokeexpire = -1;
 			peer->sockfd = defaultsockfd;
 			if (ast_string_field_init(peer, 32)) {
-				free(peer);
+				ast_free(peer);
 				peer = NULL;
 			}
 		}
@@ -8812,7 +8813,7 @@ static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, st
 					ast_clear_flag(peer, IAX_DYNAMIC);
 					if (ast_dnsmgr_lookup(v->value, &peer->addr.sin_addr, &peer->dnsmgr)) {
 						ast_string_field_free_pools(peer);
-						free(peer);
+						ast_free(peer);
 						return NULL;
 					}
 					if (!peer->addr.sin_port)
@@ -8823,7 +8824,7 @@ static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, st
 			} else if (!strcasecmp(v->name, "defaultip")) {
 				if (ast_get_ip(&peer->defaddr, v->value)) {
 					ast_string_field_free_pools(peer);
-					free(peer);
+					ast_free(peer);
 					return NULL;
 				}
 			} else if (!strcasecmp(v->name, "sourceaddress")) {
@@ -8977,7 +8978,7 @@ static struct iax2_user *build_user(const char *name, struct ast_variable *v, st
  	} else {
 		AST_LIST_UNLOCK(&users);
 		/* This is going to memset'd to 0 in the next block */
-		user = ast_calloc(sizeof(*user),1);
+		user = ast_calloc(1, sizeof(*user));
 	}
 	
 	if (user) {
@@ -8985,7 +8986,7 @@ static struct iax2_user *build_user(const char *name, struct ast_variable *v, st
 			ast_string_field_free_pools(user);
 			memset(user, 0, sizeof(struct iax2_user));
 			if (ast_string_field_init(user, 32)) {
-				free(user);
+				ast_free(user);
 				user = NULL;
 			}
 			user->maxauthreq = maxauthreq;
@@ -9178,7 +9179,7 @@ static void delete_users(void)
 		}
 		if (reg->dnsmgr)
 			ast_dnsmgr_release(reg->dnsmgr);
-		free(reg);
+		ast_free(reg);
 	}
 	AST_LIST_UNLOCK(&registrations);
 
@@ -9197,7 +9198,7 @@ static void destroy_user(struct iax2_user *user)
 		user->vars = NULL;
 	}
 	ast_string_field_free_pools(user);
-	free(user);
+	ast_free(user);
 }
 
 static void prune_users(void)
@@ -9241,7 +9242,7 @@ static void destroy_peer(struct iax2_peer *peer)
 
 	ast_string_field_free_pools(peer);
 
-	free(peer);
+	ast_free(peer);
 }
 
 static void prune_peers(void){
@@ -9794,7 +9795,7 @@ static struct iax2_dpcache *find_cache(struct ast_channel *chan, const char *dat
 			if ((dp->flags & CACHE_FLAG_PENDING) || dp->callno)
 				ast_log(LOG_WARNING, "DP still has peer field or pending or callno (flags = %d, peer = blah, callno = %d)\n", dp->flags, dp->callno);
 			else
-				free(dp);
+				ast_free(dp);
 			continue;
 		}
 		if (!strcmp(dp->peercontext, data) && !strcmp(dp->exten, exten))
diff --git a/channels/chan_local.c b/channels/chan_local.c
index 8d588d79ab97554552f9f8c13058c94a73793e3b..1fd7f2faedec611a086615a0696c4405eee82fdb 100644
--- a/channels/chan_local.c
+++ b/channels/chan_local.c
@@ -178,7 +178,7 @@ retrylock:
 		return and destroy p.  */
 		ast_mutex_unlock(&p->lock);
 		ast_mutex_destroy(&p->lock);
-		free(p);
+		ast_free(p);
 		return -1;
 	}
 	if (!other) {
@@ -530,7 +530,7 @@ static int local_hangup(struct ast_channel *ast)
 		/* And destroy */
 		if (!glaredetect) {
 			ast_mutex_destroy(&p->lock);
-			free(p);
+			ast_free(p);
 		}
 		return 0;
 	}
@@ -577,7 +577,7 @@ static struct local_pvt *local_alloc(const char *data, int format)
 	if (!ast_exists_extension(NULL, tmp->context, tmp->exten, 1, NULL)) {
 		ast_log(LOG_NOTICE, "No such extension/context %s@%s creating local channel\n", tmp->exten, tmp->context);
 		ast_mutex_destroy(&tmp->lock);
-		free(tmp);
+		ast_free(tmp);
 		tmp = NULL;
 	} else {
 		/* Add to list */
diff --git a/channels/chan_mgcp.c b/channels/chan_mgcp.c
index 2efc0af5b086e5113eb1886f7255bde0b9a8bb99..20b7447de1b7c2a2f718748abb4af632e44689b3 100644
--- a/channels/chan_mgcp.c
+++ b/channels/chan_mgcp.c
@@ -697,15 +697,18 @@ static int retrans_pkt(void *data)
 static int mgcp_postrequest(struct mgcp_endpoint *p, struct mgcp_subchannel *sub, 
                             char *data, int len, unsigned int seqno)
 {
-	struct mgcp_message *msg = ast_malloc(sizeof(*msg) + len);
+	struct mgcp_message *msg;
 	struct mgcp_message *cur;
-	struct mgcp_gateway *gw = ((p && p->parent) ? p->parent : NULL);
+	struct mgcp_gateway *gw;
  	struct timeval tv;
 
+	msg = ast_malloc(sizeof(*msg) + len);
 	if (!msg) {
 		return -1;
 	}
+	gw = ((p && p->parent) ? p->parent : NULL);
 	if (!gw) {
+		ast_free(msg);
 		return -1;
 	}
 /* SC
diff --git a/channels/chan_misdn.c b/channels/chan_misdn.c
index c1ef37c1c19e5c20bfda477c35a0c151423e06e6..42966ec107fa559adcee41e37ba1ed0faa465b12 100644
--- a/channels/chan_misdn.c
+++ b/channels/chan_misdn.c
@@ -79,9 +79,9 @@ ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
 #include "chan_misdn_config.h"
 #include "isdn_lib.h"
 
-char global_tracefile[BUFFERSIZE+1];
+char global_tracefile[BUFFERSIZE + 1];
 
-static int g_config_initialized=0;
+static int g_config_initialized = 0;
 
 struct misdn_jb{
 	int size;
@@ -149,7 +149,7 @@ struct hold_info {
 
 struct chan_list {
   
-	char allowed_bearers[BUFFERSIZE+1];
+	char allowed_bearers[BUFFERSIZE + 1];
 	
 	enum misdn_chan_state state;
 	int need_queue_hangup;
@@ -244,11 +244,13 @@ static struct ast_frame *process_ast_dsp(struct chan_list *tmp, struct ast_frame
 
 static inline void free_robin_list_r (struct robin_list *r)
 {
-        if (r) {
-                if (r->next) free_robin_list_r(r->next);
-                if (r->group) free(r->group);
-                free(r);
-        }
+	if (r) {
+		if (r->next)
+			free_robin_list_r(r->next);
+		if (r->group)
+			ast_free(r->group);
+		ast_free(r);
+	}
 }
 
 static void free_robin_list ( void )
@@ -259,12 +261,13 @@ static void free_robin_list ( void )
 
 static struct robin_list* get_robin_position (char *group) 
 {
+	struct robin_list *new;
 	struct robin_list *iter = robin;
 	for (; iter; iter = iter->next) {
 		if (!strcasecmp(iter->group, group))
 			return iter;
 	}
-	struct robin_list *new = (struct robin_list *)calloc(1, sizeof(struct robin_list));
+	new = ast_calloc(1, sizeof(*new));
 	new->group = strndup(group, strlen(group));
 	new->channel = 1;
 	if (robin) {
@@ -730,64 +733,70 @@ static void send_digit_to_chan(struct chan_list *cl, char digit )
 /*** CLI HANDLING ***/
 static int misdn_set_debug(int fd, int argc, char *argv[])
 {
+	int level;
+
 	if (argc != 4 && argc != 5 && argc != 6 && argc != 7)
 		return RESULT_SHOWUSAGE; 
 
-	int level = atoi(argv[3]);
+	level = atoi(argv[3]);
 
 	switch (argc) {
-		case 4:	
-		case 5: {
-					int only = 0;
-					if (argc == 5) {
-						if (strncasecmp(argv[4], "only", strlen(argv[4])))
-							return RESULT_SHOWUSAGE;
-						else
-							only = 1;
-					}
-					int i;
-					for (i=0; i<=max_ports; i++) {
-						misdn_debug[i] = level;
-						misdn_debug_only[i] = only;
-					}
-					ast_cli(fd, "changing debug level for all ports to %d%s\n",misdn_debug[0], only?" (only)":"");
-				}
-				break;
-		case 6: 
-		case 7: {
-					if (strncasecmp(argv[4], "port", strlen(argv[4])))
-						return RESULT_SHOWUSAGE;
-					int port = atoi(argv[5]);
-					if (port <= 0 || port > max_ports) {
-						switch (max_ports) {
-							case 0:
-								ast_cli(fd, "port number not valid! no ports available so you won't get lucky with any number here...\n");
-								break;
-							case 1:
-								ast_cli(fd, "port number not valid! only port 1 is availble.\n");
-								break;
-							default:
-								ast_cli(fd, "port number not valid! only ports 1 to %d are available.\n", max_ports);
-							}
-							return 0;
-					}
-					if (argc == 7) {
-						if (strncasecmp(argv[6], "only", strlen(argv[6])))
-							return RESULT_SHOWUSAGE;
-						else
-							misdn_debug_only[port] = 1;
-					} else
-						misdn_debug_only[port] = 0;
-					misdn_debug[port] = level;
-					ast_cli(fd, "changing debug level to %d%s for port %d\n", misdn_debug[port], misdn_debug_only[port]?" (only)":"", port);
+	case 4:	
+	case 5:
+		{
+			int only = 0, i;
+			if (argc == 5) {
+				if (strncasecmp(argv[4], "only", strlen(argv[4])))
+					return RESULT_SHOWUSAGE;
+				else
+					only = 1;
+			}
+	
+			for (i = 0; i <= max_ports; i++) {
+				misdn_debug[i] = level;
+				misdn_debug_only[i] = only;
+			}
+			ast_cli(fd, "changing debug level for all ports to %d%s\n",misdn_debug[0], only?" (only)":"");
+		}
+		break;
+	case 6: 
+	case 7:
+		{
+			int port;
+			if (strncasecmp(argv[4], "port", strlen(argv[4])))
+				return RESULT_SHOWUSAGE;
+			port = atoi(argv[5]);
+			if (port <= 0 || port > max_ports) {
+				switch (max_ports) {
+				case 0:
+					ast_cli(fd, "port number not valid! no ports available so you won't get lucky with any number here...\n");
+					break;
+				case 1:
+					ast_cli(fd, "port number not valid! only port 1 is availble.\n");
+					break;
+				default:
+					ast_cli(fd, "port number not valid! only ports 1 to %d are available.\n", max_ports);
 				}
+				return 0;
+			}
+			if (argc == 7) {
+				if (strncasecmp(argv[6], "only", strlen(argv[6])))
+					return RESULT_SHOWUSAGE;
+				else
+					misdn_debug_only[port] = 1;
+			} else
+				misdn_debug_only[port] = 0;
+			misdn_debug[port] = level;
+			ast_cli(fd, "changing debug level to %d%s for port %d\n", misdn_debug[port], misdn_debug_only[port]?" (only)":"", port);
+		}
 	}
 	return 0;
 }
 
 static int misdn_set_crypt_debug(int fd, int argc, char *argv[])
 {
-	if (argc != 5) return RESULT_SHOWUSAGE; 
+	if (argc != 5)
+		return RESULT_SHOWUSAGE; 
 
 	return 0;
 }
@@ -912,7 +921,7 @@ static int misdn_show_config (int fd, int argc, char *argv[])
 	if (argc >= 4) {
 		if (!strcmp(argv[3], "description")) {
 			if (argc == 5) {
-				enum misdn_cfg_elements elem = misdn_cfg_get_elem (argv[4]);
+				enum misdn_cfg_elements elem = misdn_cfg_get_elem(argv[4]);
 				if (elem == MISDN_CFG_FIRST)
 					ast_cli(fd, "Unknown element: %s\n", argv[4]);
 				else
@@ -947,7 +956,7 @@ static int misdn_show_config (int fd, int argc, char *argv[])
 	if (argc == 3 || onlyport == 0) {
 		ast_cli(fd,"Misdn General-Config: \n"); 
 		for (elem = MISDN_GEN_FIRST + 1, linebreak = 1; elem < MISDN_GEN_LAST; elem++, linebreak++) {
-			misdn_cfg_get_config_string( 0, elem, buffer, BUFFERSIZE);
+			misdn_cfg_get_config_string(0, elem, buffer, sizeof(buffer));
 			ast_cli(fd, "%-36s%s", buffer, !(linebreak % 2) ? "\n" : "");
 		}
 		ast_cli(fd, "\n");
@@ -958,7 +967,7 @@ static int misdn_show_config (int fd, int argc, char *argv[])
 		for (; port > 0; port = misdn_cfg_get_next_port(port)) {
 			ast_cli(fd, "\n[PORT %d]\n", port);
 			for (elem = MISDN_CFG_FIRST + 1, linebreak = 1; elem < MISDN_CFG_LAST; elem++, linebreak++) {
-				misdn_cfg_get_config_string( port, elem, buffer, BUFFERSIZE);
+				misdn_cfg_get_config_string(port, elem, buffer, sizeof(buffer));
 				ast_cli(fd, "%-36s%s", buffer, !(linebreak % 2) ? "\n" : "");
 			}	
 			ast_cli(fd, "\n");
@@ -969,7 +978,7 @@ static int misdn_show_config (int fd, int argc, char *argv[])
 		if (misdn_cfg_is_port_valid(onlyport)) {
 			ast_cli(fd, "[PORT %d]\n", onlyport);
 			for (elem = MISDN_CFG_FIRST + 1, linebreak = 1; elem < MISDN_CFG_LAST; elem++, linebreak++) {
-				misdn_cfg_get_config_string(onlyport, elem, buffer, BUFFERSIZE);
+				misdn_cfg_get_config_string(onlyport, elem, buffer, sizeof(buffer));
 				ast_cli(fd, "%-36s%s", buffer, !(linebreak % 2) ? "\n" : "");
 			}	
 			ast_cli(fd, "\n");
@@ -982,8 +991,8 @@ static int misdn_show_config (int fd, int argc, char *argv[])
 
 struct state_struct {
 	enum misdn_chan_state state;
-	char txt[255] ;
-} ;
+	char txt[255];
+};
 
 static struct state_struct state_array[] = {
 	{MISDN_NOTHING,"NOTHING"}, /* at beginning */
@@ -1010,18 +1019,19 @@ static struct state_struct state_array[] = {
 	/* misdn_hangup */
 };
 
-static char *misdn_get_ch_state(struct chan_list *p) 
+static const char *misdn_get_ch_state(struct chan_list *p) 
 {
 	int i;
 	static char state[8];
 	
 	if( !p) return NULL;
   
-	for (i=0; i< sizeof(state_array)/sizeof(struct state_struct); i++) {
-		if ( state_array[i].state == p->state) return state_array[i].txt; 
+	for (i = 0; i < sizeof(state_array) / sizeof(struct state_struct); i++) {
+		if (state_array[i].state == p->state)
+			return state_array[i].txt; 
 	}
 
- 	sprintf(state,"%d",p->state) ;
+ 	snprintf(state, sizeof(state), "%d", p->state) ;
 
 	return state;
 }
@@ -1040,8 +1050,8 @@ static void reload_config(void)
 	free_robin_list();
 	misdn_cfg_reload();
 	misdn_cfg_update_ptp();
-	misdn_cfg_get( 0, MISDN_GEN_TRACEFILE, global_tracefile, BUFFERSIZE);
-	misdn_cfg_get( 0, MISDN_GEN_DEBUG, &cfg_debug, sizeof(int));
+	misdn_cfg_get(0, MISDN_GEN_TRACEFILE, global_tracefile, sizeof(global_tracefile));
+	misdn_cfg_get(0, MISDN_GEN_DEBUG, &cfg_debug, sizeof(cfg_debug));
 
 	for (i = 0;  i <= max_ports; i++) {
 		misdn_debug[i] = cfg_debug;
@@ -1056,19 +1066,19 @@ static int misdn_reload (int fd, int argc, char *argv[])
 	return 0;
 }
 
-static void print_bc_info (int fd, struct chan_list* help, struct misdn_bchannel* bc)
+static void print_bc_info (int fd, struct chan_list *help, struct misdn_bchannel *bc)
 {
-	struct ast_channel *ast=help->ast;
+	struct ast_channel *ast = help->ast;
 	ast_cli(fd,
 		"* Pid:%d Prt:%d Ch:%d Mode:%s Org:%s dad:%s oad:%s rad:%s ctx:%s state:%s\n",
 
 		bc->pid, bc->port, bc->channel,
-		bc->nt?"NT":"TE",
-		help->originator == ORG_AST?"*":"I",
-		ast?ast->exten:NULL,
-		ast?ast->cid.cid_num:NULL,
+		bc->nt ? "NT" : "TE",
+		help->originator == ORG_AST ? "*" : "I",
+		ast ? ast->exten : NULL,
+		ast ? ast->cid.cid_num : NULL,
 		bc->rad,
-		ast?ast->context:NULL,
+		ast ? ast->context : NULL,
 		misdn_get_ch_state(help)
 		);
 	if (misdn_debug[bc->port] > 0)
@@ -1093,7 +1103,7 @@ static void print_bc_info (int fd, struct chan_list* help, struct misdn_bchannel
 			help->l3id,
 			help->addr,
 			bc->addr,
-			bc?bc->l3_id:-1,
+			bc ? bc->l3_id : -1,
 			bc->display,
 			
 			bc->active,
@@ -1105,22 +1115,23 @@ static void print_bc_info (int fd, struct chan_list* help, struct misdn_bchannel
  			bc->ec_enable,
 #endif
 
-			help->norxtone,help->notxtone,
+			help->norxtone, help->notxtone,
 			bc->holded
 			);
-  
+
 }
 
-static int misdn_show_cls (int fd, int argc, char *argv[])
+static int misdn_show_cls(int fd, int argc, char *argv[])
 {
-	struct chan_list *help=cl_te;
+	struct chan_list *help = cl_te;
   
-	ast_cli(fd,"Chan List: %p\n",cl_te); 
+	ast_cli(fd, "Chan List: %p\n", cl_te); 
   
-	for (;help; help=help->next) {
-		struct misdn_bchannel *bc=help->bc;   
-		struct ast_channel *ast=help->ast;
-		if (misdn_debug[0] > 2) ast_cli(fd, "Bc:%p Ast:%p\n", bc, ast);
+	for (; help; help = help->next) {
+		struct misdn_bchannel *bc = help->bc;   
+		struct ast_channel *ast = help->ast;
+		if (misdn_debug[0] > 2)
+			ast_cli(fd, "Bc:%p Ast:%p\n", bc, ast);
 		if (bc) {
 			print_bc_info(fd, help, bc);
 		} else {
@@ -1129,21 +1140,21 @@ static int misdn_show_cls (int fd, int argc, char *argv[])
 				ast_cli(fd, " --> l3_id: %x\n"
 						" --> dad:%s oad:%s\n"
 						" --> hold_port: %d\n"
-						" --> hold_channel: %d\n"
+						" --> hold_channel: %d\n",
 				
-						,help->l3id
-						,ast->exten
-						,ast->cid.cid_num
-						,help->hold_info.port
-						,help->hold_info.channel
+						help->l3id,
+						ast->exten,
+						ast->cid.cid_num,
+						help->hold_info.port,
+						help->hold_info.channel
 						);
 			} else {
-				ast_cli(fd,"* Channel in unknown STATE !!! Exten:%s, Callerid:%s\n", ast->exten, ast->cid.cid_num);
+				ast_cli(fd, "* Channel in unknown STATE !!! Exten:%s, Callerid:%s\n", ast->exten, ast->cid.cid_num);
 			}
 		}
 	}
-  
-  
+
+
 	return 0;
 }
 
@@ -1154,12 +1165,12 @@ static int misdn_show_cl (int fd, int argc, char *argv[])
 	if (argc != 4)
 		return RESULT_SHOWUSAGE;
   
-	for (;help; help=help->next) {
-		struct misdn_bchannel *bc=help->bc;   
-		struct ast_channel *ast=help->ast;
+	for (; help; help = help->next) {
+		struct misdn_bchannel *bc = help->bc;   
+		struct ast_channel *ast = help->ast;
     
 		if (bc && ast) {
-			if (!strcasecmp(ast->name,argv[3])) {
+			if (!strcasecmp(ast->name, argv[3])) {
 				print_bc_info(fd, help, bc);
 				break; 
 			}
@@ -1171,55 +1182,55 @@ static int misdn_show_cl (int fd, int argc, char *argv[])
 }
 
 ast_mutex_t lock;
-int MAXTICS=8;
+int MAXTICS = 8;
 
 static int misdn_set_tics (int fd, int argc, char *argv[])
 {
 	if (argc != 4)
 		return RESULT_SHOWUSAGE;
   
-	MAXTICS=atoi(argv[3]);
+	MAXTICS = atoi(argv[3]);
   
 	return 0;
 }
 
-static int misdn_show_stacks (int fd, int argc, char *argv[])
+static int misdn_show_stacks(int fd, int argc, char *argv[])
 {
 	int port;
 
 	ast_cli(fd, "BEGIN STACK_LIST:\n");
 
-	for (port=misdn_cfg_get_next_port(0); port > 0;
-	     port=misdn_cfg_get_next_port(port)) {
+	for (port = misdn_cfg_get_next_port(0); port > 0;
+	     port = misdn_cfg_get_next_port(port)) {
 		char buf[128];
-		get_show_stack_details(port,buf);
-		ast_cli(fd,"  %s  Debug:%d%s\n", buf, misdn_debug[port], misdn_debug_only[port]?"(only)":"");
+		get_show_stack_details(port, buf);
+		ast_cli(fd,"  %s  Debug:%d%s\n", buf, misdn_debug[port], misdn_debug_only[port] ? "(only)" : "");
 	}
-		
+
 	return 0;
 }
 
 
-static int misdn_show_ports_stats (int fd, int argc, char *argv[])
+static int misdn_show_ports_stats(int fd, int argc, char *argv[])
 {
 	int port;
 
 	ast_cli(fd, "Port\tin_calls\tout_calls\n");
 	
-	for (port=misdn_cfg_get_next_port(0); port > 0;
-	     port=misdn_cfg_get_next_port(port)) {
-		ast_cli(fd,"%d\t%d\t\t%d\n",port,misdn_in_calls[port],misdn_out_calls[port]);
+	for (port = misdn_cfg_get_next_port(0); port > 0;
+	     port = misdn_cfg_get_next_port(port)) {
+		ast_cli(fd, "%d\t%d\t\t%d\n", port, misdn_in_calls[port], misdn_out_calls[port]);
 	}
-	ast_cli(fd,"\n");
-	
-	return 0;
+	ast_cli(fd, "\n");
 
+	return 0;
 }
 
 
-static int misdn_show_port (int fd, int argc, char *argv[])
+static int misdn_show_port(int fd, int argc, char *argv[])
 {
 	int port;
+	char buf[128];
 	
 	if (argc != 4)
 		return RESULT_SHOWUSAGE;
@@ -1228,18 +1239,18 @@ static int misdn_show_port (int fd, int argc, char *argv[])
   
 	ast_cli(fd, "BEGIN STACK_LIST:\n");
 
-	char buf[128];
-	get_show_stack_details(port,buf);
-	ast_cli(fd,"  %s  Debug:%d%s\n",buf, misdn_debug[port], misdn_debug_only[port]?"(only)":"");
+	get_show_stack_details(port, buf);
+	ast_cli(fd, "  %s  Debug:%d%s\n", buf, misdn_debug[port], misdn_debug_only[port] ? "(only)" : "");
 
 	
 	return 0;
 }
 
-static int misdn_send_cd (int fd, int argc, char *argv[])
+static int misdn_send_cd(int fd, int argc, char *argv[])
 {
 	char *channame; 
-	char *nr; 
+	char *nr;
+	struct chan_list *tmp;
   
 	if (argc != 5)
 		return RESULT_SHOWUSAGE;
@@ -1247,71 +1258,66 @@ static int misdn_send_cd (int fd, int argc, char *argv[])
 	channame = argv[3];
 	nr = argv[4];
 
-	ast_cli(fd, "Sending Calldeflection (%s) to %s\n",nr, channame);
+	ast_cli(fd, "Sending Calldeflection (%s) to %s\n", nr, channame);
 	
-	{
-		struct chan_list *tmp=get_chan_by_ast_name(channame);
-		
-		if (!tmp) {
-			ast_cli(fd, "Sending CD with nr %s to %s failed: Channel does not exist.\n",nr, channame);
-			return 0; 
-		} else {
-			if (strlen(nr) >= 15) {
-				ast_cli(fd, "Sending CD with nr %s to %s failed: Number too long (up to 15 digits are allowed).\n",nr, channame);
-				return 0; 
-			}
-			tmp->bc->fac_out.Function = Fac_CD;
-			strncpy((char *)tmp->bc->fac_out.u.CDeflection.DeflectedToNumber, nr, sizeof(tmp->bc->fac_out.u.CDeflection.DeflectedToNumber));
-			misdn_lib_send_event(tmp->bc, EVENT_FACILITY);
-		}
+	tmp = get_chan_by_ast_name(channame);
+	if (!tmp) {
+		ast_cli(fd, "Sending CD with nr %s to %s failed: Channel does not exist.\n",nr, channame);
+		return 0; 
 	}
-  
+
+	if (strlen(nr) >= 15) {
+		ast_cli(fd, "Sending CD with nr %s to %s failed: Number too long (up to 15 digits are allowed).\n",nr, channame);
+		return 0; 
+	}
+	tmp->bc->fac_out.Function = Fac_CD;
+	ast_copy_string((char *)tmp->bc->fac_out.u.CDeflection.DeflectedToNumber, nr, sizeof(tmp->bc->fac_out.u.CDeflection.DeflectedToNumber));
+	misdn_lib_send_event(tmp->bc, EVENT_FACILITY);
+
 	return 0; 
 }
 
-static int misdn_send_digit (int fd, int argc, char *argv[])
+static int misdn_send_digit(int fd, int argc, char *argv[])
 {
 	char *channame; 
 	char *msg; 
-  
+	struct chan_list *tmp;
+	int i, msglen;
+
 	if (argc != 5)
 		return RESULT_SHOWUSAGE;
-  
+
 	channame = argv[3];
 	msg = argv[4];
+	msglen = strlen(msg);
 
-	ast_cli(fd, "Sending %s to %s\n",msg, channame);
-  
-	{
-		struct chan_list *tmp=get_chan_by_ast_name(channame);
-    
-		if (!tmp) {
-			ast_cli(fd, "Sending %s to %s failed Channel does not exist\n",msg, channame);
-			return 0; 
-		} else {
+	ast_cli(fd, "Sending %s to %s\n", msg, channame);
+
+	tmp = get_chan_by_ast_name(channame);
+
+	if (!tmp) {
+		ast_cli(fd, "Sending %s to %s failed Channel does not exist\n", msg, channame);
+		return 0; 
+	}
 #if 1
-			int i;
-			int msglen = strlen(msg);
-			for (i=0; i<msglen; i++) {
-				ast_cli(fd, "Sending: %c\n",msg[i]);
-				send_digit_to_chan(tmp, msg[i]);
-				/* res = ast_safe_sleep(tmp->ast, 250); */
-				usleep(250000);
-				/* res = ast_waitfor(tmp->ast,100); */
-			}
+	for (i = 0; i < msglen; i++) {
+		ast_cli(fd, "Sending: %c\n", msg[i]);
+		send_digit_to_chan(tmp, msg[i]);
+		/* res = ast_safe_sleep(tmp->ast, 250); */
+		usleep(250000);
+		/* res = ast_waitfor(tmp->ast,100); */
+	}
 #else
-			int res;
-			res = ast_dtmf_stream(tmp->ast,NULL,msg,250);
+	ast_dtmf_stream(tmp->ast, NULL, msg, 250);
 #endif
-		}
-	}
-  
+
 	return 0; 
 }
 
-static int misdn_toggle_echocancel (int fd, int argc, char *argv[])
+static int misdn_toggle_echocancel(int fd, int argc, char *argv[])
 {
-	char *channame; 
+	char *channame;
+	struct chan_list *tmp;
 
 	if (argc != 4)
 		return RESULT_SHOWUSAGE;
@@ -1320,55 +1326,50 @@ static int misdn_toggle_echocancel (int fd, int argc, char *argv[])
   
 	ast_cli(fd, "Toggling EchoCancel on %s\n", channame);
   
-	{
-		struct chan_list *tmp=get_chan_by_ast_name(channame);
+	tmp = get_chan_by_ast_name(channame);
     
-		if (!tmp) {
-			ast_cli(fd, "Toggling EchoCancel %s failed Channel does not exist\n", channame);
-			return 0; 
-		} else {
-			
-			tmp->toggle_ec=tmp->toggle_ec?0:1;
+	if (!tmp) {
+		ast_cli(fd, "Toggling EchoCancel %s failed Channel does not exist\n", channame);
+		return 0; 
+	}
+
+	tmp->toggle_ec = tmp->toggle_ec?0:1;
 
-			if (tmp->toggle_ec) {
+	if (tmp->toggle_ec) {
 #ifdef MISDN_1_2
-				update_pipeline_config(tmp->bc);
+		update_pipeline_config(tmp->bc);
 #else
-				update_ec_config(tmp->bc);
+		update_ec_config(tmp->bc);
 #endif
-				manager_ec_enable(tmp->bc);
-			} else {
-				manager_ec_disable(tmp->bc);
-			}
-		}
+		manager_ec_enable(tmp->bc);
+	} else {
+		manager_ec_disable(tmp->bc);
 	}
-  
+
 	return 0; 
 }
 
-static int misdn_send_display (int fd, int argc, char *argv[])
+static int misdn_send_display(int fd, int argc, char *argv[])
 {
 	char *channame; 
 	char *msg; 
-  
+	struct chan_list *tmp;
+
 	if (argc != 5)
 		return RESULT_SHOWUSAGE;
-  
+
 	channame = argv[3];
 	msg = argv[4];
 
-	ast_cli(fd, "Sending %s to %s\n",msg, channame);
-	{
-		struct chan_list *tmp;
-		tmp=get_chan_by_ast_name(channame);
+	ast_cli(fd, "Sending %s to %s\n", msg, channame);
+	tmp = get_chan_by_ast_name(channame);
     
-		if (tmp && tmp->bc) {
-			ast_copy_string(tmp->bc->display, msg, sizeof(tmp->bc->display));
-			misdn_lib_send_event(tmp->bc, EVENT_INFORMATION);
-		} else {
-			ast_cli(fd,"No such channel %s\n",channame);
-			return RESULT_FAILURE;
-		}
+	if (tmp && tmp->bc) {
+		ast_copy_string(tmp->bc->display, msg, sizeof(tmp->bc->display));
+		misdn_lib_send_event(tmp->bc, EVENT_INFORMATION);
+	} else {
+		ast_cli(fd, "No such channel %s\n", channame);
+		return RESULT_FAILURE;
 	}
 
 	return RESULT_SUCCESS ;
@@ -1377,18 +1378,16 @@ static int misdn_send_display (int fd, int argc, char *argv[])
 static char *complete_ch_helper(const char *line, const char *word, int pos, int state, int rpos)
 {
 	struct ast_channel *c;
-	int which=0;
+	int which = 0;
 	char *ret;
 	if (pos != rpos)
 		return NULL;
-	c = ast_channel_walk_locked(NULL);
-	while(c) {
+	for (c = ast_channel_walk_locked(NULL); c; c = ast_channel_walk_locked(c)) {
 		if (!strncasecmp(word, c->name, strlen(word))) {
 			if (++which > state)
 				break;
 		}
 		ast_mutex_unlock(&c->lock);
-		c = ast_channel_walk_locked(c);
 	}
 	if (c) {
 		ret = strdup(c->name);
@@ -1409,14 +1408,16 @@ static char *complete_debug_port (const char *line, const char *word, int pos, i
 		return NULL;
 
 	switch (pos) {
-	case 4: if (*word == 'p')
-				return strdup("port");
-			else if (*word == 'o')
-				return strdup("only");
-			break;
-	case 6: if (*word == 'o')
-				return strdup("only");
-			break;
+	case 4:
+		if (*word == 'p')
+			return strdup("port");
+		else if (*word == 'o')
+			return strdup("only");
+		break;
+	case 6:
+		if (*word == 'o')
+			return strdup("only");
+		break;
 	}
 	return NULL;
 }
@@ -1430,37 +1431,38 @@ static char *complete_show_config (const char *line, const char *word, int pos,
 	int port = 0;
 
 	switch (pos) {
-	case 3: if ((!strncmp(word, "description", wordlen)) && (++which > state))
-				return strdup("description");
-			if ((!strncmp(word, "descriptions", wordlen)) && (++which > state))
-				return strdup("descriptions");
-			if ((!strncmp(word, "0", wordlen)) && (++which > state))
-				return strdup("0");
-			while ((port = misdn_cfg_get_next_port(port)) != -1) {
-				snprintf(buffer, sizeof(buffer), "%d", port);
-				if ((!strncmp(word, buffer, wordlen)) && (++which > state)) {
-					return strdup(buffer);
-				}
+	case 3:
+		if ((!strncmp(word, "description", wordlen)) && (++which > state))
+			return strdup("description");
+		if ((!strncmp(word, "descriptions", wordlen)) && (++which > state))
+			return strdup("descriptions");
+		if ((!strncmp(word, "0", wordlen)) && (++which > state))
+			return strdup("0");
+		while ((port = misdn_cfg_get_next_port(port)) != -1) {
+			snprintf(buffer, sizeof(buffer), "%d", port);
+			if ((!strncmp(word, buffer, wordlen)) && (++which > state)) {
+				return strdup(buffer);
 			}
-			break;
+		}
+		break;
 	case 4:
-			if (strstr(line, "description ")) {
-				for (elem = MISDN_CFG_FIRST + 1; elem < MISDN_GEN_LAST; ++elem) {
-					if ((elem == MISDN_CFG_LAST) || (elem == MISDN_GEN_FIRST))
-						continue;
-					misdn_cfg_get_name(elem, buffer, BUFFERSIZE);
-					if (!wordlen || !strncmp(word, buffer, wordlen)) {
-						if (++which > state)
-							return strdup(buffer);
-					}
+		if (strstr(line, "description ")) {
+			for (elem = MISDN_CFG_FIRST + 1; elem < MISDN_GEN_LAST; ++elem) {
+				if ((elem == MISDN_CFG_LAST) || (elem == MISDN_GEN_FIRST))
+					continue;
+				misdn_cfg_get_name(elem, buffer, sizeof(buffer));
+				if (!wordlen || !strncmp(word, buffer, wordlen)) {
+					if (++which > state)
+						return strdup(buffer);
 				}
-			} else if (strstr(line, "descriptions ")) {
-				if ((!wordlen || !strncmp(word, "general", wordlen)) && (++which > state))
-					return strdup("general");
-				if ((!wordlen || !strncmp(word, "ports", wordlen)) && (++which > state))
-					return strdup("ports");
 			}
-			break;
+		} else if (strstr(line, "descriptions ")) {
+			if ((!wordlen || !strncmp(word, "general", wordlen)) && (++which > state))
+				return strdup("general");
+			if ((!wordlen || !strncmp(word, "ports", wordlen)) && (++which > state))
+				return strdup("ports");
+		}
+		break;
 	}
 	return NULL;
 }
@@ -1513,137 +1515,126 @@ static struct ast_cli_entry chan_misdn_clis[] = {
 		"Usage: misdn set crypt debug <level>\n" }
 };
 
-static int update_config (struct chan_list *ch, int orig) 
+static int update_config(struct chan_list *ch, int orig) 
 {
+	struct ast_channel *ast;
+	struct misdn_bchannel *bc;
+	int port, hdlc = 0;
+	int pres, screen;
+
 	if (!ch) {
 		ast_log(LOG_WARNING, "Cannot configure without chanlist\n");
 		return -1;
 	}
-	
-	struct ast_channel *ast=ch->ast;
-	struct misdn_bchannel *bc=ch->bc;
-	if (! ast || ! bc ) {
+
+	ast = ch->ast;
+	bc = ch->bc;
+	if (! ast || ! bc) {
 		ast_log(LOG_WARNING, "Cannot configure without ast || bc\n");
 		return -1;
 	}
-	
-	int port=bc->port;
-	
-	chan_misdn_log(7,port,"update_config: Getting Config\n");
 
-	int hdlc=0;
-	misdn_cfg_get( port, MISDN_CFG_HDLC, &hdlc, sizeof(int));
+	port = bc->port;
+
+	chan_misdn_log(7, port, "update_config: Getting Config\n");
+
+	misdn_cfg_get(port, MISDN_CFG_HDLC, &hdlc, sizeof(int));
 	
 	if (hdlc) {
 		switch (bc->capability) {
 		case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
 		case INFO_CAPABILITY_DIGITAL_RESTRICTED:
-			chan_misdn_log(1,bc->port," --> CONF HDLC\n");
-			bc->hdlc=1;
+			chan_misdn_log(1, bc->port, " --> CONF HDLC\n");
+			bc->hdlc = 1;
 			break;
 		}
-		
 	}
-	
-	
-	int pres, screen;
-			
-	misdn_cfg_get( port, MISDN_CFG_PRES, &pres, sizeof(int));
-	misdn_cfg_get( port, MISDN_CFG_SCREEN, &screen, sizeof(int));
-	chan_misdn_log(2,port," --> pres: %d screen: %d\n",pres, screen);
+
+
+	misdn_cfg_get(port, MISDN_CFG_PRES, &pres, sizeof(pres));
+	misdn_cfg_get(port, MISDN_CFG_SCREEN, &screen, sizeof(screen));
+	chan_misdn_log(2, port, " --> pres: %d screen: %d\n", pres, screen);
 		
 	if ( (pres + screen) < 0 ) {
 
-		chan_misdn_log(2,port," --> pres: %x\n", ast->cid.cid_pres);
+		chan_misdn_log(2, port, " --> pres: %x\n", ast->cid.cid_pres);
 			
-		switch (ast->cid.cid_pres & 0x60){
+		switch (ast->cid.cid_pres & 0x60) {
 				
 		case AST_PRES_RESTRICTED:
-			bc->pres=1;
+			bc->pres = 1;
 			chan_misdn_log(2, port, " --> PRES: Restricted (0x1)\n");
 			break;
-				
-				
 		case AST_PRES_UNAVAILABLE:
-			bc->pres=2;
+			bc->pres = 2;
 			chan_misdn_log(2, port, " --> PRES: Unavailable (0x2)\n");
 			break;
-				
 		default:
-			bc->pres=0;
+			bc->pres = 0;
 			chan_misdn_log(2, port, " --> PRES: Allowed (0x0)\n");
 		}
 			
-		switch (ast->cid.cid_pres & 0x3){
-				
+		switch (ast->cid.cid_pres & 0x3) {
+
 		case AST_PRES_USER_NUMBER_UNSCREENED:
-			bc->screen=0;
+			bc->screen = 0;
 			chan_misdn_log(2, port, " --> SCREEN: Unscreened (0x0)\n");
 			break;
-
 		case AST_PRES_USER_NUMBER_PASSED_SCREEN:
-			bc->screen=1;
+			bc->screen = 1;
 			chan_misdn_log(2, port, " --> SCREEN: Passed Screen (0x1)\n");
 			break;
 		case AST_PRES_USER_NUMBER_FAILED_SCREEN:
-			bc->screen=2;
+			bc->screen = 2;
 			chan_misdn_log(2, port, " --> SCREEN: Failed Screen (0x2)\n");
 			break;
-				
 		case AST_PRES_NETWORK_NUMBER:
-			bc->screen=3;
+			bc->screen = 3;
 			chan_misdn_log(2, port, " --> SCREEN: Network Nr. (0x3)\n");
 			break;
-				
 		default:
-			bc->screen=0;
+			bc->screen = 0;
 			chan_misdn_log(2, port, " --> SCREEN: Unscreened (0x0)\n");
 		}
-
-			
 	} else {
-		bc->screen=screen;
-		bc->pres=pres;
+		bc->screen = screen;
+		bc->pres = pres;
 	}
 
 	return 0;
-	
 }
 
 
-
-
 static void config_jitterbuffer(struct chan_list *ch)
 {
-	struct misdn_bchannel *bc=ch->bc;
-	int len=ch->jb_len, threshold=ch->jb_upper_threshold;
+	struct misdn_bchannel *bc = ch->bc;
+	int len = ch->jb_len, threshold = ch->jb_upper_threshold;
 	
-	chan_misdn_log(5,bc->port, "config_jb: Called\n");
+	chan_misdn_log(5, bc->port, "config_jb: Called\n");
 	
-	if ( ! len ) {
-		chan_misdn_log(1,bc->port, "config_jb: Deactivating Jitterbuffer\n");
+	if (! len) {
+		chan_misdn_log(1, bc->port, "config_jb: Deactivating Jitterbuffer\n");
 		bc->nojitter=1;
 	} else {
-		
-		if (len <=100 || len > 8000) {
-			chan_misdn_log(0,bc->port,"config_jb: Jitterbuffer out of Bounds, setting to 1000\n");
-			len=1000;
+		if (len <= 100 || len > 8000) {
+			chan_misdn_log(0, bc->port, "config_jb: Jitterbuffer out of Bounds, setting to 1000\n");
+			len = 1000;
 		}
-		
+
 		if ( threshold > len ) {
-			chan_misdn_log(0,bc->port,"config_jb: Jitterbuffer Threshold > Jitterbuffer setting to Jitterbuffer -1\n");
+			chan_misdn_log(0, bc->port, "config_jb: Jitterbuffer Threshold > Jitterbuffer setting to Jitterbuffer -1\n");
 		}
-		
+
 		if ( ch->jb) {
-			cb_log(0,bc->port,"config_jb: We've got a Jitterbuffer Already on this port.\n");
+			cb_log(0, bc->port, "config_jb: We've got a Jitterbuffer Already on this port.\n");
 			misdn_jb_destroy(ch->jb);
-			ch->jb=NULL;
+			ch->jb = NULL;
 		}
-		
+
 		ch->jb=misdn_jb_init(len, threshold);
 
 		if (!ch->jb ) 
-			bc->nojitter=1;
+			bc->nojitter = 1;
 	}
 }
 
@@ -1652,16 +1643,16 @@ void debug_numplan(int port, int numplan, char *type)
 {
 	switch (numplan) {
 	case NUMPLAN_INTERNATIONAL:
-		chan_misdn_log(2, port, " --> %s: International\n",type);
+		chan_misdn_log(2, port, " --> %s: International\n", type);
 		break;
 	case NUMPLAN_NATIONAL:
-		chan_misdn_log(2, port, " --> %s: National\n",type);
+		chan_misdn_log(2, port, " --> %s: National\n", type);
 		break;
 	case NUMPLAN_SUBSCRIBER:
-		chan_misdn_log(2, port, " --> %s: Subscriber\n",type);
+		chan_misdn_log(2, port, " --> %s: Subscriber\n", type);
 		break;
 	case NUMPLAN_UNKNOWN:
-		chan_misdn_log(2, port, " --> %s: Unknown\n",type);
+		chan_misdn_log(2, port, " --> %s: Unknown\n", type);
 		break;
 		/* Maybe we should cut off the prefix if present ? */
 	default:
@@ -1671,8 +1662,6 @@ void debug_numplan(int port, int numplan, char *type)
 }
 
 
-
-
 #ifdef MISDN_1_2
 static int update_pipeline_config(struct misdn_bchannel *bc)
 {
@@ -1683,11 +1672,11 @@ static int update_pipeline_config(struct misdn_bchannel *bc)
 	if (*bc->pipeline)
 		return 0;
 
-	misdn_cfg_get(bc->port, MISDN_CFG_ECHOCANCEL, &ec, sizeof(int));
+	misdn_cfg_get(bc->port, MISDN_CFG_ECHOCANCEL, &ec, sizeof(ec));
 	if (ec == 1)
-		snprintf(bc->pipeline, sizeof(bc->pipeline) - 1, "mg2ec");
+		snprintf(bc->pipeline, sizeof(bc->pipeline), "mg2ec");
 	else if (ec > 1)
-		snprintf(bc->pipeline, sizeof(bc->pipeline) - 1, "mg2ec(deftaps=%d)", ec);
+		snprintf(bc->pipeline, sizeof(bc->pipeline), "mg2ec(deftaps=%d)", ec);
 
 	return 0;
 }
@@ -1695,15 +1684,15 @@ static int update_pipeline_config(struct misdn_bchannel *bc)
 static int update_ec_config(struct misdn_bchannel *bc)
 {
 	int ec;
-	int port=bc->port;
-		
-	misdn_cfg_get( port, MISDN_CFG_ECHOCANCEL, &ec, sizeof(int));
-	
-	if (ec == 1 ) {
-		bc->ec_enable=1;
-	} else if ( ec > 1 ) {
-		bc->ec_enable=1;
-		bc->ec_deftaps=ec;
+	int port = bc->port;
+
+	misdn_cfg_get(port, MISDN_CFG_ECHOCANCEL, &ec, sizeof(ec));
+
+	if (ec == 1) {
+		bc->ec_enable = 1;
+	} else if (ec > 1) {
+		bc->ec_enable = 1;
+		bc->ec_deftaps = ec;
 	}
 
 	return 0;
@@ -1711,79 +1700,76 @@ static int update_ec_config(struct misdn_bchannel *bc)
 #endif
 
 
-static int read_config(struct chan_list *ch, int orig) {
+static int read_config(struct chan_list *ch, int orig)
+{
+	struct ast_channel *ast;
+	struct misdn_bchannel *bc;
+	int port, hdlc = 0;
+	char lang[BUFFERSIZE + 1], localmusicclass[BUFFERSIZE + 1], faxdetect[BUFFERSIZE + 1];
+	char buf[256], buf2[256];
+	ast_group_t pg, cg;
 
 	if (!ch) {
 		ast_log(LOG_WARNING, "Cannot configure without chanlist\n");
 		return -1;
 	}
 
-	struct ast_channel *ast=ch->ast;
-	struct misdn_bchannel *bc=ch->bc;
-	if (! ast || ! bc ) {
+	ast = ch->ast;
+	bc = ch->bc;
+	if (! ast || ! bc) {
 		ast_log(LOG_WARNING, "Cannot configure without ast || bc\n");
 		return -1;
 	}
 	
-	int port=bc->port;
-	
-	chan_misdn_log(1,port,"read_config: Getting Config\n");
+	port = bc->port;
 
-	char lang[BUFFERSIZE+1];
-	
+	chan_misdn_log(1, port, "read_config: Getting Config\n");
 
-	misdn_cfg_get( port, MISDN_CFG_LANGUAGE, lang, BUFFERSIZE);
+	misdn_cfg_get(port, MISDN_CFG_LANGUAGE, lang, sizeof(lang));
 	ast_string_field_set(ast, language, lang);
 
-	char localmusicclass[BUFFERSIZE+1];
-	
-	misdn_cfg_get( port, MISDN_CFG_MUSICCLASS, localmusicclass, BUFFERSIZE);
+	misdn_cfg_get(port, MISDN_CFG_MUSICCLASS, localmusicclass, sizeof(localmusicclass));
 	ast_string_field_set(ast, musicclass, localmusicclass);
-	
-	
-	misdn_cfg_get( port, MISDN_CFG_TXGAIN, &bc->txgain, sizeof(int));
-	misdn_cfg_get( port, MISDN_CFG_RXGAIN, &bc->rxgain, sizeof(int));
-	
-	misdn_cfg_get( port, MISDN_CFG_INCOMING_EARLY_AUDIO, &ch->incoming_early_audio, sizeof(int));
-	
-	misdn_cfg_get( port, MISDN_CFG_SENDDTMF, &bc->send_dtmf, sizeof(int));
 
-	misdn_cfg_get( port, MISDN_CFG_NEED_MORE_INFOS, &bc->need_more_infos, sizeof(int));
-	misdn_cfg_get( port, MISDN_CFG_NTTIMEOUT, &ch->nttimeout, sizeof(int));
-	
-	misdn_cfg_get( port, MISDN_CFG_NOAUTORESPOND_ON_SETUP, &ch->noautorespond_on_setup, sizeof(int));
-	
-	misdn_cfg_get( port, MISDN_CFG_FAR_ALERTING, &ch->far_alerting, sizeof(int));
+	misdn_cfg_get(port, MISDN_CFG_TXGAIN, &bc->txgain, sizeof(bc->txgain));
+	misdn_cfg_get(port, MISDN_CFG_RXGAIN, &bc->rxgain, sizeof(bc->rxgain));
+
+	misdn_cfg_get(port, MISDN_CFG_INCOMING_EARLY_AUDIO, &ch->incoming_early_audio, sizeof(ch->incoming_early_audio));
+
+	misdn_cfg_get(port, MISDN_CFG_SENDDTMF, &bc->send_dtmf, sizeof(bc->send_dtmf));
+
+	misdn_cfg_get(port, MISDN_CFG_NEED_MORE_INFOS, &bc->need_more_infos, sizeof(bc->need_more_infos));
+	misdn_cfg_get(port, MISDN_CFG_NTTIMEOUT, &ch->nttimeout, sizeof(ch->nttimeout));
+
+	misdn_cfg_get(port, MISDN_CFG_NOAUTORESPOND_ON_SETUP, &ch->noautorespond_on_setup, sizeof(ch->noautorespond_on_setup));
+
+	misdn_cfg_get(port, MISDN_CFG_FAR_ALERTING, &ch->far_alerting, sizeof(ch->far_alerting));
+
+	misdn_cfg_get(port, MISDN_CFG_ALLOWED_BEARERS, &ch->allowed_bearers, sizeof(ch->allowed_bearers));
+
+  	misdn_cfg_get(port, MISDN_CFG_FAXDETECT, faxdetect, sizeof(faxdetect));
+
+	misdn_cfg_get(port, MISDN_CFG_HDLC, &hdlc, sizeof(hdlc));
 
-	misdn_cfg_get( port, MISDN_CFG_ALLOWED_BEARERS, &ch->allowed_bearers, BUFFERSIZE);
-	
-  	char faxdetect[BUFFERSIZE+1];
-  	misdn_cfg_get( port, MISDN_CFG_FAXDETECT, faxdetect, BUFFERSIZE);
-	
-	int hdlc=0;
-	misdn_cfg_get( port, MISDN_CFG_HDLC, &hdlc, sizeof(int));
-	
 	if (hdlc) {
 		switch (bc->capability) {
 		case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
 		case INFO_CAPABILITY_DIGITAL_RESTRICTED:
-			chan_misdn_log(1,bc->port," --> CONF HDLC\n");
-			bc->hdlc=1;
+			chan_misdn_log(1, bc->port, " --> CONF HDLC\n");
+			bc->hdlc = 1;
 			break;
 		}
 		
 	}
 	/*Initialize new Jitterbuffer*/
-	{
-		misdn_cfg_get( port, MISDN_CFG_JITTERBUFFER, &ch->jb_len, sizeof(int));
-		misdn_cfg_get( port, MISDN_CFG_JITTERBUFFER_UPPER_THRESHOLD, &ch->jb_upper_threshold, sizeof(int));
-		
-		config_jitterbuffer(ch);
-	}
-	
-	misdn_cfg_get( bc->port, MISDN_CFG_CONTEXT, ch->context, sizeof(ch->context));
-	
-	ast_copy_string (ast->context,ch->context,sizeof(ast->context));	
+	misdn_cfg_get(port, MISDN_CFG_JITTERBUFFER, &ch->jb_len, sizeof(ch->jb_len));
+	misdn_cfg_get(port, MISDN_CFG_JITTERBUFFER_UPPER_THRESHOLD, &ch->jb_upper_threshold, sizeof(ch->jb_upper_threshold));
+
+	config_jitterbuffer(ch);
+
+	misdn_cfg_get(bc->port, MISDN_CFG_CONTEXT, ch->context, sizeof(ch->context));
+
+	ast_copy_string(ast->context, ch->context, sizeof(ast->context));
 
 #ifdef MISDN_1_2
 	update_pipeline_config(bc);
@@ -1791,130 +1777,102 @@ static int read_config(struct chan_list *ch, int orig) {
 	update_ec_config(bc);
 #endif
 
-	{
-		int eb3;
-		
-		misdn_cfg_get( bc->port, MISDN_CFG_EARLY_BCONNECT, &eb3, sizeof(int));
-		bc->early_bconnect=eb3;
-	}
-	
-	port=bc->port;
-	
-	{
-		char buf[256];
-		ast_group_t pg,cg;
-		
-		misdn_cfg_get(port, MISDN_CFG_PICKUPGROUP, &pg, sizeof(pg));
-		misdn_cfg_get(port, MISDN_CFG_CALLGROUP, &cg, sizeof(cg));
-		
-		chan_misdn_log(5, port, " --> * CallGrp:%s PickupGrp:%s\n",ast_print_group(buf,sizeof(buf),cg),ast_print_group(buf,sizeof(buf),pg));
-		ast->pickupgroup=pg;
-		ast->callgroup=cg;
-	}
+	misdn_cfg_get(bc->port, MISDN_CFG_EARLY_BCONNECT, &bc->early_bconnect, sizeof(bc->early_bconnect));
+
+	misdn_cfg_get(port, MISDN_CFG_PICKUPGROUP, &pg, sizeof(pg));
+	misdn_cfg_get(port, MISDN_CFG_CALLGROUP, &cg, sizeof(cg));
+
+	chan_misdn_log(5, port, " --> * CallGrp:%s PickupGrp:%s\n", ast_print_group(buf, sizeof(buf), cg), ast_print_group(buf2, sizeof(buf2), pg));
+	ast->pickupgroup = pg;
+	ast->callgroup = cg;
 	
-	if ( orig  == ORG_AST) {
-		misdn_cfg_get( port, MISDN_CFG_TE_CHOOSE_CHANNEL, &(bc->te_choose_channel), sizeof(int));
-		
+	if (orig == ORG_AST) {
+		char callerid[BUFFERSIZE + 1];
+
+		misdn_cfg_get(port, MISDN_CFG_TE_CHOOSE_CHANNEL, &(bc->te_choose_channel), sizeof(bc->te_choose_channel));
+
  		if (strstr(faxdetect, "outgoing") || strstr(faxdetect, "both")) {
  			if (strstr(faxdetect, "nojump"))
- 				ch->faxdetect=2;
+ 				ch->faxdetect = 2;
  			else
- 				ch->faxdetect=1;
+ 				ch->faxdetect = 1;
  		}
 
-		{
-			char callerid[BUFFERSIZE+1];
-			misdn_cfg_get( port, MISDN_CFG_CALLERID, callerid, BUFFERSIZE);
-			if ( ! ast_strlen_zero(callerid) ) {
-				chan_misdn_log(1, port, " --> * Setting Cid to %s\n", callerid);
-				{
-					int l = sizeof(bc->oad);
-					strncpy(bc->oad,callerid, l);
-					bc->oad[l-1] = 0;
-				}
-
-			}
-
-			
-			misdn_cfg_get( port, MISDN_CFG_DIALPLAN, &bc->dnumplan, sizeof(int));
-			misdn_cfg_get( port, MISDN_CFG_LOCALDIALPLAN, &bc->onumplan, sizeof(int));
-			misdn_cfg_get( port, MISDN_CFG_CPNDIALPLAN, &bc->cpnnumplan, sizeof(int));
-			debug_numplan(port, bc->dnumplan,"TON");
-			debug_numplan(port, bc->onumplan,"LTON");
-			debug_numplan(port, bc->cpnnumplan,"CTON");
+		misdn_cfg_get(port, MISDN_CFG_CALLERID, callerid, sizeof(callerid));
+		if ( ! ast_strlen_zero(callerid) ) {
+			chan_misdn_log(1, port, " --> * Setting Cid to %s\n", callerid);
+			ast_copy_string(bc->oad, callerid, sizeof(bc->oad));
 		}
 
+		misdn_cfg_get(port, MISDN_CFG_DIALPLAN, &bc->dnumplan, sizeof(bc->dnumplan));
+		misdn_cfg_get(port, MISDN_CFG_LOCALDIALPLAN, &bc->onumplan, sizeof(bc->onumplan));
+		misdn_cfg_get(port, MISDN_CFG_CPNDIALPLAN, &bc->cpnnumplan, sizeof(bc->cpnnumplan));
+		debug_numplan(port, bc->dnumplan, "TON");
+		debug_numplan(port, bc->onumplan, "LTON");
+		debug_numplan(port, bc->cpnnumplan, "CTON");
+
 		ch->overlap_dial = 0;
 	} else { /** ORIGINATOR MISDN **/
+		char prefix[BUFFERSIZE + 1] = "";
+
  		if (strstr(faxdetect, "incoming") || strstr(faxdetect, "both")) {
  			if (strstr(faxdetect, "nojump"))
- 				ch->faxdetect=2;
+ 				ch->faxdetect = 2;
  			else
- 				ch->faxdetect=1;
+ 				ch->faxdetect = 1;
  		}
-	
-		misdn_cfg_get( port, MISDN_CFG_CPNDIALPLAN, &bc->cpnnumplan, sizeof(int));
-		debug_numplan(port, bc->cpnnumplan,"CTON");
-		
-		char prefix[BUFFERSIZE+1]="";
-		switch( bc->onumplan ) {
+
+		misdn_cfg_get(port, MISDN_CFG_CPNDIALPLAN, &bc->cpnnumplan, sizeof(bc->cpnnumplan));
+		debug_numplan(port, bc->cpnnumplan, "CTON");
+
+		switch (bc->onumplan) {
 		case NUMPLAN_INTERNATIONAL:
-			misdn_cfg_get( bc->port, MISDN_CFG_INTERNATPREFIX, prefix, BUFFERSIZE);
+			misdn_cfg_get(bc->port, MISDN_CFG_INTERNATPREFIX, prefix, sizeof(prefix));
 			break;
-			
+
 		case NUMPLAN_NATIONAL:
-			misdn_cfg_get( bc->port, MISDN_CFG_NATPREFIX, prefix, BUFFERSIZE);
+			misdn_cfg_get(bc->port, MISDN_CFG_NATPREFIX, prefix, sizeof(prefix));
 			break;
 		default:
 			break;
 		}
-		
-		{
-			int l = strlen(prefix) + strlen(bc->oad);
-			char tmp[l+1];
-			strcpy(tmp,prefix);
-			strcat(tmp,bc->oad);
-			strcpy(bc->oad,tmp);
-		}
-		
+
+		ast_copy_string(buf, bc->oad, sizeof(buf));
+		snprintf(bc->oad, sizeof(bc->oad), "%s%s", prefix, buf);
+
 		if (!ast_strlen_zero(bc->dad)) {
-			ast_copy_string(bc->orig_dad,bc->dad, sizeof(bc->orig_dad));
+			ast_copy_string(bc->orig_dad, bc->dad, sizeof(bc->orig_dad));
 		}
-		
+
 		if ( ast_strlen_zero(bc->dad) && !ast_strlen_zero(bc->keypad)) {
-			ast_copy_string(bc->dad,bc->keypad, sizeof(bc->dad));
+			ast_copy_string(bc->dad, bc->keypad, sizeof(bc->dad));
 		}
 
 		prefix[0] = 0;
-		
-		switch( bc->dnumplan ) {
+
+		switch (bc->dnumplan) {
 		case NUMPLAN_INTERNATIONAL:
-			misdn_cfg_get( bc->port, MISDN_CFG_INTERNATPREFIX, prefix, BUFFERSIZE);
+			misdn_cfg_get(bc->port, MISDN_CFG_INTERNATPREFIX, prefix, sizeof(prefix));
 			break;
 		case NUMPLAN_NATIONAL:
-			misdn_cfg_get( bc->port, MISDN_CFG_NATPREFIX, prefix, BUFFERSIZE);
+			misdn_cfg_get(bc->port, MISDN_CFG_NATPREFIX, prefix, sizeof(prefix));
 			break;
 		default:
 			break;
 		}
-		
-		{
-			int l = strlen(prefix) + strlen(bc->dad);
-			char tmp[l+1];
-			strcpy(tmp,prefix);
-			strcat(tmp,bc->dad);
-			strcpy(bc->dad,tmp);
-		}
-		
-		if ( strcmp(bc->dad,ast->exten)) {
+
+		ast_copy_string(buf, bc->dad, sizeof(buf));
+		snprintf(bc->dad, sizeof(bc->dad), "%s%s", prefix, buf);
+
+		if (strcmp(bc->dad, ast->exten)) {
 			ast_copy_string(ast->exten, bc->dad, sizeof(ast->exten));
 		}
-		
+
 		ast_set_callerid(ast, bc->oad, NULL, bc->oad);
-		
+
 		if ( !ast_strlen_zero(bc->rad) ) {
 			if (ast->cid.cid_rdnis)
-				free(ast->cid.cid_rdnis);
+				ast_free(ast->cid.cid_rdnis);
 			ast->cid.cid_rdnis = strdup(bc->rad);
 		}
 	
@@ -1925,13 +1883,13 @@ static int read_config(struct chan_list *ch, int orig) {
 	ch->overlap_dial_task = -1;
 	
 	if (ch->faxdetect) {
-		misdn_cfg_get( port, MISDN_CFG_FAXDETECT_TIMEOUT, &ch->faxdetect_timeout, sizeof(ch->faxdetect_timeout));
+		misdn_cfg_get(port, MISDN_CFG_FAXDETECT_TIMEOUT, &ch->faxdetect_timeout, sizeof(ch->faxdetect_timeout));
 		if (!ch->dsp)
 			ch->dsp = ast_dsp_new();
 		if (ch->dsp)
 			ast_dsp_set_features(ch->dsp, DSP_FEATURE_DTMF_DETECT | DSP_FEATURE_FAX_DETECT);
 		if (!ch->trans)
-			ch->trans=ast_translator_build_path(AST_FORMAT_SLINEAR, AST_FORMAT_ALAW);
+			ch->trans = ast_translator_build_path(AST_FORMAT_SLINEAR, AST_FORMAT_ALAW);
 	}
 
 	/* AOCD initialization */
@@ -1947,27 +1905,24 @@ static int read_config(struct chan_list *ch, int orig) {
 
 static int misdn_call(struct ast_channel *ast, char *dest, int timeout)
 {
-	int port=0;
+	int port = 0;
 	int r;
-	struct chan_list *ch=MISDN_ASTERISK_TECH_PVT(ast);
+	int exceed;
+	int bridging;
+	struct chan_list *ch = MISDN_ASTERISK_TECH_PVT(ast);
 	struct misdn_bchannel *newbc;
-	char *opts=NULL, *ext,*tokb;
-	char dest_cp[256];
+	char *opts = NULL, *ext, *tokb;
+	char *dest_cp = ast_strdupa(dest);
 
-	{
-		strncpy(dest_cp,dest,sizeof(dest_cp)-1);
-		dest_cp[sizeof(dest_cp)]=0;
-		
-		ext=strtok_r(dest_cp,"/",&tokb);
-		
+	ext = strtok_r(dest_cp, "/", &tokb);
+
+	if (ext) {
+		ext = strtok_r(NULL, "/", &tokb);
 		if (ext) {
-			ext=strtok_r(NULL,"/",&tokb);
-			if (ext) {
-				opts=strtok_r(NULL,"/",&tokb);
-			} else {
-				chan_misdn_log(0,0,"misdn_call: No Extension given!\n");
-				return -1;
-			}
+			opts = strtok_r(NULL, "/", &tokb);
+		} else {
+			chan_misdn_log(0, 0, "misdn_call: No Extension given!\n");
+			return -1;
 		}
 	}
 
@@ -1978,127 +1933,110 @@ static int misdn_call(struct ast_channel *ast, char *dest, int timeout)
 
 	if (((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) || !dest  ) {
 		ast_log(LOG_WARNING, " --> ! misdn_call called on %s, neither down nor reserved (or dest==NULL)\n", ast->name);
-		ast->hangupcause=41;
+		ast->hangupcause = AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
 		ast_setstate(ast, AST_STATE_DOWN);
 		return -1;
 	}
 
 	if (!ch) {
 		ast_log(LOG_WARNING, " --> ! misdn_call called on %s, neither down nor reserved (or dest==NULL)\n", ast->name);
-		ast->hangupcause=41;
+		ast->hangupcause = AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
 		ast_setstate(ast, AST_STATE_DOWN);
 		return -1;
 	}
 	
-	newbc=ch->bc;
+	newbc = ch->bc;
 	
 	if (!newbc) {
 		ast_log(LOG_WARNING, " --> ! misdn_call called on %s, neither down nor reserved (or dest==NULL)\n", ast->name);
-		ast->hangupcause=41;
+		ast->hangupcause = AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
 		ast_setstate(ast, AST_STATE_DOWN);
 		return -1;
 	}
 	
-	port=newbc->port;
-
+	port = newbc->port;
 
-	int exceed;
-	if ((exceed=add_out_calls(port))) {
+	if ((exceed = add_out_calls(port))) {
 		char tmp[16];
-		sprintf(tmp,"%d",exceed);
-		pbx_builtin_setvar_helper(ast,"MAX_OVERFLOW",tmp);
+		snprintf(tmp, sizeof(tmp), "%d", exceed);
+		pbx_builtin_setvar_helper(ast, "MAX_OVERFLOW", tmp);
 		return -1;
 	}
 	
-	chan_misdn_log(1, port, "* CALL: %s\n",dest);
+	chan_misdn_log(1, port, "* CALL: %s\n", dest);
 	
-	chan_misdn_log(2, port, " --> * dad:%s tech:%s ctx:%s\n",ast->exten,ast->name, ast->context);
+	chan_misdn_log(2, port, " --> * dad:%s tech:%s ctx:%s\n", ast->exten, ast->name, ast->context);
 	
-	chan_misdn_log(3, port, " --> * adding2newbc ext %s\n",ast->exten);
+	chan_misdn_log(3, port, " --> * adding2newbc ext %s\n", ast->exten);
 	if (ast->exten) {
-		int l = sizeof(newbc->dad);
-		strncpy(ast->exten,ext,sizeof(ast->exten));
-
-		strncpy(newbc->dad,ext,l);
-
-		newbc->dad[l-1] = 0;
+		ast_copy_string(ast->exten, ext, sizeof(ast->exten));
+		ast_copy_string(newbc->dad, ext, sizeof(newbc->dad));
 	}
 
-	if (ast->cid.cid_rdnis)  
-		strcpy(newbc->rad, ast->cid.cid_rdnis);
+	if (!ast_strlen_zero(ast->cid.cid_rdnis))
+		ast_copy_string(newbc->rad, ast->cid.cid_rdnis, sizeof(newbc->rad));
 	else 
-		newbc->rad[0]=0;
+		newbc->rad = "";
 
-	chan_misdn_log(3, port, " --> * adding2newbc callerid %s\n",ast->cid.cid_num);
-	if (ast_strlen_zero(newbc->oad) && ast->cid.cid_num ) {
+	chan_misdn_log(3, port, " --> * adding2newbc callerid %s\n", ast->cid.cid_num);
+	if (ast_strlen_zero(newbc->oad) && !ast_strlen_zero(ast->cid.cid_num)) {
+		ast_copy_string(newbc->oad, ast->cid.cid_num, sizeof(newbc->oad));
+	}
 
-		if (ast->cid.cid_num) {
-			int l = sizeof(newbc->oad);
-			strncpy(newbc->oad,ast->cid.cid_num, l);
-			newbc->oad[l-1] = 0;
-		}
+	newbc->capability = ast->transfercapability;
+	pbx_builtin_setvar_helper(ast, "TRANSFERCAPABILITY", ast_transfercapability2str(newbc->capability));
+	if ( ast->transfercapability == INFO_CAPABILITY_DIGITAL_UNRESTRICTED) {
+		chan_misdn_log(2, port, " --> * Call with flag Digital\n");
 	}
 
-	{
-		struct chan_list *ch=MISDN_ASTERISK_TECH_PVT(ast);
-		if (!ch) { ast_verbose("No chan_list in misdn_call\n"); return -1;}
-		
-		newbc->capability=ast->transfercapability;
-		pbx_builtin_setvar_helper(ast,"TRANSFERCAPABILITY",ast_transfercapability2str(newbc->capability));
-		if ( ast->transfercapability == INFO_CAPABILITY_DIGITAL_UNRESTRICTED) {
-			chan_misdn_log(2, port, " --> * Call with flag Digital\n");
-		}
+	/* update screening and presentation */ 
+	update_config(ch, ORG_AST);
 		
+	/* fill in some ies from channel vary*/
+	import_ch(ast, newbc, ch);
 
-		/* update screening and presentation */ 
-		update_config(ch,ORG_AST);
-		
-		/* fill in some ies from channel vary*/
-		import_ch(ast, newbc, ch);
-		
-		/* Finally The Options Override Everything */
-		if (opts)
-			misdn_set_opt_exec(ast,opts);
-		else
-			chan_misdn_log(2,port,"NO OPTS GIVEN\n");
+	/* Finally The Options Override Everything */
+	if (opts)
+		misdn_set_opt_exec(ast, opts);
+	else
+		chan_misdn_log(2, port, "NO OPTS GIVEN\n");
 
-		/*check for bridging*/
-		int bridging;
-		misdn_cfg_get( 0, MISDN_GEN_BRIDGING, &bridging, sizeof(int));
-		if (bridging && ch->other_ch) {
+	/*check for bridging*/
+	misdn_cfg_get(0, MISDN_GEN_BRIDGING, &bridging, sizeof(bridging));
+	if (bridging && ch->other_ch) {
 #ifdef MISDN_1_2
-			chan_misdn_log(1, port, "Disabling EC (aka Pipeline) on both Sides\n");
-			*ch->bc->pipeline=0;
-			*ch->other_ch->bc->pipeline=0;
+		chan_misdn_log(1, port, "Disabling EC (aka Pipeline) on both Sides\n");
+		*ch->bc->pipeline = 0;
+		*ch->other_ch->bc->pipeline = 0;
 #else
-			chan_misdn_log(1, port, "Disabling EC on both Sides\n");
-			ch->bc->ec_enable=0;
-			ch->other_ch->bc->ec_enable=0;
+		chan_misdn_log(1, port, "Disabling EC on both Sides\n");
+		ch->bc->ec_enable = 0;
+		ch->other_ch->bc->ec_enable = 0;
 #endif
-		}
-		
-		r=misdn_lib_send_event( newbc, EVENT_SETUP );
-		
-		/** we should have l3id after sending setup **/
-		ch->l3id=newbc->l3_id;
 	}
-	
+
+	r = misdn_lib_send_event( newbc, EVENT_SETUP );
+
+	/** we should have l3id after sending setup **/
+	ch->l3id = newbc->l3_id;
+
 	if ( r == -ENOCHAN  ) {
 		chan_misdn_log(0, port, " --> * Theres no Channel at the moment .. !\n");
-		chan_misdn_log(1, port, " --> * SEND: State Down pid:%d\n",newbc?newbc->pid:-1);
-		ast->hangupcause=34;
+		chan_misdn_log(1, port, " --> * SEND: State Down pid:%d\n", newbc ? newbc->pid : -1);
+		ast->hangupcause = AST_CAUSE_NORMAL_CIRCUIT_CONGESTION;
 		ast_setstate(ast, AST_STATE_DOWN);
 		return -1;
 	}
 	
-	chan_misdn_log(2, port, " --> * SEND: State Dialing pid:%d\n",newbc?newbc->pid:1);
+	chan_misdn_log(2, port, " --> * SEND: State Dialing pid:%d\n", newbc ? newbc->pid : 1);
 
 	ast_setstate(ast, AST_STATE_DIALING);
-	ast->hangupcause=16;
+	ast->hangupcause = AST_CAUSE_NORMAL_CLEARING;
 	
-	if (newbc->nt) stop_bc_tones(ch);
+	if (newbc->nt)
+		stop_bc_tones(ch);
 
-	ch->state=MISDN_CALLING;
+	ch->state = MISDN_CALLING;
 	
 	return 0; 
 }
@@ -2107,11 +2045,11 @@ static int misdn_call(struct ast_channel *ast, char *dest, int timeout)
 static int misdn_answer(struct ast_channel *ast)
 {
 	struct chan_list *p;
+	const char *tmp;
 
+	if (!ast || ! (p = MISDN_ASTERISK_TECH_PVT(ast)) ) return -1;
 	
-	if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast)) ) return -1;
-	
-	chan_misdn_log(1, p? (p->bc? p->bc->port : 0) : 0, "* ANSWER:\n");
+	chan_misdn_log(1, p ? (p->bc ? p->bc->port : 0) : 0, "* ANSWER:\n");
 	
 	if (!p) {
 		ast_log(LOG_WARNING, " --> Channel not connected ??\n");
@@ -2124,43 +2062,36 @@ static int misdn_answer(struct ast_channel *ast)
 		ast_queue_hangup(ast);
 	}
 
-	{
-		const char *tmp_key = pbx_builtin_getvar_helper(p->ast, "CRYPT_KEY");
-		
-		if (tmp_key ) {
-			chan_misdn_log(1, p->bc->port, " --> Connection will be BF crypted\n");
-			{
-				int l = sizeof(p->bc->crypt_key);
-				strncpy(p->bc->crypt_key,tmp_key, l);
-				p->bc->crypt_key[l-1] = 0;
-			}
-		} else {
-			chan_misdn_log(3, p->bc->port, " --> Connection is without BF encryption\n");
-		}
-    
+	tmp = pbx_builtin_getvar_helper(p->ast, "CRYPT_KEY");
+
+	if (!ast_strlen_zero(tmp)) {
+		chan_misdn_log(1, p->bc->port, " --> Connection will be BF crypted\n");
+		ast_copy_string(p->bc->crypt_key, tmp, sizeof(p->bc->crypt_key));
+	} else {
+		chan_misdn_log(3, p->bc->port, " --> Connection is without BF encryption\n");
 	}
 
 	{
-		const char *nodsp=pbx_builtin_getvar_helper(ast, "MISDN_DIGITAL_TRANS");
-		if (nodsp) {
-			chan_misdn_log(1, p->bc->port, " --> Connection is transparent digital\n");
-			p->bc->nodsp=1;
-			p->bc->hdlc=0;
-			p->bc->nojitter=1;
-		}
+
+	tmp = pbx_builtin_getvar_helper(ast, "MISDN_DIGITAL_TRANS");
+	if (!ast_strlen_zero(tmp) && ast_true(tmp)) {
+		chan_misdn_log(1, p->bc->port, " --> Connection is transparent digital\n");
+		p->bc->nodsp = 1;
+		p->bc->hdlc = 0;
+		p->bc->nojitter = 1;
 	}
-	
+
 	p->state = MISDN_CONNECTED;
 	stop_indicate(p);
 
 	if ( ast_strlen_zero(p->bc->cad) ) {
 		chan_misdn_log(2,p->bc->port," --> empty cad using dad\n");
-		ast_copy_string(p->bc->cad,p->bc->dad,sizeof(p->bc->cad));
+		ast_copy_string(p->bc->cad, p->bc->dad, sizeof(p->bc->cad));
 	}
 
 	misdn_lib_send_event( p->bc, EVENT_CONNECT);
 	start_bc_tones(p);
-	
+
 	return 0;
 }
 
@@ -2173,11 +2104,13 @@ static int misdn_digit_begin(struct ast_channel *chan, char digit)
 static int misdn_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
 {
 	struct chan_list *p;
+	struct misdn_bchannel *bc;
+	char buf[2] = { digit, 0 };
 	
 	if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast))) return -1;
 
-	struct misdn_bchannel *bc=p->bc;
-	chan_misdn_log(1, bc?bc->port:0, "* IND : Digit %c\n",digit);
+	bc = p->bc;
+	chan_misdn_log(1, bc ? bc->port : 0, "* IND : Digit %c\n", digit);
 	
 	if (!bc) {
 		ast_log(LOG_WARNING, " --> !! Got Digit Event withut having bchannel Object\n");
@@ -2185,45 +2118,24 @@ static int misdn_digit_end(struct ast_channel *ast, char digit, unsigned int dur
 	}
 	
 	switch (p->state ) {
-		case MISDN_CALLING:
-		{
-			
-			char buf[8];
-			buf[0]=digit;
-			buf[1]=0;
-			
-			int l = sizeof(bc->infos_pending);
-			strncat(bc->infos_pending,buf,l);
-			bc->infos_pending[l-1] = 0;
-		}
+	case MISDN_CALLING:
+		if (strlen(bc->infos_pending) < sizeof(bc->infos_pending) - 1)
+			strncat(bc->infos_pending, buf, sizeof(bc->infos_pending) - 1);
 		break;
-		case MISDN_CALLING_ACKNOWLEDGE:
-		{
-			bc->info_dad[0]=digit;
-			bc->info_dad[1]=0;
-			
-			{
-				int l = sizeof(bc->dad);
-				strncat(bc->dad,bc->info_dad, l - strlen(bc->dad));
-				bc->dad[l-1] = 0;
-		}
-			{
-				int l = sizeof(p->ast->exten);
-				strncpy(p->ast->exten, bc->dad, l);
-				p->ast->exten[l-1] = 0;
-			}
-			
-			misdn_lib_send_event( bc, EVENT_INFORMATION);
-		}
+	case MISDN_CALLING_ACKNOWLEDGE:
+		ast_copy_string(bc->info_dad, buf, sizeof(bc->info_dad));
+		if (strlen(bc->dad) < sizeof(bc->dad) - 1)
+			strncat(bc->dad, buf, sizeof(bc->dad) - 1);
+		ast_copy_string(p->ast->exten, bc->dad, sizeof(p->ast->exten));
+		misdn_lib_send_event( bc, EVENT_INFORMATION);
 		break;
-		
-		default:
-			if ( bc->send_dtmf ) {
-				send_digit_to_chan(p,digit);
-			}
+	default:
+		if (bc->send_dtmf) {
+			send_digit_to_chan(p, digit);
+		}
 		break;
 	}
-	
+
 	return 0;
 }
 
@@ -2231,13 +2143,13 @@ static int misdn_digit_end(struct ast_channel *ast, char digit, unsigned int dur
 static int misdn_fixup(struct ast_channel *oldast, struct ast_channel *ast)
 {
 	struct chan_list *p;
-	
+
 	if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast) )) return -1;
-	
-	chan_misdn_log(1, p->bc?p->bc->port:0, "* IND: Got Fixup State:%s L3id:%x\n", misdn_get_ch_state(p), p->l3id);
-	
-	p->ast = ast ;
-  
+
+	chan_misdn_log(1, p->bc ? p->bc->port : 0, "* IND: Got Fixup State:%s L3id:%x\n", misdn_get_ch_state(p), p->l3id);
+
+	p->ast = ast;
+
 	return 0;
 }
 
@@ -2247,26 +2159,25 @@ static int misdn_indication(struct ast_channel *ast, int cond, const void *data,
 {
 	struct chan_list *p;
 
-  
 	if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast))) {
-		ast_log(LOG_WARNING, "Returnded -1 in misdn_indication\n");
+		ast_log(LOG_WARNING, "Returned -1 in misdn_indication\n");
 		return -1;
 	}
 	
 	if (!p->bc ) {
-		chan_misdn_log(1, 0, "* IND : Indication from %s\n",ast->exten);
+		chan_misdn_log(1, 0, "* IND : Indication from %s\n", ast->exten);
 		ast_log(LOG_WARNING, "Private Pointer but no bc ?\n");
 		return -1;
 	}
 	
-	chan_misdn_log(5, p->bc->port, "* IND : Indication [%d] from %s\n",cond, ast->exten);
+	chan_misdn_log(5, p->bc->port, "* IND : Indication [%d] from %s\n", cond, ast->exten);
 	
 	switch (cond) {
 	case AST_CONTROL_BUSY:
-		chan_misdn_log(1, p->bc->port, "* IND :\tbusy pid:%d\n",p->bc?p->bc->pid:-1);
-		ast_setstate(ast,AST_STATE_BUSY);
+		chan_misdn_log(1, p->bc->port, "* IND :\tbusy pid:%d\n", p->bc ? p->bc->pid : -1);
+		ast_setstate(ast, AST_STATE_BUSY);
 
-		p->bc->out_cause=17;
+		p->bc->out_cause = AST_CAUSE_USER_BUSY;
 		if (p->state != MISDN_CONNECTED) {
 			start_bc_tones(p);
 			misdn_lib_send_event( p->bc, EVENT_DISCONNECT);
@@ -2274,75 +2185,69 @@ static int misdn_indication(struct ast_channel *ast, int cond, const void *data,
 			chan_misdn_log(-1, p->bc->port, " --> !! Got Busy in Connected State !?! ast:%s\n", ast->name);
 		}
 		return -1;
-		break;
 	case AST_CONTROL_RING:
-		chan_misdn_log(1, p->bc->port, "* IND :\tring pid:%d\n",p->bc?p->bc->pid:-1);
+		chan_misdn_log(1, p->bc->port, "* IND :\tring pid:%d\n", p->bc ? p->bc->pid : -1);
 		return -1;
-		break;
-		
 	case AST_CONTROL_RINGING:
-		chan_misdn_log(1, p->bc->port, "* IND :\tringing pid:%d\n",p->bc?p->bc->pid:-1);
+		chan_misdn_log(1, p->bc->port, "* IND :\tringing pid:%d\n", p->bc ? p->bc->pid : -1);
 		switch (p->state) {
-			case MISDN_ALERTING:
-				chan_misdn_log(2, p->bc->port, " --> * IND :\tringing pid:%d but I was Ringing before, so ignoreing it\n",p->bc?p->bc->pid:-1);
-				break;
-			case MISDN_CONNECTED:
-				chan_misdn_log(2, p->bc->port, " --> * IND :\tringing pid:%d but Connected, so just send TONE_ALERTING without state changes \n",p->bc?p->bc->pid:-1);
-				return -1;
-				break;
-			default:
-				p->state=MISDN_ALERTING;
-				chan_misdn_log(2, p->bc->port, " --> * IND :\tringing pid:%d\n",p->bc?p->bc->pid:-1);
-				misdn_lib_send_event( p->bc, EVENT_ALERTING);
+		case MISDN_ALERTING:
+			chan_misdn_log(2, p->bc->port, " --> * IND :\tringing pid:%d but I was Ringing before, so ignoreing it\n", p->bc ? p->bc->pid : -1);
+			break;
+		case MISDN_CONNECTED:
+			chan_misdn_log(2, p->bc->port, " --> * IND :\tringing pid:%d but Connected, so just send TONE_ALERTING without state changes \n", p->bc ? p->bc->pid : -1);
+			return -1;
+		default:
+			p->state = MISDN_ALERTING;
+			chan_misdn_log(2, p->bc->port, " --> * IND :\tringing pid:%d\n", p->bc ? p->bc->pid : -1);
+			misdn_lib_send_event( p->bc, EVENT_ALERTING);
 			
-				if (p->other_ch && p->other_ch->bc) {
-					if (misdn_inband_avail(p->other_ch->bc)) {
-						chan_misdn_log(2,p->bc->port, " --> other End is mISDN and has inband info available\n");
-						break;
-					}
+			if (p->other_ch && p->other_ch->bc) {
+				if (misdn_inband_avail(p->other_ch->bc)) {
+					chan_misdn_log(2, p->bc->port, " --> other End is mISDN and has inband info available\n");
+					break;
+				}
 
-					if (!p->other_ch->bc->nt) {
-						chan_misdn_log(2,p->bc->port, " --> other End is mISDN TE so it has inband info for sure (?)\n");
-						break;
-					}
+				if (!p->other_ch->bc->nt) {
+					chan_misdn_log(2, p->bc->port, " --> other End is mISDN TE so it has inband info for sure (?)\n");
+					break;
 				}
+			}
 
-				chan_misdn_log(3, p->bc->port, " --> * SEND: State Ring pid:%d\n",p->bc?p->bc->pid:-1);
-				ast_setstate(ast,AST_STATE_RINGING);
+			chan_misdn_log(3, p->bc->port, " --> * SEND: State Ring pid:%d\n", p->bc ? p->bc->pid : -1);
+			ast_setstate(ast, AST_STATE_RINGING);
 			
-				if ( !p->bc->nt && (p->originator==ORG_MISDN) && !p->incoming_early_audio ) 
-					chan_misdn_log(2,p->bc->port, " --> incoming_early_audio off\n");
-				else 
-					return -1;
+			if ( !p->bc->nt && (p->originator == ORG_MISDN) && !p->incoming_early_audio ) 
+				chan_misdn_log(2, p->bc->port, " --> incoming_early_audio off\n");
+			else 
+				return -1;
 		}
 		break;
 	case AST_CONTROL_ANSWER:
-		chan_misdn_log(1, p->bc->port, " --> * IND :\tanswer pid:%d\n",p->bc?p->bc->pid:-1);
+		chan_misdn_log(1, p->bc->port, " --> * IND :\tanswer pid:%d\n", p->bc ? p->bc->pid : -1);
 		start_bc_tones(p);
 		break;
 	case AST_CONTROL_TAKEOFFHOOK:
-		chan_misdn_log(1, p->bc->port, " --> *\ttakeoffhook pid:%d\n",p->bc?p->bc->pid:-1);
+		chan_misdn_log(1, p->bc->port, " --> *\ttakeoffhook pid:%d\n", p->bc ? p->bc->pid : -1);
 		return -1;
-		break;
 	case AST_CONTROL_OFFHOOK:
-		chan_misdn_log(1, p->bc->port, " --> *\toffhook pid:%d\n",p->bc?p->bc->pid:-1);
+		chan_misdn_log(1, p->bc->port, " --> *\toffhook pid:%d\n", p->bc ? p->bc->pid : -1);
 		return -1;
-		break; 
 	case AST_CONTROL_FLASH:
-		chan_misdn_log(1, p->bc->port, " --> *\tflash pid:%d\n",p->bc?p->bc->pid:-1);
+		chan_misdn_log(1, p->bc->port, " --> *\tflash pid:%d\n", p->bc ? p->bc->pid : -1);
 		break;
 	case AST_CONTROL_PROGRESS:
-		chan_misdn_log(1, p->bc->port, " --> * IND :\tprogress pid:%d\n",p->bc?p->bc->pid:-1);
+		chan_misdn_log(1, p->bc->port, " --> * IND :\tprogress pid:%d\n", p->bc ? p->bc->pid : -1);
 		misdn_lib_send_event( p->bc, EVENT_PROGRESS);
 		break;
 	case AST_CONTROL_PROCEEDING:
-		chan_misdn_log(1, p->bc->port, " --> * IND :\tproceeding pid:%d\n",p->bc?p->bc->pid:-1);
+		chan_misdn_log(1, p->bc->port, " --> * IND :\tproceeding pid:%d\n", p->bc ? p->bc->pid : -1);
 		misdn_lib_send_event( p->bc, EVENT_PROCEEDING);
 		break;
 	case AST_CONTROL_CONGESTION:
-		chan_misdn_log(1, p->bc->port, " --> * IND :\tcongestion pid:%d\n",p->bc?p->bc->pid:-1);
+		chan_misdn_log(1, p->bc->port, " --> * IND :\tcongestion pid:%d\n", p->bc ? p->bc->pid : -1);
 
-		p->bc->out_cause=42;
+		p->bc->out_cause = AST_CAUSE_SWITCH_CONGESTION;
 		start_bc_tones(p);
 		misdn_lib_send_event( p->bc, EVENT_DISCONNECT);
 
@@ -2351,23 +2256,21 @@ static int misdn_indication(struct ast_channel *ast, int cond, const void *data,
 		}
 		break;
 	case -1 :
-		chan_misdn_log(1, p->bc->port, " --> * IND :\t-1! (stop indication) pid:%d\n",p->bc?p->bc->pid:-1);
-		
+		chan_misdn_log(1, p->bc->port, " --> * IND :\t-1! (stop indication) pid:%d\n", p->bc ? p->bc->pid : -1);
+
 		stop_indicate(p);
 
 		if (p->state == MISDN_CONNECTED) 
 			start_bc_tones(p);
-
 		break;
-
 	case AST_CONTROL_HOLD:
-		chan_misdn_log(1, p->bc->port, " --> *\tHOLD pid:%d\n",p->bc?p->bc->pid:-1);
+		chan_misdn_log(1, p->bc->port, " --> *\tHOLD pid:%d\n", p->bc ? p->bc->pid : -1);
 		break;
 	case AST_CONTROL_UNHOLD:
-		chan_misdn_log(1, p->bc->port, " --> *\tUNHOLD pid:%d\n",p->bc?p->bc->pid:-1);
+		chan_misdn_log(1, p->bc->port, " --> *\tUNHOLD pid:%d\n", p->bc ? p->bc->pid : -1);
 		break;
 	default:
-		chan_misdn_log(1, p->bc->port, " --> * Unknown Indication:%d pid:%d\n",cond,p->bc?p->bc->pid:-1);
+		chan_misdn_log(1, p->bc->port, " --> * Unknown Indication:%d pid:%d\n", cond, p->bc ? p->bc->pid : -1);
 	}
   
 	return 0;
@@ -2376,22 +2279,23 @@ static int misdn_indication(struct ast_channel *ast, int cond, const void *data,
 static int misdn_hangup(struct ast_channel *ast)
 {
 	struct chan_list *p;
-	struct misdn_bchannel *bc=NULL;
+	struct misdn_bchannel *bc = NULL;
+	const char *varcause = NULL;
 
 	if (option_debug)
 		ast_log(LOG_DEBUG, "misdn_hangup(%s)\n", ast->name);
-	
+
 	if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast) ) ) return -1;
-	
+
 	if (!p) {
 		chan_misdn_log(3, 0, "misdn_hangup called, without chan_list obj.\n");
 		return 0 ;
 	}
-	
-	bc=p->bc;
 
-	MISDN_ASTERISK_TECH_PVT(ast)=NULL;
-	p->ast=NULL;
+	bc = p->bc;
+
+	MISDN_ASTERISK_TECH_PVT(ast) = NULL;
+	p->ast = NULL;
 
 	if (ast->_state == AST_STATE_RESERVED || 
 		p->state == MISDN_NOTHING || 
@@ -2402,12 +2306,12 @@ static int misdn_hangup(struct ast_channel *ast)
 		/* between request and call */
 		if (option_debug)
 			ast_log(LOG_DEBUG, "State Reserved (or nothing) => chanIsAvail\n");
-		MISDN_ASTERISK_TECH_PVT(ast)=NULL;
+		MISDN_ASTERISK_TECH_PVT(ast) = NULL;
 		
 		cl_dequeue_chan(&cl_te, p);
 		close(p->pipe[0]);
 		close(p->pipe[1]);
-		free(p);
+		ast_free(p);
 		
 		if (bc)
 			misdn_lib_release(bc);
@@ -2416,122 +2320,116 @@ static int misdn_hangup(struct ast_channel *ast)
 	}
 
 	if (!bc) {
-		ast_log(LOG_WARNING,"Hangup with private but no bc ? state:%s l3id:%x\n", misdn_get_ch_state(p), p->l3id);
+		ast_log(LOG_WARNING, "Hangup with private but no bc ? state:%s l3id:%x\n", misdn_get_ch_state(p), p->l3id);
 		goto CLEAN_CH;
 	}
 
 
-	p->need_hangup=0;
-	p->need_queue_hangup=0;
-	p->need_busy=0;
+	p->need_hangup = 0;
+	p->need_queue_hangup = 0;
+	p->need_busy = 0;
 
 
 	if (!p->bc->nt) 
 		stop_bc_tones(p);
 
-	
-	{
-		const char *varcause=NULL;
-		bc->out_cause=ast->hangupcause?ast->hangupcause:16;
+	bc->out_cause = ast->hangupcause ? ast->hangupcause : AST_CAUSE_NORMAL_CLEARING;
 		
-		if ( (varcause=pbx_builtin_getvar_helper(ast, "HANGUPCAUSE")) ||
-		     (varcause=pbx_builtin_getvar_helper(ast, "PRI_CAUSE"))) {
-			int tmpcause=atoi(varcause);
-			bc->out_cause=tmpcause?tmpcause:16;
-		}
+	if ( (varcause = pbx_builtin_getvar_helper(ast, "HANGUPCAUSE")) ||
+	     (varcause = pbx_builtin_getvar_helper(ast, "PRI_CAUSE"))) {
+		int tmpcause = atoi(varcause);
+		bc->out_cause = tmpcause ? tmpcause : AST_CAUSE_NORMAL_CLEARING;
+	}
     
-		chan_misdn_log(1, bc->port, "* IND : HANGUP\tpid:%d ctx:%s dad:%s oad:%s State:%s\n",p->bc?p->bc->pid:-1, ast->context, ast->exten, ast->cid.cid_num, misdn_get_ch_state(p));
-		chan_misdn_log(3, bc->port, " --> l3id:%x\n",p->l3id);
-		chan_misdn_log(3, bc->port, " --> cause:%d\n",bc->cause);
-		chan_misdn_log(2, bc->port, " --> out_cause:%d\n",bc->out_cause);
-		chan_misdn_log(2, bc->port, " --> state:%s\n", misdn_get_ch_state(p));
-		
-		switch (p->state) {
-		case MISDN_INCOMING_SETUP:
-		case MISDN_CALLING:
-			p->state=MISDN_CLEANING;
-			misdn_lib_send_event( bc, EVENT_RELEASE_COMPLETE);
-			break;
-		case MISDN_HOLDED:
-		case MISDN_DIALING:
-			start_bc_tones(p);
-			hanguptone_indicate(p);
+	chan_misdn_log(1, bc->port, "* IND : HANGUP\tpid:%d ctx:%s dad:%s oad:%s State:%s\n", p->bc ? p->bc->pid : -1, ast->context, ast->exten, ast->cid.cid_num, misdn_get_ch_state(p));
+	chan_misdn_log(3, bc->port, " --> l3id:%x\n", p->l3id);
+	chan_misdn_log(3, bc->port, " --> cause:%d\n", bc->cause);
+	chan_misdn_log(2, bc->port, " --> out_cause:%d\n", bc->out_cause);
+	chan_misdn_log(2, bc->port, " --> state:%s\n", misdn_get_ch_state(p));
+
+	switch (p->state) {
+	case MISDN_INCOMING_SETUP:
+	case MISDN_CALLING:
+		p->state = MISDN_CLEANING;
+		misdn_lib_send_event( bc, EVENT_RELEASE_COMPLETE);
+		break;
+	case MISDN_HOLDED:
+	case MISDN_DIALING:
+		start_bc_tones(p);
+		hanguptone_indicate(p);
 		
-			if (bc->need_disconnect)
-				misdn_lib_send_event( bc, EVENT_DISCONNECT);
-			break;
+		if (bc->need_disconnect)
+			misdn_lib_send_event( bc, EVENT_DISCONNECT);
+		break;
 
-		case MISDN_CALLING_ACKNOWLEDGE:
-			start_bc_tones(p);
-			hanguptone_indicate(p);
+	case MISDN_CALLING_ACKNOWLEDGE:
+		start_bc_tones(p);
+		hanguptone_indicate(p);
 		
-			if (bc->need_disconnect)
-				misdn_lib_send_event( bc, EVENT_DISCONNECT);
-			break;
+		if (bc->need_disconnect)
+			misdn_lib_send_event( bc, EVENT_DISCONNECT);
+		break;
       
-		case MISDN_ALERTING:
-		case MISDN_PROGRESS:
-		case MISDN_PROCEEDING:
-			if (p->originator != ORG_AST) 
-				hanguptone_indicate(p);
+	case MISDN_ALERTING:
+	case MISDN_PROGRESS:
+	case MISDN_PROCEEDING:
+		if (p->originator != ORG_AST) 
+			hanguptone_indicate(p);
       
-			/*p->state=MISDN_CLEANING;*/
-			if (bc->need_disconnect)
-				misdn_lib_send_event( bc, EVENT_DISCONNECT);
-			break;
-		case MISDN_CONNECTED:
-		case MISDN_PRECONNECTED:
-			/*  Alerting or Disconect */
-			if (p->bc->nt) {
-				start_bc_tones(p);
-				hanguptone_indicate(p);
-				p->bc->progress_indicator=8;
-			}
-			if (bc->need_disconnect)
-				misdn_lib_send_event( bc, EVENT_DISCONNECT);
+		/*p->state=MISDN_CLEANING;*/
+		if (bc->need_disconnect)
+			misdn_lib_send_event( bc, EVENT_DISCONNECT);
+		break;
+	case MISDN_CONNECTED:
+	case MISDN_PRECONNECTED:
+		/*  Alerting or Disconect */
+		if (p->bc->nt) {
+			start_bc_tones(p);
+			hanguptone_indicate(p);
+			p->bc->progress_indicator = 8;
+		}
+		if (bc->need_disconnect)
+			misdn_lib_send_event( bc, EVENT_DISCONNECT);
 
-			/*p->state=MISDN_CLEANING;*/
-			break;
-		case MISDN_DISCONNECTED:
-			misdn_lib_send_event( bc, EVENT_RELEASE);
-			p->state=MISDN_CLEANING; /* MISDN_HUNGUP_FROM_AST; */
-			break;
+		/*p->state=MISDN_CLEANING;*/
+		break;
+	case MISDN_DISCONNECTED:
+		misdn_lib_send_event( bc, EVENT_RELEASE);
+		p->state = MISDN_CLEANING; /* MISDN_HUNGUP_FROM_AST; */
+		break;
 
-		case MISDN_RELEASED:
-		case MISDN_CLEANING:
-			p->state=MISDN_CLEANING;
-			break;
+	case MISDN_RELEASED:
+	case MISDN_CLEANING:
+		p->state = MISDN_CLEANING;
+		break;
 
-		case MISDN_BUSY:
-			break;
+	case MISDN_BUSY:
+		break;
       
-		case MISDN_HOLD_DISCONNECT:
-			/* need to send release here */
-			chan_misdn_log(1, bc->port, " --> cause %d\n",bc->cause);
-			chan_misdn_log(1, bc->port, " --> out_cause %d\n",bc->out_cause);
-			
-			bc->out_cause=-1;
-			misdn_lib_send_event(bc,EVENT_RELEASE);
-			p->state=MISDN_CLEANING;
-			break;
-		default:
-			if (bc->nt) {
-				bc->out_cause=-1;
-				misdn_lib_send_event(bc, EVENT_RELEASE);
-				p->state=MISDN_CLEANING; 
-			} else {
-				if (bc->need_disconnect)
-					misdn_lib_send_event(bc, EVENT_DISCONNECT);
-			}
+	case MISDN_HOLD_DISCONNECT:
+		/* need to send release here */
+		chan_misdn_log(1, bc->port, " --> cause %d\n", bc->cause);
+		chan_misdn_log(1, bc->port, " --> out_cause %d\n", bc->out_cause);
+
+		bc->out_cause = -1;
+		misdn_lib_send_event(bc, EVENT_RELEASE);
+		p->state = MISDN_CLEANING;
+		break;
+	default:
+		if (bc->nt) {
+			bc->out_cause = -1;
+			misdn_lib_send_event(bc, EVENT_RELEASE);
+			p->state = MISDN_CLEANING; 
+		} else {
+			if (bc->need_disconnect)
+				misdn_lib_send_event(bc, EVENT_DISCONNECT);
 		}
+	}
 
-		p->state=MISDN_CLEANING;
+	p->state = MISDN_CLEANING;
     
-	}
-	
+	chan_misdn_log(3, bc->port, " --> Channel: %s hanguped new state:%s\n", ast->name, misdn_get_ch_state(p));
 
-	chan_misdn_log(3, bc->port, " --> Channel: %s hanguped new state:%s\n",ast->name,misdn_get_ch_state(p));
-	
 	return 0;
 }
 
@@ -2548,7 +2446,6 @@ static struct ast_frame *process_ast_dsp(struct chan_list *tmp, struct ast_frame
 		return NULL;
 	}
 
- 
  	if (!f || (f->frametype != AST_FRAME_DTMF))
  		return frame;
  
@@ -2611,40 +2508,40 @@ static struct ast_frame *process_ast_dsp(struct chan_list *tmp, struct ast_frame
 }
 
 
-static struct ast_frame  *misdn_read(struct ast_channel *ast)
+static struct ast_frame *misdn_read(struct ast_channel *ast)
 {
 	struct chan_list *tmp;
 	int len;
 	
 	if (!ast) {
-		chan_misdn_log(1,0,"misdn_read called without ast\n");
+		chan_misdn_log(1, 0, "misdn_read called without ast\n");
 		return NULL;
 	}
- 	if (!(tmp=MISDN_ASTERISK_TECH_PVT(ast))) {
-		chan_misdn_log(1,0,"misdn_read called without ast->pvt\n");
+ 	if (!(tmp = MISDN_ASTERISK_TECH_PVT(ast))) {
+		chan_misdn_log(1, 0, "misdn_read called without ast->pvt\n");
 		return NULL;
 	}
 
-	if (!tmp->bc && !(tmp->state==MISDN_HOLDED)) {
-		chan_misdn_log(1,0,"misdn_read called without bc\n");
+	if (!tmp->bc && !(tmp->state == MISDN_HOLDED)) {
+		chan_misdn_log(1, 0, "misdn_read called without bc\n");
 		return NULL;
 	}
 
-	len=read(tmp->pipe[0],tmp->ast_rd_buf,sizeof(tmp->ast_rd_buf));
+	len = read(tmp->pipe[0], tmp->ast_rd_buf, sizeof(tmp->ast_rd_buf));
 
-	if (len<=0) {
+	if (len <= 0) {
 		/* we hangup here, since our pipe is closed */
-		chan_misdn_log(2,tmp->bc->port,"misdn_read: Pipe closed, hanging up\n");
+		chan_misdn_log(2, tmp->bc->port, "misdn_read: Pipe closed, hanging up\n");
 		return NULL;
 	}
 
-	tmp->frame.frametype  = AST_FRAME_VOICE;
+	tmp->frame.frametype = AST_FRAME_VOICE;
 	tmp->frame.subclass = AST_FORMAT_ALAW;
 	tmp->frame.datalen = len;
 	tmp->frame.samples = len;
 	tmp->frame.mallocd = 0;
 	tmp->frame.offset = 0;
-	tmp->frame.delivery= ast_tv(0,0) ;
+	tmp->frame.delivery = ast_tv(0,0);
 	tmp->frame.src = NULL;
 	tmp->frame.data = tmp->ast_rd_buf;
 
@@ -2652,22 +2549,22 @@ static struct ast_frame  *misdn_read(struct ast_channel *ast)
 		if (tmp->faxdetect_timeout) {
 			if (ast_tvzero(tmp->faxdetect_tv)) {
 				tmp->faxdetect_tv = ast_tvnow();
-				chan_misdn_log(2,tmp->bc->port,"faxdetect: starting detection with timeout: %ds ...\n", tmp->faxdetect_timeout);
+				chan_misdn_log(2, tmp->bc->port, "faxdetect: starting detection with timeout: %ds ...\n", tmp->faxdetect_timeout);
 				return process_ast_dsp(tmp, &tmp->frame);
 			} else {
 				struct timeval tv_now = ast_tvnow();
 				int diff = ast_tvdiff_ms(tv_now, tmp->faxdetect_tv);
 				if (diff <= (tmp->faxdetect_timeout * 1000)) {
-					chan_misdn_log(5,tmp->bc->port,"faxdetect: detecting ...\n");
+					chan_misdn_log(5, tmp->bc->port, "faxdetect: detecting ...\n");
 					return process_ast_dsp(tmp, &tmp->frame);
 				} else {
-					chan_misdn_log(2,tmp->bc->port,"faxdetect: stopping detection (time ran out) ...\n");
+					chan_misdn_log(2, tmp->bc->port, "faxdetect: stopping detection (time ran out) ...\n");
 					tmp->faxdetect = 0;
 					return &tmp->frame;
 				}
 			}
 		} else {
-			chan_misdn_log(5,tmp->bc->port,"faxdetect: detecting ... (no timeout)\n");
+			chan_misdn_log(5, tmp->bc->port, "faxdetect: detecting ... (no timeout)\n");
 			return process_ast_dsp(tmp, &tmp->frame);
 		}
 	} else {
@@ -2684,7 +2581,7 @@ static int misdn_write(struct ast_channel *ast, struct ast_frame *frame)
 	struct chan_list *ch;
 	int i  = 0;
 	
-	if (!ast || ! (ch=MISDN_ASTERISK_TECH_PVT(ast)) ) return -1;
+	if (!ast || ! (ch = MISDN_ASTERISK_TECH_PVT(ast)) ) return -1;
 
 	if (ch->state == MISDN_HOLDED) {
 		chan_misdn_log(7, 0, "misdn_write: Returning because holded\n");
@@ -2702,26 +2599,26 @@ static int misdn_write(struct ast_channel *ast, struct ast_frame *frame)
 	}
 
 
-	if ( !frame->subclass) {
+	if (!frame->subclass) {
 		chan_misdn_log(4, ch->bc->port, "misdn_write: * prods us\n");
 		return 0;
 	}
 	
-	if ( !(frame->subclass & prefformat)) {
+	if (!(frame->subclass & prefformat)) {
 		
 		chan_misdn_log(-1, ch->bc->port, "Got Unsupported Frame with Format:%d\n", frame->subclass);
 		return 0;
 	}
 	
 
-	if ( !frame->samples ) {
+	if (!frame->samples ) {
 		chan_misdn_log(4, ch->bc->port, "misdn_write: zero write\n");
 		
 		if (!strcmp(frame->src,"ast_prod")) {
 			chan_misdn_log(1, ch->bc->port, "misdn_write: state (%s) prodded.\n", misdn_get_ch_state(ch));
 
 			if (ch->ts) {
-				chan_misdn_log(4,ch->bc->port,"Starting Playtones\n");
+				chan_misdn_log(4, ch->bc->port, "Starting Playtones\n");
 				misdn_lib_tone_generator_start(ch->bc);
 			}
 			return 0;
@@ -2737,40 +2634,39 @@ static int misdn_write(struct ast_channel *ast, struct ast_frame *frame)
 	
 #ifdef MISDN_DEBUG
 	{
-		int i, max=5>frame->samples?frame->samples:5;
-		
-		printf("write2mISDN %p %d bytes: ", p, frame->samples);
-		
-		for (i=0; i<  max ; i++) printf("%2.2x ",((char*) frame->data)[i]);
-		printf ("\n");
+		int i, max = 5 > frame->samples ? frame->samples : 5;
+
+		ast_log(LOG_DEBUG, "write2mISDN %p %d bytes: ", p, frame->samples);
+
+		for (i = 0; i < max ; i++)
+			ast_log(LOG_DEBUG, "%2.2x ", ((char*) frame->data)[i]);
 	}
 #endif
 
-
 	switch (ch->bc->bc_state) {
-		case BCHAN_ACTIVATED:
-		case BCHAN_BRIDGED:
-			break;
-		default:
+	case BCHAN_ACTIVATED:
+	case BCHAN_BRIDGED:
+		break;
+	default:
 		if (!ch->dropped_frame_cnt)
-			chan_misdn_log(5, ch->bc->port, "BC not active (nor bridged) droping: %d frames addr:%x exten:%s cid:%s ch->state:%s bc_state:%d l3id:%x\n",frame->samples,ch->bc->addr, ast->exten, ast->cid.cid_num,misdn_get_ch_state( ch), ch->bc->bc_state, ch->bc->l3_id);
+			chan_misdn_log(5, ch->bc->port, "BC not active (nor bridged) droping: %d frames addr:%x exten:%s cid:%s ch->state:%s bc_state:%d l3id:%x\n", frame->samples, ch->bc->addr, ast->exten, ast->cid.cid_num, misdn_get_ch_state( ch), ch->bc->bc_state, ch->bc->l3_id);
 		
 		ch->dropped_frame_cnt++;
 		if (ch->dropped_frame_cnt > 100) {
-			ch->dropped_frame_cnt=0;
-			chan_misdn_log(5, ch->bc->port, "BC not active (nor bridged) droping: %d frames addr:%x  dropped > 100 frames!\n",frame->samples,ch->bc->addr);
+			ch->dropped_frame_cnt = 0;
+			chan_misdn_log(5, ch->bc->port, "BC not active (nor bridged) droping: %d frames addr:%x  dropped > 100 frames!\n", frame->samples, ch->bc->addr);
 
 		}
 
 		return 0;
 	}
 
-	chan_misdn_log(9, ch->bc->port, "Sending :%d bytes 2 MISDN\n",frame->samples);
+	chan_misdn_log(9, ch->bc->port, "Sending :%d bytes 2 MISDN\n", frame->samples);
 	if ( !ch->bc->nojitter && misdn_cap_is_speech(ch->bc->capability) ) {
 		/* Buffered Transmit (triggert by read from isdn side)*/
-		if (misdn_jb_fill(ch->jb,frame->data,frame->samples) < 0) {
+		if (misdn_jb_fill(ch->jb, frame->data, frame->samples) < 0) {
 			if (ch->bc->active)
-				cb_log(0,ch->bc->port,"Misdn Jitterbuffer Overflow.\n");
+				cb_log(0, ch->bc->port, "Misdn Jitterbuffer Overflow.\n");
 		}
 		
 	} else {
@@ -2778,8 +2674,6 @@ static int misdn_write(struct ast_channel *ast, struct ast_frame *frame)
 		i=misdn_lib_tx2misdn_frm(ch->bc, frame->data, frame->samples);
 	}
 
-	
-	
 	return 0;
 }
 
@@ -2793,79 +2687,77 @@ static enum ast_bridge_result  misdn_bridge (struct ast_channel *c0,
 				      int timeoutms)
 
 {
-	struct chan_list *ch1,*ch2;
+	struct chan_list *ch1, *ch2;
 	struct ast_channel *carr[2], *who;
-	int to=-1;
+	int to = -1;
 	struct ast_frame *f;
+	int p1_b, p2_b;
+	int bridging;
   
-	ch1=get_chan_by_ast(c0);
-	ch2=get_chan_by_ast(c1);
+	ch1 = get_chan_by_ast(c0);
+	ch2 = get_chan_by_ast(c1);
 
-	carr[0]=c0;
-	carr[1]=c1;
+	carr[0] = c0;
+	carr[1] = c1;
   
-	if (ch1 && ch2 ) ;
-	else
+	if (!(ch1 && ch2))
 		return -1;
 
-	int p1_b, p2_b;
+	misdn_cfg_get(ch1->bc->port, MISDN_CFG_BRIDGING, &p1_b, sizeof(p1_b));
+	misdn_cfg_get(ch2->bc->port, MISDN_CFG_BRIDGING, &p2_b, sizeof(p2_b));
 
-	misdn_cfg_get(ch1->bc->port, MISDN_CFG_BRIDGING, &p1_b, sizeof(int));
-	misdn_cfg_get(ch2->bc->port, MISDN_CFG_BRIDGING, &p2_b, sizeof(int));
-	
-	if ( ! p1_b || ! p2_b) {
+	if (! p1_b || ! p2_b) {
 		ast_log(LOG_NOTICE, "Falling back to Asterisk bridging\n");
 		return AST_BRIDGE_FAILED;
 	}
 
-	int bridging;
-	misdn_cfg_get( 0, MISDN_GEN_BRIDGING, &bridging, sizeof(int));
+	misdn_cfg_get(0, MISDN_GEN_BRIDGING, &bridging, sizeof(bridging));
 	if (bridging) {
 		/* trying to make a mISDN_dsp conference */
-		chan_misdn_log(1, ch1->bc->port, "I SEND: Making conference with Number:%d\n", ch1->bc->pid +1);
-		misdn_lib_bridge(ch1->bc,ch2->bc);
+		chan_misdn_log(1, ch1->bc->port, "I SEND: Making conference with Number:%d\n", ch1->bc->pid + 1);
+		misdn_lib_bridge(ch1->bc, ch2->bc);
 	}
-	
+
 	if (option_verbose > 2) 
 		ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
 
 	chan_misdn_log(1, ch1->bc->port, "* Making Native Bridge between %s and %s\n", ch1->bc->oad, ch2->bc->oad);
  
-	if (! (flags&AST_BRIDGE_DTMF_CHANNEL_0) )
-		ch1->ignore_dtmf=1;
+	if (! (flags & AST_BRIDGE_DTMF_CHANNEL_0) )
+		ch1->ignore_dtmf = 1;
 
-	if (! (flags&AST_BRIDGE_DTMF_CHANNEL_1) )
-		ch2->ignore_dtmf=1;
+	if (! (flags & AST_BRIDGE_DTMF_CHANNEL_1) )
+		ch2->ignore_dtmf = 1;
 
-	while(1) {
-		to=-1;
+	for (;/*ever*/;) {
+		to = -1;
 		who = ast_waitfor_n(carr, 2, &to);
 
 		if (!who) {
-			ast_log(LOG_NOTICE,"misdn_bridge: empty read, breaking out\n");
+			ast_log(LOG_NOTICE, "misdn_bridge: empty read, breaking out\n");
 			break;
 		}
 		f = ast_read(who);
-    
+
 		if (!f || f->frametype == AST_FRAME_CONTROL) {
 			/* got hangup .. */
 
 			if (!f) 
-				chan_misdn_log(4,ch1->bc->port,"Read Null Frame\n");
+				chan_misdn_log(4, ch1->bc->port, "Read Null Frame\n");
 			else
-				chan_misdn_log(4,ch1->bc->port,"Read Frame Controll class:%d\n",f->subclass);
-			
-			*fo=f;
-			*rc=who;
-      
+				chan_misdn_log(4, ch1->bc->port, "Read Frame Controll class:%d\n", f->subclass);
+
+			*fo = f;
+			*rc = who;
+
 			break;
 		}
 		
 		if ( f->frametype == AST_FRAME_DTMF ) {
-			chan_misdn_log(1,0,"Read DTMF %d from %s\n",f->subclass, who->exten);
+			chan_misdn_log(1, 0, "Read DTMF %d from %s\n", f->subclass, who->exten);
 
-			*fo=f;
-			*rc=who;
+			*fo = f;
+			*rc = who;
 			break;
 		}
 	
@@ -2878,19 +2770,17 @@ static enum ast_bridge_result  misdn_bridge (struct ast_channel *c0,
 #endif
 
 		if (who == c0) {
-			ast_write(c1,f);
+			ast_write(c1, f);
 		}
 		else {
-			ast_write(c0,f);
+			ast_write(c0, f);
 		}
-    
 	}
-	
-	chan_misdn_log(1, ch1->bc->port, "I SEND: Splitting conference with Number:%d\n", ch1->bc->pid +1);
-	
-	misdn_lib_split_bridge(ch1->bc,ch2->bc);
-	
-	
+
+	chan_misdn_log(1, ch1->bc->port, "I SEND: Splitting conference with Number:%d\n", ch1->bc->pid + 1);
+
+	misdn_lib_split_bridge(ch1->bc, ch2->bc);
+
 	return AST_BRIDGE_COMPLETE;
 }
 
@@ -2898,31 +2788,31 @@ static enum ast_bridge_result  misdn_bridge (struct ast_channel *c0,
 
 static int dialtone_indicate(struct chan_list *cl)
 {
-	const struct ind_tone_zone_sound *ts= NULL;
-	struct ast_channel *ast=cl->ast;
+	const struct ind_tone_zone_sound *ts = NULL;
+	struct ast_channel *ast = cl->ast;
+	int nd = 0;
 
 	if (!ast) {
-		chan_misdn_log(0,cl->bc->port,"No Ast in dialtone_indicate\n");
+		chan_misdn_log(0, cl->bc->port, "No Ast in dialtone_indicate\n");
 		return -1;
 	}
 
-	int nd=0;
-	misdn_cfg_get( cl->bc->port, MISDN_CFG_NODIALTONE, &nd, sizeof(nd));
+	misdn_cfg_get(cl->bc->port, MISDN_CFG_NODIALTONE, &nd, sizeof(nd));
 
 	if (nd) {
-		chan_misdn_log(1,cl->bc->port,"Not sending Dialtone, because config wants it\n");
+		chan_misdn_log(1, cl->bc->port, "Not sending Dialtone, because config wants it\n");
 		return 0;
 	}
 	
-	chan_misdn_log(3,cl->bc->port," --> Dial\n");
-	ts=ast_get_indication_tone(ast->zone,"dial");
-	cl->ts=ts;	
+	chan_misdn_log(3, cl->bc->port, " --> Dial\n");
+	ts = ast_get_indication_tone(ast->zone, "dial");
+	cl->ts = ts;	
 	
 	if (ts) {
-		cl->notxtone=0;
-		cl->norxtone=0;
+		cl->notxtone = 0;
+		cl->norxtone = 0;
 		/* This prods us in misdn_write */
-		ast_playtones_start(ast,0, ts->data, 0);
+		ast_playtones_start(ast, 0, ts->data, 0);
 	}
 
 	return 0;
@@ -2930,26 +2820,26 @@ static int dialtone_indicate(struct chan_list *cl)
 
 static int hanguptone_indicate(struct chan_list *cl)
 {
-	misdn_lib_send_tone(cl->bc,TONE_HANGUP);
+	misdn_lib_send_tone(cl->bc, TONE_HANGUP);
 	return 0;
 }
 
 static int stop_indicate(struct chan_list *cl)
 {
-	struct ast_channel *ast=cl->ast;
+	struct ast_channel *ast = cl->ast;
 
 	if (!ast) {
-		chan_misdn_log(0,cl->bc->port,"No Ast in stop_indicate\n");
+		chan_misdn_log(0, cl->bc->port, "No Ast in stop_indicate\n");
 		return -1;
 	}
 
-	chan_misdn_log(3,cl->bc->port," --> None\n");
+	chan_misdn_log(3, cl->bc->port, " --> None\n");
 	misdn_lib_tone_generator_stop(cl->bc);
 	ast_playtones_stop(ast);
 
-	cl->ts=NULL;
+	cl->ts = NULL;
 	/*ast_deactivate_generator(ast);*/
-	
+
 	return 0;
 }
 
@@ -2957,8 +2847,8 @@ static int stop_indicate(struct chan_list *cl)
 static int start_bc_tones(struct chan_list* cl)
 {
 	misdn_lib_tone_generator_stop(cl->bc);
-	cl->notxtone=0;
-	cl->norxtone=0;
+	cl->notxtone = 0;
+	cl->norxtone = 0;
 	return 0;
 }
 
@@ -2966,8 +2856,8 @@ static int stop_bc_tones(struct chan_list *cl)
 {
 	if (!cl) return -1;
 
-	cl->notxtone=1;
-	cl->norxtone=1;
+	cl->notxtone = 1;
+	cl->norxtone = 1;
 	
 	return 0;
 }
@@ -2975,85 +2865,77 @@ static int stop_bc_tones(struct chan_list *cl)
 
 static struct chan_list *init_chan_list(int orig)
 {
-	struct chan_list *cl=malloc(sizeof(struct chan_list));
-	
+	struct chan_list *cl;
+
+	cl = ast_calloc(1, sizeof(*cl));
+
 	if (!cl) {
 		chan_misdn_log(-1, 0, "misdn_request: malloc failed!");
 		return NULL;
 	}
 	
-	memset(cl,0,sizeof(struct chan_list));
+	cl->originator = orig;
+	cl->need_queue_hangup = 1;
+	cl->need_hangup = 1;
+	cl->need_busy = 1;
+	cl->overlap_dial_task = -1;
 
-	cl->originator=orig;
-	cl->need_queue_hangup=1;
-	cl->need_hangup=1;
-	cl->need_busy=1;
-	cl->overlap_dial_task=-1;
-	
 	return cl;
-	
 }
 
 static struct ast_channel *misdn_request(const char *type, int format, void *data, int *cause)
-
 {
 	struct ast_channel *tmp = NULL;
-	char group[BUFFERSIZE+1]="";
+	char group[BUFFERSIZE + 1] = "";
 	char buf[128];
-	char buf2[128], *ext=NULL, *port_str;
-	char *tokb=NULL, *p=NULL;
-	int channel=0, port=0;
+	char *buf2 = ast_strdupa(data), *ext = NULL, *port_str;
+	char *tokb = NULL, *p = NULL;
+	int channel = 0, port = 0;
 	struct misdn_bchannel *newbc = NULL;
-	int dec=0;
-	
-	struct chan_list *cl=init_chan_list(ORG_AST);
-	
-	sprintf(buf,"%s/%s",misdn_type,(char*)data);
-	ast_copy_string(buf2,data, 128);
-	
-	port_str=strtok_r(buf2,"/", &tokb);
+	int dec = 0;
+
+	struct chan_list *cl = init_chan_list(ORG_AST);
+
+	snprintf(buf, sizeof(buf), "%s/%s", misdn_type, (char*)data);
 
-	ext=strtok_r(NULL,"/", &tokb);
+	port_str = strtok_r(buf2, "/", &tokb);
+
+	ext = strtok_r(NULL, "/", &tokb);
 
 	if (port_str) {
-		if (port_str[0]=='g' && port_str[1]==':' ) {
+		if (port_str[0] == 'g' && port_str[1] == ':' ) {
 			/* We make a group call lets checkout which ports are in my group */
 			port_str += 2;
-			strncpy(group, port_str, BUFFERSIZE);
-			group[127] = 0;
-			chan_misdn_log(2, 0, " --> Group Call group: %s\n",group);
-		} 
-		else if ((p = strchr(port_str, ':'))) {
+			ast_copy_string(group, port_str, sizeof(group));
+			chan_misdn_log(2, 0, " --> Group Call group: %s\n", group);
+		} else if ((p = strchr(port_str, ':'))) {
 			/* we have a preselected channel */
 			*p = 0;
 			channel = atoi(++p);
 			port = atoi(port_str);
 			chan_misdn_log(2, port, " --> Call on preselected Channel (%d).\n", channel);
-		}
-		else {
+		} else {
 			port = atoi(port_str);
 		}
 	} else {
-		ast_log(LOG_WARNING, " --> ! IND : CALL dad:%s WITHOUT PORT/Group, check extension.conf\n",ext);
+		ast_log(LOG_WARNING, " --> ! IND : CALL dad:%s WITHOUT PORT/Group, check extensions.conf\n", ext);
 		return NULL;
 	}
 
 	if (misdn_cfg_is_group_method(group, METHOD_STANDARD_DEC)) {
 		chan_misdn_log(4, port, " --> STARTING STANDARDDEC...\n");
-		dec=1;
+		dec = 1;
 	}
 
 	if (!ast_strlen_zero(group)) {
-	
-		char cfg_group[BUFFERSIZE+1];
+		char cfg_group[BUFFERSIZE + 1];
 		struct robin_list *rr = NULL;
 
 		if (misdn_cfg_is_group_method(group, METHOD_ROUND_ROBIN)) {
 			chan_misdn_log(4, port, " --> STARTING ROUND ROBIN...\n");
 			rr = get_robin_position(group);
 		}
-		
-			
+
 		if (rr) {
 			int robin_channel = rr->channel;
 			int port_start;
@@ -3078,24 +2960,23 @@ static struct ast_channel *misdn_request(const char *type, int format, void *dat
 						next_chan = 0;
 					}
 
-					misdn_cfg_get(port, MISDN_CFG_GROUPNAME, cfg_group, BUFFERSIZE);
-					
+					misdn_cfg_get(port, MISDN_CFG_GROUPNAME, cfg_group, sizeof(cfg_group));
+
 					if (!strcasecmp(cfg_group, group)) {
 						int port_up;
 						int check;
-						misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(int));
+						misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(check));
 						port_up = misdn_lib_port_up(port, check);
 
 						if (check && !port_up) 
-							chan_misdn_log(1,port,"L1 is not Up on this Port\n");
+							chan_misdn_log(1, port, "L1 is not Up on this Port\n");
 						
-						if (check && port_up<0) {
-							ast_log(LOG_WARNING,"This port (%d) is blocked\n", port);
+						if (check && port_up < 0) {
+							ast_log(LOG_WARNING, "This port (%d) is blocked\n", port);
 						}
-						
-						
-						if ( port_up>0 )	{
-							newbc = misdn_lib_get_free_bc(port, robin_channel,0, 0);
+
+						if (port_up > 0)	{
+							newbc = misdn_lib_get_free_bc(port, robin_channel, 0, 0);
 							if (newbc) {
 								chan_misdn_log(4, port, " Success! Found port:%d channel:%d\n", newbc->port, newbc->channel);
 								if (port_up)
@@ -3110,21 +2991,21 @@ static struct ast_channel *misdn_request(const char *type, int format, void *dat
 			} while (!newbc && robin_channel != rr->channel);
 			
 		} else {		
-			for (port=misdn_cfg_get_next_port(0); port > 0;
-				 port=misdn_cfg_get_next_port(port)) {
-				
-				misdn_cfg_get( port, MISDN_CFG_GROUPNAME, cfg_group, BUFFERSIZE);
+			for (port = misdn_cfg_get_next_port(0); port > 0;
+				 port = misdn_cfg_get_next_port(port)) {
+
+				misdn_cfg_get(port, MISDN_CFG_GROUPNAME, cfg_group, sizeof(cfg_group));
 
-				chan_misdn_log(3,port, "Group [%s] Port [%d]\n", group, port);
+				chan_misdn_log(3, port, "Group [%s] Port [%d]\n", group, port);
 				if (!strcasecmp(cfg_group, group)) {
 					int port_up;
 					int check;
-					misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(int));
+					misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(check));
 					port_up = misdn_lib_port_up(port, check);
-					
+
 					chan_misdn_log(4, port, "portup:%d\n", port_up);
-					
-					if ( port_up>0 ) {
+
+					if (port_up > 0) {
 						newbc = misdn_lib_get_free_bc(port, 0, 0, dec);
 						if (newbc)
 							break;
@@ -3144,21 +3025,21 @@ static struct ast_channel *misdn_request(const char *type, int format, void *dat
 		}
 	} else { /* 'Normal' Port dial * Port dial */
 		if (channel)
-			chan_misdn_log(1, port," --> preselected_channel: %d\n",channel);
+			chan_misdn_log(1, port, " --> preselected_channel: %d\n", channel);
 		newbc = misdn_lib_get_free_bc(port, channel, 0, dec);
 
 		if (!newbc) {
-			ast_log(LOG_WARNING, "Could not create channel on port:%d with extensions:%s\n",port,ext);
+			ast_log(LOG_WARNING, "Could not create channel on port:%d with extensions:%s\n", port, ext);
 			return NULL;
 		}
 	}
 	
 
 	/* create ast_channel and link all the objects together */
-	cl->bc=newbc;
+	cl->bc = newbc;
 	
 	tmp = misdn_new(cl, AST_STATE_RESERVED, ext, NULL, format, port, channel);
-	cl->ast=tmp;
+	cl->ast = tmp;
 	
 	/* register chan in local list */
 	cl_queue_chan(&cl_te, cl) ;
@@ -3167,18 +3048,18 @@ static struct ast_channel *misdn_request(const char *type, int format, void *dat
 	read_config(cl, ORG_AST);
 
 	/* important */
-	cl->need_hangup=0;
+	cl->need_hangup = 0;
 	
 	return tmp;
 }
 
 
-static int misdn_send_text (struct ast_channel *chan, const char *text)
+static int misdn_send_text(struct ast_channel *chan, const char *text)
 {
-	struct chan_list *tmp=chan->tech_pvt;
+	struct chan_list *tmp = chan->tech_pvt;
 	
 	if (tmp && tmp->bc) {
-		ast_copy_string(tmp->bc->display,text,sizeof(tmp->bc->display));
+		ast_copy_string(tmp->bc->display, text, sizeof(tmp->bc->display));
 		misdn_lib_send_event(tmp->bc, EVENT_INFORMATION);
 	} else {
 		ast_log(LOG_WARNING, "No chan_list but send_text request?\n");
@@ -3189,84 +3070,87 @@ static int misdn_send_text (struct ast_channel *chan, const char *text)
 }
 
 static struct ast_channel_tech misdn_tech = {
-	.type="mISDN",
-	.description="Channel driver for mISDN Support (Bri/Pri)",
-	.capabilities= AST_FORMAT_ALAW ,
-	.requester=misdn_request,
-	.send_digit_begin=misdn_digit_begin,
-	.send_digit_end=misdn_digit_end,
-	.call=misdn_call,
-	.bridge=misdn_bridge, 
-	.hangup=misdn_hangup,
-	.answer=misdn_answer,
-	.read=misdn_read,
-	.write=misdn_write,
-	.indicate=misdn_indication,
-	.fixup=misdn_fixup,
-	.send_text=misdn_send_text,
-	.properties=0
+	.type = "mISDN",
+	.description = "Channel driver for mISDN Support (Bri/Pri)",
+	.capabilities = AST_FORMAT_ALAW ,
+	.requester = misdn_request,
+	.send_digit_begin = misdn_digit_begin,
+	.send_digit_end = misdn_digit_end,
+	.call = misdn_call,
+	.bridge = misdn_bridge, 
+	.hangup = misdn_hangup,
+	.answer = misdn_answer,
+	.read = misdn_read,
+	.write = misdn_write,
+	.indicate = misdn_indication,
+	.fixup = misdn_fixup,
+	.send_text = misdn_send_text,
+	.properties = 0
 };
 
 static struct ast_channel_tech misdn_tech_wo_bridge = {
-	.type="mISDN",
-	.description="Channel driver for mISDN Support (Bri/Pri)",
-	.capabilities=AST_FORMAT_ALAW ,
-	.requester=misdn_request,
-	.send_digit_begin=misdn_digit_begin,
-	.send_digit_end=misdn_digit_end,
-	.call=misdn_call,
-	.hangup=misdn_hangup,
-	.answer=misdn_answer,
-	.read=misdn_read,
-	.write=misdn_write,
-	.indicate=misdn_indication,
-	.fixup=misdn_fixup,
-	.send_text=misdn_send_text,
-	.properties=0
+	.type = "mISDN",
+	.description = "Channel driver for mISDN Support (Bri/Pri)",
+	.capabilities = AST_FORMAT_ALAW ,
+	.requester = misdn_request,
+	.send_digit_begin = misdn_digit_begin,
+	.send_digit_end = misdn_digit_end,
+	.call = misdn_call,
+	.hangup = misdn_hangup,
+	.answer = misdn_answer,
+	.read = misdn_read,
+	.write = misdn_write,
+	.indicate = misdn_indication,
+	.fixup = misdn_fixup,
+	.send_text = misdn_send_text,
+	.properties = 0
 };
 
 
-static int glob_channel=0;
+static int glob_channel = 0;
 
 static void update_name(struct ast_channel *tmp, int port, int c) 
 {
-	int chan_offset=0;
+	int chan_offset = 0;
 	int tmp_port = misdn_cfg_get_next_port(0);
-	for (; tmp_port > 0; tmp_port=misdn_cfg_get_next_port(tmp_port)) {
-	if (tmp_port == port) break;
-		chan_offset+=misdn_lib_port_is_pri(tmp_port)?30:2;	
+	for (; tmp_port > 0; tmp_port = misdn_cfg_get_next_port(tmp_port)) {
+		if (tmp_port == port)
+			break;
+		chan_offset += misdn_lib_port_is_pri(tmp_port) ? 30 : 2;	
 	}
-	if (c<0) c=0;
+	if (c < 0)
+		c = 0;
 
 	ast_string_field_build(tmp, name, "%s/%d-u%d",
 				 misdn_type, chan_offset+c, glob_channel++);
 
-	chan_misdn_log(3,port," --> updating channel name to [%s]\n",tmp->name);
-	
+	chan_misdn_log(3 , port, " --> updating channel name to [%s]\n", tmp->name);
 }
 
 static struct ast_channel *misdn_new(struct chan_list *chlist, int state,  char *exten, char *callerid, int format, int port, int c)
 {
 	struct ast_channel *tmp;
 	char *cid_name = 0, *cid_num = 0;
-	int chan_offset=0;
+	int chan_offset = 0;
 	int tmp_port = misdn_cfg_get_next_port(0);
+	int bridging;
 
-	for (; tmp_port > 0; tmp_port=misdn_cfg_get_next_port(tmp_port)) {
-	if (tmp_port == port) break;
-		chan_offset+=misdn_lib_port_is_pri(tmp_port)?30:2;	
+	for (; tmp_port > 0; tmp_port = misdn_cfg_get_next_port(tmp_port)) {
+		if (tmp_port == port)
+			break;
+		chan_offset += misdn_lib_port_is_pri(tmp_port) ? 30 : 2;	
 	}
-	if (c<0) c=0;
+	if (c < 0)
+		c = 0;
 
-	
 	if (callerid) 
 		ast_callerid_parse(callerid, &cid_name, &cid_num);
 
 	tmp = ast_channel_alloc(1, state, cid_num, cid_name, "", exten, "", 0, "%s/%d-u%d", misdn_type, chan_offset + c, glob_channel++);
-	
+
 	if (tmp) {
-		chan_misdn_log(2, 0, " --> * NEW CHANNEL dad:%s oad:%s\n",exten,callerid);
-		
+		chan_misdn_log(2, 0, " --> * NEW CHANNEL dad:%s oad:%s\n", exten, callerid);
+
 		tmp->nativeformats = prefformat;
 
 		tmp->readformat = format;
@@ -3275,24 +3159,23 @@ static struct ast_channel *misdn_new(struct chan_list *chlist, int state,  char
 		tmp->rawwriteformat = format;
     
 		tmp->tech_pvt = chlist;
-		
-		int bridging;
-		misdn_cfg_get( 0, MISDN_GEN_BRIDGING, &bridging, sizeof(int));
-		
+
+		misdn_cfg_get(0, MISDN_GEN_BRIDGING, &bridging, sizeof(bridging));
+
 		if (bridging)
 			tmp->tech = &misdn_tech;
 		else
 			tmp->tech = &misdn_tech_wo_bridge;
-		
+
 		tmp->writeformat = format;
 		tmp->readformat = format;
 		tmp->priority=1;
-		
+
 		if (exten) 
-			ast_copy_string(tmp->exten, exten,  sizeof(tmp->exten));
+			ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
 		else
-			chan_misdn_log(1,0,"misdn_new: no exten given.\n");
-		
+			chan_misdn_log(1, 0, "misdn_new: no exten given.\n");
+
 		if (callerid) {
 			char *cid_name, *cid_num;
       
@@ -3304,14 +3187,11 @@ static struct ast_channel *misdn_new(struct chan_list *chlist, int state,  char
 			tmp->cid.cid_name = ast_strdup(cid_name);
 		}
 
-		{
-			if (pipe(chlist->pipe)<0)
-				perror("Pipe failed\n");
-			
-			tmp->fds[0]=chlist->pipe[0];
-			
-		}
-		
+		if (pipe(chlist->pipe) < 0)
+			ast_log(LOG_ERROR, "Pipe failed\n");
+
+		tmp->fds[0] = chlist->pipe[0];
+
 		if (state == AST_STATE_RING)
 			tmp->rings = 1;
 		else
@@ -3319,7 +3199,7 @@ static struct ast_channel *misdn_new(struct chan_list *chlist, int state,  char
 		
 		
 	} else {
-		chan_misdn_log(-1,0,"Unable to allocate channel structure\n");
+		chan_misdn_log(-1, 0, "Unable to allocate channel structure\n");
 	}
 	
 	return tmp;
@@ -3327,51 +3207,50 @@ static struct ast_channel *misdn_new(struct chan_list *chlist, int state,  char
 
 static struct chan_list *find_chan_by_bc(struct chan_list *list, struct misdn_bchannel *bc)
 {
-	struct chan_list *help=list;
-	for (;help; help=help->next) {
+	struct chan_list *help = list;
+	for (; help; help = help->next) {
 		if (help->bc == bc) return help;
 	}
-  
-	chan_misdn_log(6, bc->port, "$$$ find_chan: No channel found for oad:%s dad:%s\n",bc->oad,bc->dad);
-  
+
+	chan_misdn_log(6, bc->port, "$$$ find_chan: No channel found for oad:%s dad:%s\n", bc->oad, bc->dad);
+
 	return NULL;
 }
 
 static struct chan_list *find_chan_by_pid(struct chan_list *list, int pid)
 {
-	struct chan_list *help=list;
-	for (;help; help=help->next) {
+	struct chan_list *help = list;
+	for (; help; help = help->next) {
 		if ( help->bc && (help->bc->pid == pid) ) return help;
 	}
-  
-	chan_misdn_log(6, 0, "$$$ find_chan: No channel found for pid:%d\n",pid);
-  
+
+	chan_misdn_log(6, 0, "$$$ find_chan: No channel found for pid:%d\n", pid);
+
 	return NULL;
 }
 
 static struct chan_list *find_holded(struct chan_list *list, struct misdn_bchannel *bc)
 {
-	struct chan_list *help=list;
-	
-	chan_misdn_log(6, bc->port, "$$$ find_holded: channel:%d oad:%s dad:%s\n",bc->channel, bc->oad,bc->dad);
-	for (;help; help=help->next) {
-		chan_misdn_log(4, bc->port, "$$$ find_holded: --> holded:%d channel:%d\n",help->state==MISDN_HOLDED, help->hold_info.channel);
+	struct chan_list *help = list;
+
+	chan_misdn_log(6, bc->port, "$$$ find_holded: channel:%d oad:%s dad:%s\n", bc->channel, bc->oad, bc->dad);
+	for (;help; help = help->next) {
+		chan_misdn_log(4, bc->port, "$$$ find_holded: --> holded:%d channel:%d\n", help->state==MISDN_HOLDED, help->hold_info.channel);
 		if ( 	(help->state == MISDN_HOLDED) && 
 			(help->hold_info.port == bc->port) ) 
 			return help;
-	}	
-	chan_misdn_log(6, bc->port, "$$$ find_chan: No channel found for oad:%s dad:%s\n",bc->oad,bc->dad);
-  
+	}
+	chan_misdn_log(6, bc->port, "$$$ find_chan: No channel found for oad:%s dad:%s\n", bc->oad, bc->dad);
+
 	return NULL;
 }
 
 
 static struct chan_list *find_holded_l3(struct chan_list *list, unsigned long l3_id, int w) 
-
 {
-	struct chan_list *help=list;
+	struct chan_list *help = list;
 
-	for (;help; help=help->next) {
+	for (; help; help = help->next) {
 		if ( (help->state == MISDN_HOLDED) &&
 			 (help->l3id == l3_id)   
 			) 
@@ -3383,29 +3262,29 @@ static struct chan_list *find_holded_l3(struct chan_list *list, unsigned long l3
 
 static void cl_queue_chan(struct chan_list **list, struct chan_list *chan)
 {
-	chan_misdn_log(4, chan->bc? chan->bc->port : 0, "* Queuing chan %p\n",chan);
+	chan_misdn_log(4, chan->bc ? chan->bc->port : 0, "* Queuing chan %p\n", chan);
   
 	ast_mutex_lock(&cl_te_lock);
 	if (!*list) {
 		*list = chan;
 	} else {
-		struct chan_list *help=*list;
-		for (;help->next; help=help->next); 
-		help->next=chan;
+		struct chan_list *help = *list;
+		for (; help->next; help = help->next); 
+		help->next = chan;
 	}
-	chan->next=NULL;
+	chan->next = NULL;
 	ast_mutex_unlock(&cl_te_lock);
 }
 
 static void cl_dequeue_chan(struct chan_list **list, struct chan_list *chan) 
 {
+	struct chan_list *help;
+
 	if (chan->dsp) 
 		ast_dsp_free(chan->dsp);
 	if (chan->trans)
 		ast_translator_free_path(chan->trans);
 
-	
-
 	ast_mutex_lock(&cl_te_lock);
 	if (!*list) {
 		ast_mutex_unlock(&cl_te_lock);
@@ -3413,19 +3292,16 @@ static void cl_dequeue_chan(struct chan_list **list, struct chan_list *chan)
 	}
   
 	if (*list == chan) {
-		*list=(*list)->next;
+		*list = (*list)->next;
 		ast_mutex_unlock(&cl_te_lock);
-		return ;
+		return;
 	}
   
-	{
-		struct chan_list *help=*list;
-		for (;help->next; help=help->next) {
-			if (help->next == chan) {
-				help->next=help->next->next;
-				ast_mutex_unlock(&cl_te_lock);
-				return;
-			}
+	for (help = *list; help->next; help = help->next) {
+		if (help->next == chan) {
+			help->next = help->next->next;
+			ast_mutex_unlock(&cl_te_lock);
+			return;
 		}
 	}
 	
@@ -3437,145 +3313,138 @@ static void cl_dequeue_chan(struct chan_list **list, struct chan_list *chan)
 
 int pbx_start_chan(struct chan_list *ch)
 {
-	int ret=ast_pbx_start(ch->ast);	
+	int ret = ast_pbx_start(ch->ast);	
 
-	if (ret>=0) 
-		ch->need_hangup=0;
+	if (ret >= 0) 
+		ch->need_hangup = 0;
 	else
-		ch->need_hangup=1;
+		ch->need_hangup = 1;
 
 	return ret;
 }
 
 static void hangup_chan(struct chan_list *ch)
 {
-	int port=ch?ch->bc?ch->bc->port:0:0;
+	int port = ch ? (ch->bc ? ch->bc->port : 0) : 0;
 	if (!ch) {
-		cb_log(1,0,"Cannot hangup chan, no ch\n");
+		cb_log(1, 0, "Cannot hangup chan, no ch\n");
 		return;
 	}
 
-	cb_log(5,port,"hangup_chan called\n");
+	cb_log(5, port, "hangup_chan called\n");
 
-	if (ch->need_hangup) 
-	{
-		cb_log(2,port," --> hangup\n");
-		send_cause2ast(ch->ast,ch->bc,ch);
-		ch->need_hangup=0;
-		ch->need_queue_hangup=0;
+	if (ch->need_hangup) {
+		cb_log(2, port, " --> hangup\n");
+		send_cause2ast(ch->ast, ch->bc, ch);
+		ch->need_hangup = 0;
+		ch->need_queue_hangup = 0;
 		if (ch->ast)
 			ast_hangup(ch->ast);
 		return;
 	}
 
 	if (!ch->need_queue_hangup) {
-		cb_log(2,port," --> No need to queue hangup\n");
+		cb_log(2, port, " --> No need to queue hangup\n");
 	}
 
-	ch->need_queue_hangup=0;
+	ch->need_queue_hangup = 0;
 	if (ch->ast) {
-		send_cause2ast(ch->ast,ch->bc,ch);
+		send_cause2ast(ch->ast, ch->bc, ch);
 
 		if (ch->ast)
 			ast_queue_hangup(ch->ast);
-		cb_log(2,port," --> queue_hangup\n");
+		cb_log(2, port, " --> queue_hangup\n");
 	} else {
-		cb_log(1,port,"Cannot hangup chan, no ast\n");
+		cb_log(1, port, "Cannot hangup chan, no ast\n");
 	}
 }
 
 /** Isdn asks us to release channel, pendant to misdn_hangup **/
 static void release_chan(struct misdn_bchannel *bc) {
-	struct ast_channel *ast=NULL;
-	{
-		struct chan_list *ch=find_chan_by_bc(cl_te, bc);
-		if (!ch)  {
-			chan_misdn_log(1, bc->port, "release_chan: Ch not found!\n");
-			return;
-		}
+	struct ast_channel *ast = NULL;
+	struct chan_list *ch = find_chan_by_bc(cl_te, bc);
+
+	if (!ch)  {
+		chan_misdn_log(1, bc->port, "release_chan: Ch not found!\n");
+		return;
+	}
 		
-		if (ch->ast) {
-			ast=ch->ast;
-		} 
+	if (ch->ast) {
+		ast = ch->ast;
+	} 
 		
-		chan_misdn_log(5, bc->port, "release_chan: bc with l3id: %x\n",bc->l3_id);
+	chan_misdn_log(5, bc->port, "release_chan: bc with l3id: %x\n", bc->l3_id);
 		
-		/*releaseing jitterbuffer*/
-		if (ch->jb ) {
-			misdn_jb_destroy(ch->jb);
-			ch->jb=NULL;
-		} else {
-			if (!bc->nojitter)
-				chan_misdn_log(5,bc->port,"Jitterbuffer already destroyed.\n");
-		}
+	/*releaseing jitterbuffer*/
+	if (ch->jb ) {
+		misdn_jb_destroy(ch->jb);
+		ch->jb = NULL;
+	} else {
+		if (!bc->nojitter)
+			chan_misdn_log(5, bc->port, "Jitterbuffer already destroyed.\n");
+	}
 
-		if (ch->overlap_dial) {
-			if (ch->overlap_dial_task != -1) {
-				misdn_tasks_remove(ch->overlap_dial_task);
-				ch->overlap_dial_task = -1;
-			}
-			ast_mutex_destroy(&ch->overlap_tv_lock);
+	if (ch->overlap_dial) {
+		if (ch->overlap_dial_task != -1) {
+			misdn_tasks_remove(ch->overlap_dial_task);
+			ch->overlap_dial_task = -1;
 		}
+		ast_mutex_destroy(&ch->overlap_tv_lock);
+	}
 
-		if (ch->originator == ORG_AST) {
-			misdn_out_calls[bc->port]--;
-		} else {
-			misdn_in_calls[bc->port]--;
-		}
+	if (ch->originator == ORG_AST) {
+		misdn_out_calls[bc->port]--;
+	} else {
+		misdn_in_calls[bc->port]--;
+	}
 		
-		if (ch) {
-			
-			close(ch->pipe[0]);
-			close(ch->pipe[1]);
+	if (ch) {
+		close(ch->pipe[0]);
+		close(ch->pipe[1]);
 
-			
-			if (ast && MISDN_ASTERISK_TECH_PVT(ast)) {
-				chan_misdn_log(1, bc->port, "* RELEASING CHANNEL pid:%d ctx:%s dad:%s oad:%s state: %s\n",bc?bc->pid:-1, ast->context, ast->exten,ast->cid.cid_num,misdn_get_ch_state(ch));
-				chan_misdn_log(3, bc->port, " --> * State Down\n");
-				MISDN_ASTERISK_TECH_PVT(ast)=NULL;
-				
-      
-				if (ast->_state != AST_STATE_RESERVED) {
-					chan_misdn_log(3, bc->port, " --> Setting AST State to down\n");
-					ast_setstate(ast, AST_STATE_DOWN);
-				}
+		if (ast && MISDN_ASTERISK_TECH_PVT(ast)) {
+			chan_misdn_log(1, bc->port, "* RELEASING CHANNEL pid:%d ctx:%s dad:%s oad:%s state: %s\n", bc ? bc->pid : -1, ast->context, ast->exten, ast->cid.cid_num, misdn_get_ch_state(ch));
+			chan_misdn_log(3, bc->port, " --> * State Down\n");
+			MISDN_ASTERISK_TECH_PVT(ast) = NULL;
+
+			if (ast->_state != AST_STATE_RESERVED) {
+				chan_misdn_log(3, bc->port, " --> Setting AST State to down\n");
+				ast_setstate(ast, AST_STATE_DOWN);
 			}
-				
-			ch->state=MISDN_CLEANING;
-			cl_dequeue_chan(&cl_te, ch);
-			
-			free(ch);
-		} else {
-			/* chan is already cleaned, so exiting  */
 		}
+
+		ch->state = MISDN_CLEANING;
+		cl_dequeue_chan(&cl_te, ch);
+
+		ast_free(ch);
+	} else {
+		/* chan is already cleaned, so exiting  */
 	}
 }
 /*** release end **/
 
 static void misdn_transfer_bc(struct chan_list *tmp_ch, struct chan_list *holded_chan)
 {
-	chan_misdn_log(4,0,"TRANSFERING %s to %s\n",holded_chan->ast->name, tmp_ch->ast->name);
-	
-	tmp_ch->state=MISDN_HOLD_DISCONNECT;
-  
+	chan_misdn_log(4, 0, "TRANSFERING %s to %s\n", holded_chan->ast->name, tmp_ch->ast->name);
+
+	tmp_ch->state = MISDN_HOLD_DISCONNECT;
+
 	ast_moh_stop(ast_bridged_channel(holded_chan->ast));
 
 	holded_chan->state=MISDN_CONNECTED;
-	//misdn_lib_transfer(holded_chan->bc);
+	/* misdn_lib_transfer(holded_chan->bc); */
 	ast_channel_masquerade(holded_chan->ast, ast_bridged_channel(tmp_ch->ast));
 }
 
 
-static void do_immediate_setup(struct misdn_bchannel *bc,struct chan_list *ch , struct ast_channel *ast)
+static void do_immediate_setup(struct misdn_bchannel *bc, struct chan_list *ch, struct ast_channel *ast)
 {
-	char predial[256]="";
-	char *p = predial;
-  
+	char *predial;
 	struct ast_frame fr;
-  
-	strncpy(predial, ast->exten, sizeof(predial) -1 );
-  
-	ch->state=MISDN_DIALING;
+
+	predial = ast_strdupa(ast->exten);
+
+	ch->state = MISDN_DIALING;
 
 	if (!ch->noautorespond_on_setup) {
 		if (bc->nt) {
@@ -3595,10 +3464,10 @@ static void do_immediate_setup(struct misdn_bchannel *bc,struct chan_list *ch ,
 
 	chan_misdn_log(1, bc->port, "* Starting Ast ctx:%s dad:%s oad:%s with 's' extension\n", ast->context, ast->exten, ast->cid.cid_num);
   
-	strncpy(ast->exten,"s", 2);
+	strncpy(ast->exten, "s", 2);
   
-	if (pbx_start_chan(ch)<0) {
-		ast=NULL;
+	if (pbx_start_chan(ch) < 0) {
+		ast = NULL;
 		hangup_chan(ch);
 		hanguptone_indicate(ch);
 
@@ -3609,44 +3478,44 @@ static void do_immediate_setup(struct misdn_bchannel *bc,struct chan_list *ch ,
 	}
   
   
-	while (!ast_strlen_zero(p) ) {
+	while (!ast_strlen_zero(predial) ) {
 		fr.frametype = AST_FRAME_DTMF;
-		fr.subclass = *p ;
-		fr.src=NULL;
-		fr.data = NULL ;
+		fr.subclass = *predial;
+		fr.src = NULL;
+		fr.data = NULL;
 		fr.datalen = 0;
-		fr.samples = 0 ;
-		fr.mallocd =0 ;
-		fr.offset= 0 ;
-		fr.delivery= ast_tv(0,0) ;
+		fr.samples = 0;
+		fr.mallocd = 0;
+		fr.offset = 0;
+		fr.delivery = ast_tv(0,0);
 
 		if (ch->ast && MISDN_ASTERISK_PVT(ch->ast) && MISDN_ASTERISK_TECH_PVT(ch->ast)) {
 			ast_queue_frame(ch->ast, &fr);
 		}
-		p++;
+		predial++;
 	}
 }
 
 
 
-static void send_cause2ast(struct ast_channel *ast, struct misdn_bchannel*bc, struct chan_list *ch) {
+static void send_cause2ast(struct ast_channel *ast, struct misdn_bchannel *bc, struct chan_list *ch) {
 	if (!ast) {
-		chan_misdn_log(1,0,"send_cause2ast: No Ast\n");
+		chan_misdn_log(1, 0, "send_cause2ast: No Ast\n");
 		return;
 	}
 	if (!bc) {
-		chan_misdn_log(1,0,"send_cause2ast: No BC\n");
+		chan_misdn_log(1, 0, "send_cause2ast: No BC\n");
 		return;
 	}
 	if (!ch) {
-		chan_misdn_log(1,0,"send_cause2ast: No Ch\n");
+		chan_misdn_log(1, 0, "send_cause2ast: No Ch\n");
 		return;
 	}
-	
-	ast->hangupcause=bc->cause;
-	
-	switch ( bc->cause) {
-		
+
+	ast->hangupcause = bc->cause;
+
+	switch (bc->cause) {
+
 	case 1: /** Congestion Cases **/
 	case 2:
 	case 3:
@@ -3657,105 +3526,98 @@ static void send_cause2ast(struct ast_channel *ast, struct misdn_bchannel*bc, st
 		 * Not Queueing the Congestion anymore, since we want to hear
 		 * the inband message
 		 *
-		chan_misdn_log(1, bc?bc->port:0, " --> * SEND: Queue Congestion pid:%d\n", bc?bc->pid:-1);
-		ch->state=MISDN_BUSY;
+		chan_misdn_log(1, bc ? bc->port : 0, " --> * SEND: Queue Congestion pid:%d\n", bc ? bc->pid : -1);
+		ch->state = MISDN_BUSY;
 		
 		ast_queue_control(ast, AST_CONTROL_CONGESTION);
 		*/
 		break;
-		
+
 	case 21:
 	case 17: /* user busy */
-	
-		ch->state=MISDN_BUSY;
-			
+
+		ch->state = MISDN_BUSY;
+
 		if (!ch->need_busy) {
-			chan_misdn_log(1,bc?bc->port:0, "Queued busy already\n");
+			chan_misdn_log(1, bc ? bc->port : 0, "Queued busy already\n");
 			break;
 		}
-		
-		chan_misdn_log(1,  bc?bc->port:0, " --> * SEND: Queue Busy pid:%d\n", bc?bc->pid:-1);
+
+		chan_misdn_log(1, bc ? bc->port : 0, " --> * SEND: Queue Busy pid:%d\n", bc ? bc->pid : -1);
 		
 		ast_queue_control(ast, AST_CONTROL_BUSY);
 		
-		ch->need_busy=0;
+		ch->need_busy = 0;
 		
 		break;
 	}
 }
 
 
-
-
 void import_ch(struct ast_channel *chan, struct misdn_bchannel *bc, struct chan_list *ch)
 {
-	const char *tmp;
-	tmp=pbx_builtin_getvar_helper(chan,"MISDN_PID");
+	const char *tmp = pbx_builtin_getvar_helper(chan, "MISDN_PID");
 	if (tmp) {
-		ch->other_pid=atoi(tmp);
-		chan_misdn_log(3,bc->port," --> IMPORT_PID: importing pid:%s\n",tmp);
-		if (ch->other_pid >0) {
-			ch->other_ch=find_chan_by_pid(cl_te,ch->other_pid);
-			if (ch->other_ch) ch->other_ch->other_ch=ch;
+		ch->other_pid = atoi(tmp);
+		chan_misdn_log(3, bc->port, " --> IMPORT_PID: importing pid:%s\n", tmp);
+		if (ch->other_pid > 0) {
+			ch->other_ch = find_chan_by_pid(cl_te, ch->other_pid);
+			if (ch->other_ch)
+				ch->other_ch->other_ch = ch;
 		}
 	}
 
-	tmp=pbx_builtin_getvar_helper(chan,"MISDN_ADDRESS_COMPLETE");
+	tmp = pbx_builtin_getvar_helper(chan, "MISDN_ADDRESS_COMPLETE");
 	if (tmp && (atoi(tmp) == 1)) {
-		bc->sending_complete=1;
+		bc->sending_complete = 1;
 	}
-	
-	tmp=pbx_builtin_getvar_helper(chan,"MISDN_USERUSER");
+
+	tmp = pbx_builtin_getvar_helper(chan, "MISDN_USERUSER");
 	if (tmp) {
 		ast_log(LOG_NOTICE, "MISDN_USERUSER: %s\n", tmp);
-		strcpy(bc->uu, tmp);
-		bc->uulen=strlen(bc->uu);
+		ast_copy_string(bc->uu, tmp, sizeof(bc->uu));
+		bc->uulen = strlen(bc->uu);
 	}
 
-	tmp=pbx_builtin_getvar_helper(chan,"MISDN_KEYPAD");
-	if (tmp) {
-		strncpy(bc->keypad,tmp,sizeof(bc->keypad));
-		bc->keypad[sizeof(bc->keypad)-1]=0;
-	}
-	
-	
+	tmp = pbx_builtin_getvar_helper(chan, "MISDN_KEYPAD");
+	if (tmp)
+		ast_copy_string(bc->keypad, tmp, sizeof(bc->keypad));
 }
 
 void export_ch(struct ast_channel *chan, struct misdn_bchannel *bc, struct chan_list *ch)
 {
 	char tmp[32];
-	chan_misdn_log(3,bc->port," --> EXPORT_PID: pid:%d\n",bc->pid);
-	sprintf(tmp,"%d",bc->pid);
-	pbx_builtin_setvar_helper(chan,"_MISDN_PID",tmp);
+	chan_misdn_log(3, bc->port, " --> EXPORT_PID: pid:%d\n", bc->pid);
+	snprintf(tmp, sizeof(tmp), "%d", bc->pid);
+	pbx_builtin_setvar_helper(chan, "_MISDN_PID", tmp);
 
 	if (bc->sending_complete) {
-		sprintf(tmp,"%d",bc->sending_complete);
-		pbx_builtin_setvar_helper(chan,"MISDN_ADDRESS_COMPLETE",tmp);
+		snprintf(tmp, sizeof(tmp), "%d", bc->sending_complete);
+		pbx_builtin_setvar_helper(chan, "MISDN_ADDRESS_COMPLETE", tmp);
 	}
 
 	if (bc->urate) {
-		sprintf(tmp,"%d",bc->urate);
-		pbx_builtin_setvar_helper(chan,"MISDN_URATE",tmp);
+		snprintf(tmp, sizeof(tmp), "%d", bc->urate);
+		pbx_builtin_setvar_helper(chan, "MISDN_URATE", tmp);
 	}
 
-	if (bc->uulen) {
-		pbx_builtin_setvar_helper(chan,"MISDN_USERUSER",bc->uu);
-	}
+	if (bc->uulen)
+		pbx_builtin_setvar_helper(chan, "MISDN_USERUSER", bc->uu);
 
-	if (bc->keypad[0]) 
-		pbx_builtin_setvar_helper(chan,"MISDN_KEYPAD",bc->keypad);
+	if (!ast_strlen_zero(bc->keypad)) 
+		pbx_builtin_setvar_helper(chan, "MISDN_KEYPAD", bc->keypad);
 }
 
 int add_in_calls(int port)
 {
 	int max_in_calls;
 	
-	misdn_cfg_get( port, MISDN_CFG_MAX_IN, &max_in_calls, sizeof(max_in_calls));
+	misdn_cfg_get(port, MISDN_CFG_MAX_IN, &max_in_calls, sizeof(max_in_calls));
 	misdn_in_calls[port]++;
 
-	if (max_in_calls >=0 && max_in_calls<misdn_in_calls[port]) {
-		ast_log(LOG_NOTICE,"Marking Incoming Call on port[%d]\n",port);
-		return misdn_in_calls[port]-max_in_calls;
+	if (max_in_calls >= 0 && max_in_calls < misdn_in_calls[port]) {
+		ast_log(LOG_NOTICE, "Marking Incoming Call on port[%d]\n", port);
+		return misdn_in_calls[port] - max_in_calls;
 	}
 	
 	return 0;
@@ -3765,12 +3627,11 @@ int add_out_calls(int port)
 {
 	int max_out_calls;
 	
-	misdn_cfg_get( port, MISDN_CFG_MAX_OUT, &max_out_calls, sizeof(max_out_calls));
-	
+	misdn_cfg_get(port, MISDN_CFG_MAX_OUT, &max_out_calls, sizeof(max_out_calls));
 
-	if (max_out_calls >=0 && max_out_calls<=misdn_out_calls[port]) {
-		ast_log(LOG_NOTICE,"Rejecting Outgoing Call on port[%d]\n",port);
-		return (misdn_out_calls[port]+1)-max_out_calls;
+	if (max_out_calls >= 0 && max_out_calls <= misdn_out_calls[port]) {
+		ast_log(LOG_NOTICE, "Rejecting Outgoing Call on port[%d]\n", port);
+		return (misdn_out_calls[port] + 1) - max_out_calls;
 	}
 
 	misdn_out_calls[port]++;
@@ -3779,19 +3640,19 @@ int add_out_calls(int port)
 }
 
 static void wait_for_digits(struct chan_list *ch, struct misdn_bchannel *bc, struct ast_channel *chan) {
-	ch->state=MISDN_WAITING4DIGS;
-	misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
+	ch->state = MISDN_WAITING4DIGS;
+	misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE);
 	if (bc->nt)
 		dialtone_indicate(ch);
 }
 
 static void start_pbx(struct chan_list *ch, struct misdn_bchannel *bc, struct ast_channel *chan) {
-	if (pbx_start_chan(ch)<0) {
+	if (pbx_start_chan(ch) < 0) {
 		hangup_chan(ch);
 		chan_misdn_log(-1, bc->port, "ast_pbx_start returned <0 in SETUP\n");
 		if (bc->nt) {
 			hanguptone_indicate(ch);
-			misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
+			misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE);
 		} else
 			misdn_lib_send_event(bc, EVENT_RELEASE);
 	}
@@ -3803,58 +3664,57 @@ static void start_pbx(struct chan_list *ch, struct misdn_bchannel *bc, struct as
 static enum event_response_e
 cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 {
-	struct chan_list *ch=find_chan_by_bc(cl_te, bc);
+	struct chan_list *ch = find_chan_by_bc(cl_te, bc);
 	
 	if (event != EVENT_BCHAN_DATA && event != EVENT_TONE_GENERATE) { /*  Debug Only Non-Bchan */
-		int debuglevel=1;
-		if ( event==EVENT_CLEANUP && !user_data)
-			debuglevel=5;
+		int debuglevel = 1;
+		if ( event == EVENT_CLEANUP && !user_data)
+			debuglevel = 5;
 
-		chan_misdn_log(debuglevel, bc->port, "I IND :%s oad:%s dad:%s pid:%d state:%s\n", manager_isdn_get_info(event), bc->oad, bc->dad, bc->pid, ch?misdn_get_ch_state(ch):"none");
-		if (debuglevel==1) {
+		chan_misdn_log(debuglevel, bc->port, "I IND :%s oad:%s dad:%s pid:%d state:%s\n", manager_isdn_get_info(event), bc->oad, bc->dad, bc->pid, ch ? misdn_get_ch_state(ch) : "none");
+		if (debuglevel == 1) {
 			misdn_lib_log_ies(bc);
-			chan_misdn_log(4,bc->port," --> bc_state:%s\n",bc_state2str(bc->bc_state));
+			chan_misdn_log(4, bc->port, " --> bc_state:%s\n", bc_state2str(bc->bc_state));
 		}
 	}
 	
 	if (!ch) {
 		switch(event) {
-			case EVENT_SETUP:
-			case EVENT_DISCONNECT:
-			case EVENT_PORT_ALARM:
-			case EVENT_RETRIEVE:
-			case EVENT_NEW_BC:
-			case EVENT_FACILITY:
-				break;
-			case EVENT_RELEASE_COMPLETE:
-				chan_misdn_log(1, bc->port, " --> no Ch, so we've already released.\n");
-				break;
-			case EVENT_CLEANUP:
-			case EVENT_TONE_GENERATE:
-			case EVENT_BCHAN_DATA:
-				return -1;
-
-			default:
-				chan_misdn_log(1,bc->port, "Chan not existing at the moment bc->l3id:%x bc:%p event:%s port:%d channel:%d\n",bc->l3_id, bc, manager_isdn_get_info( event), bc->port,bc->channel);
-				return -1;
+		case EVENT_SETUP:
+		case EVENT_DISCONNECT:
+		case EVENT_PORT_ALARM:
+		case EVENT_RETRIEVE:
+		case EVENT_NEW_BC:
+		case EVENT_FACILITY:
+			break;
+		case EVENT_RELEASE_COMPLETE:
+			chan_misdn_log(1, bc->port, " --> no Ch, so we've already released.\n");
+			break;
+		case EVENT_CLEANUP:
+		case EVENT_TONE_GENERATE:
+		case EVENT_BCHAN_DATA:
+			return -1;
+		default:
+			chan_misdn_log(1, bc->port, "Chan not existing at the moment bc->l3id:%x bc:%p event:%s port:%d channel:%d\n", bc->l3_id, bc, manager_isdn_get_info(event), bc->port, bc->channel);
+			return -1;
 		}
 	}
 	
-	if (ch ) {
+	if (ch) {
 		switch (event) {
 		case EVENT_TONE_GENERATE:
-		break;
+			break;
 		case EVENT_DISCONNECT:
 		case EVENT_RELEASE:
 		case EVENT_RELEASE_COMPLETE:
 		case EVENT_CLEANUP:
 		case EVENT_TIMEOUT:
 			if (!ch->ast)
-				chan_misdn_log(3,bc->port,"ast_hangup already called, so we have no ast ptr anymore in event(%s)\n",manager_isdn_get_info(event));
+				chan_misdn_log(3, bc->port, "ast_hangup already called, so we have no ast ptr anymore in event(%s)\n", manager_isdn_get_info(event));
 			break;
 		default:
-			if ( !ch->ast  || !MISDN_ASTERISK_PVT(ch->ast) || !MISDN_ASTERISK_TECH_PVT(ch->ast)) {
-				if (event!=EVENT_BCHAN_DATA)
+			if (!ch->ast  || !MISDN_ASTERISK_PVT(ch->ast) || !MISDN_ASTERISK_TECH_PVT(ch->ast)) {
+				if (event != EVENT_BCHAN_DATA)
 					ast_log(LOG_NOTICE, "No Ast or No private Pointer in Event (%d:%s)\n", event, manager_isdn_get_info(event));
 				return -1;
 			}
@@ -3865,14 +3725,14 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 	switch (event) {
 	case EVENT_PORT_ALARM:
 		{
-			int boa=0;
-			misdn_cfg_get( bc->port, MISDN_CFG_ALARM_BLOCK, &boa, sizeof(int));
+			int boa = 0;
+			misdn_cfg_get(bc->port, MISDN_CFG_ALARM_BLOCK, &boa, sizeof(boa));
 			if (boa) {
-				cb_log(1,bc->port," --> blocking\n");
+				cb_log(1, bc->port, " --> blocking\n");
 				misdn_lib_port_block(bc->port); 
 			}
 		}
-	break;
+		break;
 	case EVENT_BCHAN_ACTIVATED:
 		break;
 		
@@ -3887,32 +3747,31 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 
 	case EVENT_NEW_BC:
 		if (!ch) {
-			ch=find_holded(cl_te,bc);
+			ch = find_holded(cl_te,bc);
 		}
 		
 		if (!ch) {
-			ast_log(LOG_WARNING,"NEW_BC without chan_list?\n");
+			ast_log(LOG_WARNING, "NEW_BC without chan_list?\n");
 			break;
 		}
 
 		if (bc)
-			ch->bc=(struct misdn_bchannel*)user_data;
+			ch->bc = (struct misdn_bchannel *)user_data;
 		break;
 		
 	case EVENT_DTMF_TONE:
 	{
 		/*  sending INFOS as DTMF-Frames :) */
-		struct ast_frame fr;
-		memset(&fr, 0 , sizeof(fr));
+		struct ast_frame fr = { 0, };
 		fr.frametype = AST_FRAME_DTMF;
 		fr.subclass = bc->dtmf ;
-		fr.src=NULL;
-		fr.data = NULL ;
+		fr.src = NULL;
+		fr.data = NULL;
 		fr.datalen = 0;
-		fr.samples = 0 ;
-		fr.mallocd =0 ;
-		fr.offset= 0 ;
-		fr.delivery= ast_tv(0,0) ;
+		fr.samples = 0;
+		fr.mallocd = 0;
+		fr.offset = 0;
+		fr.delivery = ast_tv(0,0);
 		
 		if (!ch->ignore_dtmf) {
 			chan_misdn_log(2, bc->port, " --> DTMF:%c\n", bc->dtmf);
@@ -3921,51 +3780,45 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 			chan_misdn_log(2, bc->port, " --> Ingoring DTMF:%c due to bridge flags\n", bc->dtmf);
 		}
 	}
-	break;
+		break;
 	case EVENT_STATUS:
 		break;
     
 	case EVENT_INFORMATION:
 	{
-		int l;
-
 		if ( ch->state != MISDN_CONNECTED ) 
 			stop_indicate(ch);
 	
-		if (!ch->ast) break;
+		if (!ch->ast)
+			break;
 
 		if (ch->state == MISDN_WAITING4DIGS ) {
 			/*  Ok, incomplete Setup, waiting till extension exists */
 			if (ast_strlen_zero(bc->info_dad) && ! ast_strlen_zero(bc->keypad)) {
 				chan_misdn_log(1, bc->port, " --> using keypad as info\n");
-				strcpy(bc->info_dad,bc->keypad);
+				ast_copy_string(bc->info_dad, bc->keypad, sizeof(bc->info_dad));
 			}
 
-			l = sizeof(bc->dad);
-			strncat(bc->dad,bc->info_dad, l);
-			bc->dad[l-1] = 0;
-
-			l = sizeof(ch->ast->exten);
-			strncpy(ch->ast->exten, bc->dad, l);
-			ch->ast->exten[l-1] = 0;
+			strncat(bc->dad,bc->info_dad, sizeof(bc->dad) - 1);
+			ast_copy_string(ch->ast->exten, bc->dad, sizeof(ch->ast->exten));
 
 			/* Check for Pickup Request first */
 			if (!strcmp(ch->ast->exten, ast_pickup_ext())) {
 				if (ast_pickup_call(ch->ast)) {
 					hangup_chan(ch);
 				} else {
-					struct ast_channel *chan=ch->ast;
+					struct ast_channel *chan = ch->ast;
 					ch->state = MISDN_CALLING_ACKNOWLEDGE;
 					ast_setstate(chan, AST_STATE_DOWN);
 					hangup_chan(ch);
-					ch->ast=NULL;
+					ch->ast = NULL;
 					break;
 				}
 			}
 			
-			if(!ast_canmatch_extension(ch->ast, ch->context, bc->dad, 1, bc->oad)) {
+			if (!ast_canmatch_extension(ch->ast, ch->context, bc->dad, 1, bc->oad)) {
 				if (ast_exists_extension(ch->ast, ch->context, "i", 1, bc->oad)) {
-					ast_log(LOG_WARNING, "Extension can never match, So jumping to 'i' extension. port(%d)\n",bc->port);
+					ast_log(LOG_WARNING, "Extension can never match, So jumping to 'i' extension. port(%d)\n", bc->port);
 					strcpy(ch->ast->exten, "i");
 					start_pbx(ch, bc, ch->ast);
 					break;
@@ -3977,10 +3830,10 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 
 				if (bc->nt)
 					hanguptone_indicate(ch);
-				ch->state=MISDN_EXTCANTMATCH;
-				bc->out_cause=1;
+				ch->state = MISDN_EXTCANTMATCH;
+				bc->out_cause = 1;
 
-				misdn_lib_send_event(bc, EVENT_DISCONNECT );
+				misdn_lib_send_event(bc, EVENT_DISCONNECT);
 				break;
 			}
 
@@ -4000,28 +3853,22 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 		} else {
 			/*  sending INFOS as DTMF-Frames :) */
 			struct ast_frame fr;
+			int digits;
 			fr.frametype = AST_FRAME_DTMF;
 			fr.subclass = bc->info_dad[0] ;
-			fr.src=NULL;
-			fr.data = NULL ;
+			fr.src = NULL;
+			fr.data = NULL;
 			fr.datalen = 0;
-			fr.samples = 0 ;
-			fr.mallocd =0 ;
-			fr.offset= 0 ;
-			fr.delivery= ast_tv(0,0) ;
+			fr.samples = 0;
+			fr.mallocd = 0;
+			fr.offset = 0;
+			fr.delivery = ast_tv(0,0);
 
-			
-			int digits;
-			misdn_cfg_get( 0, MISDN_GEN_APPEND_DIGITS2EXTEN, &digits, sizeof(int));
+			misdn_cfg_get(0, MISDN_GEN_APPEND_DIGITS2EXTEN, &digits, sizeof(digits));
 			if (ch->state != MISDN_CONNECTED ) {
 				if (digits) {
-					int l = sizeof(bc->dad);
-					strncat(bc->dad,bc->info_dad, l);
-					bc->dad[l-1] = 0;
-					l = sizeof(ch->ast->exten);
-					strncpy(ch->ast->exten, bc->dad, l);
-					ch->ast->exten[l-1] = 0;
-
+					strncat(bc->dad, bc->info_dad, sizeof(bc->dad) - 1);
+					ast_copy_string(ch->ast->exten, bc->dad, sizeof(ch->ast->exten));
 					ast_cdr_update(ch->ast);
 				}
 				
@@ -4029,138 +3876,147 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 			}
 		}
 	}
-	break;
+		break;
 	case EVENT_SETUP:
 	{
-		struct chan_list *ch=find_chan_by_bc(cl_te, bc);
+		struct chan_list *ch = find_chan_by_bc(cl_te, bc);
+		int msn_valid = misdn_cfg_is_msn_valid(bc->port, bc->dad);
+		struct ast_channel *chan;
+		int exceed;
+		int pres,screen;
+		int ai;
+		int im;
+
 		if (ch) {
 			switch (ch->state) {
-				case MISDN_NOTHING:
-				ch=NULL;
+			case MISDN_NOTHING:
+				ch = NULL;
 				break;
-				default:
+			default:
 				chan_misdn_log(1, bc->port, " --> Ignoring Call we have already one\n");
 				return RESPONSE_IGNORE_SETUP_WITHOUT_CLOSE; /*  Ignore MSNs which are not in our List */
 			}
 		}
-	}
 
-	int msn_valid = misdn_cfg_is_msn_valid(bc->port, bc->dad);
-	if (!bc->nt && ! msn_valid) {
-		chan_misdn_log(1, bc->port, " --> Ignoring Call, its not in our MSN List\n");
-		return RESPONSE_IGNORE_SETUP; /*  Ignore MSNs which are not in our List */
-	}
+		if (!bc->nt && ! msn_valid) {
+			chan_misdn_log(1, bc->port, " --> Ignoring Call, its not in our MSN List\n");
+			return RESPONSE_IGNORE_SETUP; /*  Ignore MSNs which are not in our List */
+		}
 
-	
-	if (bc->cw) {
-		chan_misdn_log(0, bc->port, " --> Call Waiting on PMP sending RELEASE_COMPLETE\n");
-		int cause;
-		misdn_cfg_get( bc->port, MISDN_CFG_REJECT_CAUSE, &cause, sizeof(cause));
-		bc->out_cause=cause?cause:16;
-		return RESPONSE_RELEASE_SETUP;
-	}
+		if (bc->cw) {
+			int cause;
+			chan_misdn_log(0, bc->port, " --> Call Waiting on PMP sending RELEASE_COMPLETE\n");
+			misdn_cfg_get(bc->port, MISDN_CFG_REJECT_CAUSE, &cause, sizeof(cause));
+			bc->out_cause = cause ? cause : 16;
+			return RESPONSE_RELEASE_SETUP;
+		}
 
-	print_bearer(bc);
+		print_bearer(bc);
     
-	{
-		int msn_valid = misdn_cfg_is_msn_valid(bc->port, bc->dad);
 		if (!bc->nt && ! msn_valid) {
 			chan_misdn_log(1, bc->port, " --> Ignoring Call, its not in our MSN List\n");
 			return RESPONSE_IGNORE_SETUP; /*  Ignore MSNs which are not in our List */
 		}
 
 		if (bc->cw) {
-			chan_misdn_log(0, bc->port, " --> Call Waiting on PMP sending RELEASE_COMPLETE\n");
 			int cause;
-			misdn_cfg_get( bc->port, MISDN_CFG_REJECT_CAUSE, &cause, sizeof(cause));
-			bc->out_cause=cause?cause:16;
+			chan_misdn_log(0, bc->port, " --> Call Waiting on PMP sending RELEASE_COMPLETE\n");
+			misdn_cfg_get(bc->port, MISDN_CFG_REJECT_CAUSE, &cause, sizeof(cause));
+			bc->out_cause = cause ? cause : 16;
 			return RESPONSE_RELEASE_SETUP;
 		}
 
 		print_bearer(bc);
 
-		struct chan_list *ch=init_chan_list(ORG_MISDN);
-		struct ast_channel *chan;
-		int exceed;
+		ch = init_chan_list(ORG_MISDN);
 
-		if (!ch) { chan_misdn_log(-1, bc->port, "cb_events: malloc for chan_list failed!\n"); return 0;}
+		if (!ch) {
+			chan_misdn_log(-1, bc->port, "cb_events: malloc for chan_list failed!\n");
+			return 0;
+		}
 
 		ch->bc = bc;
-		ch->l3id=bc->l3_id;
-		ch->addr=bc->addr;
+		ch->l3id = bc->l3_id;
+		ch->addr = bc->addr;
 		ch->originator = ORG_MISDN;
 
-		chan=misdn_new(ch, AST_STATE_RESERVED,bc->dad, bc->oad, AST_FORMAT_ALAW, bc->port, bc->channel);
+		chan = misdn_new(ch, AST_STATE_RESERVED, bc->dad, bc->oad, AST_FORMAT_ALAW, bc->port, bc->channel);
 		ch->ast = chan;
 
-		if ((exceed=add_in_calls(bc->port))) {
+		if ((exceed = add_in_calls(bc->port))) {
 			char tmp[16];
-			sprintf(tmp,"%d",exceed);
-			pbx_builtin_setvar_helper(chan,"MAX_OVERFLOW",tmp);
+			snprintf(tmp, sizeof(tmp), "%d", exceed);
+			pbx_builtin_setvar_helper(chan, "MAX_OVERFLOW", tmp);
 		}
 
 		read_config(ch, ORG_MISDN);
 
 		export_ch(chan, bc, ch);
 
-		ch->ast->rings=1;
+		ch->ast->rings = 1;
 		ast_setstate(ch->ast, AST_STATE_RINGING);
 
-		int pres,screen;
-
 		switch (bc->pres) {
-			case 1:
-				pres=AST_PRES_RESTRICTED; chan_misdn_log(2,bc->port," --> PRES: Restricted (1)\n");
-				break;
-			case 2:
-				pres=AST_PRES_UNAVAILABLE; chan_misdn_log(2,bc->port," --> PRES: Restricted (2)\n");
-				break;
-			default:
-				pres=AST_PRES_ALLOWED; chan_misdn_log(2,bc->port," --> PRES: Restricted (%d)\n", bc->pres);
+		case 1:
+			pres = AST_PRES_RESTRICTED;
+			chan_misdn_log(2, bc->port, " --> PRES: Restricted (1)\n");
+			break;
+		case 2:
+			pres = AST_PRES_UNAVAILABLE;
+			chan_misdn_log(2, bc->port, " --> PRES: Restricted (2)\n");
+			break;
+		default:
+			pres = AST_PRES_ALLOWED;
+			chan_misdn_log(2, bc->port, " --> PRES: Restricted (%d)\n", bc->pres);
 		}
 
 		switch (bc->screen) {
-			case 0:
-				screen=AST_PRES_USER_NUMBER_UNSCREENED;  chan_misdn_log(2,bc->port," --> SCREEN: Unscreened (0)\n");
-				break;
-			case 1:
-				screen=AST_PRES_USER_NUMBER_PASSED_SCREEN; chan_misdn_log(2,bc->port," --> SCREEN: Passed screen (1)\n");
-				break;
-			case 2:
-				screen=AST_PRES_USER_NUMBER_FAILED_SCREEN; chan_misdn_log(2,bc->port," --> SCREEN: failed screen (2)\n");
-				break;
-			case 3:
-				screen=AST_PRES_NETWORK_NUMBER; chan_misdn_log(2,bc->port," --> SCREEN: Network Number (3)\n");
-				break;
-			default:
-				screen=AST_PRES_USER_NUMBER_UNSCREENED; chan_misdn_log(2,bc->port," --> SCREEN: Unscreened (%d)\n",bc->screen);
+		case 0:
+			screen = AST_PRES_USER_NUMBER_UNSCREENED;
+			chan_misdn_log(2, bc->port, " --> SCREEN: Unscreened (0)\n");
+			break;
+		case 1:
+			screen = AST_PRES_USER_NUMBER_PASSED_SCREEN;
+			chan_misdn_log(2, bc->port, " --> SCREEN: Passed screen (1)\n");
+			break;
+		case 2:
+			screen = AST_PRES_USER_NUMBER_FAILED_SCREEN;
+			chan_misdn_log(2, bc->port, " --> SCREEN: failed screen (2)\n");
+			break;
+		case 3:
+			screen = AST_PRES_NETWORK_NUMBER;
+			chan_misdn_log(2, bc->port, " --> SCREEN: Network Number (3)\n");
+			break;
+		default:
+			screen = AST_PRES_USER_NUMBER_UNSCREENED;
+			chan_misdn_log(2, bc->port, " --> SCREEN: Unscreened (%d)\n", bc->screen);
 		}
 
-		chan->cid.cid_pres=pres+screen;
+		chan->cid.cid_pres = pres + screen;
 
 		pbx_builtin_setvar_helper(chan, "TRANSFERCAPABILITY", ast_transfercapability2str(bc->capability));
-		chan->transfercapability=bc->capability;
+		chan->transfercapability = bc->capability;
 
 		switch (bc->capability) {
-			case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
-				pbx_builtin_setvar_helper(chan,"CALLTYPE","DIGITAL");
-				break;
-			default:
-				pbx_builtin_setvar_helper(chan,"CALLTYPE","SPEECH");
+		case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
+			pbx_builtin_setvar_helper(chan, "CALLTYPE", "DIGITAL");
+			break;
+		default:
+			pbx_builtin_setvar_helper(chan, "CALLTYPE", "SPEECH");
 		}
 
 		/** queue new chan **/
-		cl_queue_chan(&cl_te, ch) ;
+		cl_queue_chan(&cl_te, ch);
 
-		if (!strstr(ch->allowed_bearers,"all")) {
+		if (!strstr(ch->allowed_bearers, "all")) {
 			int i;
-			for (i=0; i< sizeof(allowed_bearers_array)/sizeof(struct allowed_bearers); i++) {
+			for (i = 0; i < sizeof(allowed_bearers_array) / sizeof(struct allowed_bearers); i++) {
 				if (allowed_bearers_array[i].cap == bc->capability) {
-					if (  !strstr( ch->allowed_bearers, allowed_bearers_array[i].name)) {
-						chan_misdn_log(0,bc->port,"Bearer Not allowed\b");
-						bc->out_cause=88;
+					if (!strstr(ch->allowed_bearers, allowed_bearers_array[i].name)) {
+						chan_misdn_log(0, bc->port, "Bearer Not allowed\b");
+						bc->out_cause = AST_CAUSE_INCOMPATIBLE_DESTINATION;
 
-						ch->state=MISDN_EXTCANTMATCH;
+						ch->state = MISDN_EXTCANTMATCH;
 						misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
 						return RESPONSE_OK;
 					}
@@ -4183,7 +4039,7 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 				ch->state = MISDN_CALLING_ACKNOWLEDGE;
 				ast_setstate(chan, AST_STATE_DOWN);
 				hangup_chan(ch);
-				ch->ast=NULL;
+				ch->ast = NULL;
 				break;
 			}
 		}
@@ -4192,28 +4048,26 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 		   added support for s extension hope it will help those poor cretains
 		   which haven't overlap dial.
 		   */
-		int ai;
-		misdn_cfg_get( bc->port, MISDN_CFG_ALWAYS_IMMEDIATE, &ai, sizeof(ai));
-		if ( ai ) {
-			do_immediate_setup(bc, ch , chan);
+		misdn_cfg_get(bc->port, MISDN_CFG_ALWAYS_IMMEDIATE, &ai, sizeof(ai));
+		if (ai) {
+			do_immediate_setup(bc, ch, chan);
 			break;
 		}
 
 		/* check if we should jump into s when we have no dad */
-		int im;
-		misdn_cfg_get( bc->port, MISDN_CFG_IMMEDIATE, &im, sizeof(im));
-		if ( im && ast_strlen_zero(bc->dad) ) {
-			do_immediate_setup(bc, ch , chan);
+		misdn_cfg_get(bc->port, MISDN_CFG_IMMEDIATE, &im, sizeof(im));
+		if (im && ast_strlen_zero(bc->dad)) {
+			do_immediate_setup(bc, ch, chan);
 			break;
 		}
 
-		chan_misdn_log(5,bc->port,"CONTEXT:%s\n",ch->context);
+		chan_misdn_log(5, bc->port, "CONTEXT:%s\n", ch->context);
 		if(!ast_canmatch_extension(ch->ast, ch->context, bc->dad, 1, bc->oad)) {
 			if (ast_exists_extension(ch->ast, ch->context, "i", 1, bc->oad)) {
-				ast_log(LOG_WARNING, "Extension can never match, So jumping to 'i' extension. port(%d)\n",bc->port);
+				ast_log(LOG_WARNING, "Extension can never match, So jumping to 'i' extension. port(%d)\n", bc->port);
 				strcpy(ch->ast->exten, "i");
 				misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE);
-				ch->state=MISDN_DIALING;
+				ch->state = MISDN_DIALING;
 				start_pbx(ch, bc, chan);
 				break;
 			}
@@ -4224,8 +4078,8 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 			if (bc->nt)
 				hanguptone_indicate(ch);
 
-			ch->state=MISDN_EXTCANTMATCH;
-			bc->out_cause=1;
+			ch->state = MISDN_EXTCANTMATCH;
+			bc->out_cause = AST_CAUSE_UNALLOCATED;
 
 			if (bc->nt)
 				misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
@@ -4283,7 +4137,7 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 			else
 				misdn_lib_send_event(bc, EVENT_PROCEEDING);
 
-			ch->state=MISDN_DIALING;
+			ch->state = MISDN_DIALING;
 			start_pbx(ch, bc, chan);
 			break;
 		}
@@ -4299,25 +4153,13 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 		
 		if (!ast_strlen_zero(bc->infos_pending)) {
 			/* TX Pending Infos */
-			
-			{
-				int l = sizeof(bc->dad);
-				strncat(bc->dad,bc->infos_pending, l - strlen(bc->dad));
-				bc->dad[l-1] = 0;
-			}	
-		
-			if (!ch->ast) break;
-			{
-				int l = sizeof(ch->ast->exten);
-				strncpy(ch->ast->exten, bc->dad, l);
-				ch->ast->exten[l-1] = 0;
-			}
-			{
-				int l = sizeof(bc->info_dad);
-				strncpy(bc->info_dad, bc->infos_pending, l);
-				bc->info_dad[l-1] = 0;
-			}
-			strncpy(bc->infos_pending,"", 1);
+			strncat(bc->dad, bc->infos_pending, sizeof(bc->dad) - strlen(bc->dad) - 1);
+
+			if (!ch->ast)
+				break;
+			ast_copy_string(ch->ast->exten, bc->dad, l, sizeof(ch->ast->exten));
+			ast_copy_string(bc->info_dad, bc->infos_pending, sizeof(bc->info_dad));
+			ast_copy_string(bc->infos_pending, "", sizeof(bc->infos_pending));
 
 			misdn_lib_send_event(bc, EVENT_INFORMATION);
 		}
@@ -4326,14 +4168,15 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 	case EVENT_PROCEEDING:
 	{
 		
-		if ( misdn_cap_is_speech(bc->capability) &&
+		if (misdn_cap_is_speech(bc->capability) &&
 		     misdn_inband_avail(bc) ) {
 			start_bc_tones(ch);
 		}
 
 		ch->state = MISDN_PROCEEDING;
 		
-		if (!ch->ast) break;
+		if (!ch->ast)
+			break;
 
 		ast_queue_control(ch->ast, AST_CONTROL_PROCEEDING);
 	}
@@ -4341,7 +4184,7 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 	case EVENT_PROGRESS:
 
 		if (bc->channel) 
-			update_name(ch->ast,bc->port,bc->channel);
+			update_name(ch->ast, bc->port, bc->channel);
 
 		if (!bc->nt ) {
 			if ( misdn_cap_is_speech(bc->capability) &&
@@ -4350,9 +4193,10 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 				start_bc_tones(ch);
 			}
 			
-			ch->state=MISDN_PROGRESS;
+			ch->state = MISDN_PROGRESS;
 
-			if (!ch->ast) break;
+			if (!ch->ast)
+				break;
 			ast_queue_control(ch->ast, AST_CONTROL_PROGRESS);
 		}
 		break;
@@ -4362,20 +4206,21 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 	{
 		ch->state = MISDN_ALERTING;
 		
-		if (!ch->ast) break;
+		if (!ch->ast)
+			break;
 
 		ast_queue_control(ch->ast, AST_CONTROL_RINGING);
 		ast_setstate(ch->ast, AST_STATE_RINGING);
 		
-		cb_log(7,bc->port," --> Set State Ringing\n");
+		cb_log(7, bc->port, " --> Set State Ringing\n");
 		
-		if ( misdn_cap_is_speech(bc->capability) && misdn_inband_avail(bc)) {
-			cb_log(1,bc->port,"Starting Tones, we have inband Data\n");
+		if (misdn_cap_is_speech(bc->capability) && misdn_inband_avail(bc)) {
+			cb_log(1, bc->port, "Starting Tones, we have inband Data\n");
 			start_bc_tones(ch);
 		} else {
-			cb_log(3,bc->port," --> We have no inband Data, the other end must create ringing\n");
+			cb_log(3, bc->port, " --> We have no inband Data, the other end must create ringing\n");
 			if (ch->far_alerting) {
-				cb_log(1,bc->port," --> The other end can not do ringing eh ?.. we must do all ourself..");
+				cb_log(1, bc->port, " --> The other end can not do ringing eh ?.. we must do all ourself..");
 				start_bc_tones(ch);
 				/*tone_indicate(ch, TONE_FAR_ALERTING);*/
 			}
@@ -4384,21 +4229,24 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 	break;
 	case EVENT_CONNECT:
 	{
+		struct ast_channel *bridged;
+
 		/*we answer when we've got our very new L3 ID from the NT stack */
-		misdn_lib_send_event(bc,EVENT_CONNECT_ACKNOWLEDGE);
+		misdn_lib_send_event(bc, EVENT_CONNECT_ACKNOWLEDGE);
 
-		if (!ch->ast) break;
+		if (!ch->ast)
+			break;
 
-		struct ast_channel *bridged=ast_bridged_channel(ch->ast);
+		bridged = ast_bridged_channel(ch->ast);
 		stop_indicate(ch);
 
-		if (bridged && !strcasecmp(bridged->tech->type,"mISDN")) {
-			struct chan_list *bridged_ch=MISDN_ASTERISK_TECH_PVT(bridged);
+		if (bridged && !strcasecmp(bridged->tech->type, "mISDN")) {
+			struct chan_list *bridged_ch = MISDN_ASTERISK_TECH_PVT(bridged);
 
-			chan_misdn_log(1,bc->port," --> copying cpndialplan:%d and cad:%s to the A-Channel\n",bc->cpnnumplan,bc->cad);
+			chan_misdn_log(1, bc->port, " --> copying cpndialplan:%d and cad:%s to the A-Channel\n", bc->cpnnumplan, bc->cad);
 			if (bridged_ch) {
-				bridged_ch->bc->cpnnumplan=bc->cpnnumplan;
-				ast_copy_string(bridged_ch->bc->cad,bc->cad,sizeof(bc->cad));
+				bridged_ch->bc->cpnnumplan = bc->cpnnumplan;
+				ast_copy_string(bridged_ch->bc->cad, bc->cad, sizeof(bridged_ch->bc->cad));
 			}
 		}
 	}
@@ -4406,91 +4254,91 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 	/* notice that we don't break here!*/
 	case EVENT_CONNECT_ACKNOWLEDGE:
 	{
-		ch->l3id=bc->l3_id;
-		ch->addr=bc->addr;
-		
+		ch->l3id = bc->l3_id;
+		ch->addr = bc->addr;
+
 		start_bc_tones(ch);
-		
+
 		ch->state = MISDN_CONNECTED;
-		
-		if (!ch->ast) break;
+
+		if (!ch->ast)
+			break;
 
 		ast_queue_control(ch->ast, AST_CONTROL_ANSWER);
 	}
 	break;
 	case EVENT_DISCONNECT:
-	/*we might not have an ch->ast ptr here anymore*/
-	if (ch) {
-		struct chan_list *holded_ch=find_holded(cl_te, bc);
-		
-		chan_misdn_log(3,bc->port," --> org:%d nt:%d, inbandavail:%d state:%d\n", ch->originator, bc->nt, misdn_inband_avail(bc), ch->state);
-		if ( ch->originator==ORG_AST && !bc->nt && misdn_inband_avail(bc) && ch->state != MISDN_CONNECTED) {
-			/* If there's inband information available (e.g. a
-			   recorded message saying what was wrong with the
-			   dialled number, or perhaps even giving an
-			   alternative number, then play it instead of
-			   immediately releasing the call */
-			chan_misdn_log(1,bc->port, " --> Inband Info Avail, not sending RELEASE\n");
+		/*we might not have an ch->ast ptr here anymore*/
+		if (ch) {
+			struct chan_list *holded_ch = find_holded(cl_te, bc);
+
+			chan_misdn_log(3, bc->port, " --> org:%d nt:%d, inbandavail:%d state:%d\n", ch->originator, bc->nt, misdn_inband_avail(bc), ch->state);
+			if (ch->originator == ORG_AST && !bc->nt && misdn_inband_avail(bc) && ch->state != MISDN_CONNECTED) {
+				/* If there's inband information available (e.g. a
+				   recorded message saying what was wrong with the
+				   dialled number, or perhaps even giving an
+				   alternative number, then play it instead of
+				   immediately releasing the call */
+				chan_misdn_log(1, bc->port, " --> Inband Info Avail, not sending RELEASE\n");
 		
-			ch->state=MISDN_DISCONNECTED;
-			start_bc_tones(ch);
+				ch->state = MISDN_DISCONNECTED;
+				start_bc_tones(ch);
 
-			if (ch->ast) {
-				ch->ast->hangupcause=bc->cause;
-				if (bc->cause == 17)
-					ast_queue_control(ch->ast, AST_CONTROL_BUSY);
+				if (ch->ast) {
+					ch->ast->hangupcause = bc->cause;
+					if (bc->cause == AST_CAUSE_USER_BUSY)
+						ast_queue_control(ch->ast, AST_CONTROL_BUSY);
+				}
+				ch->need_busy = 0;
+				break;
 			}
-			ch->need_busy=0;
-			break;
-		}
-		
-		/*Check for holded channel, to implement transfer*/
-		if (	holded_ch && 
-			holded_ch != ch && 
-			ch->ast && 
-			ch->state == MISDN_CONNECTED	) {
-			cb_log(1,bc->port," --> found holded ch\n");
-			misdn_transfer_bc(ch, holded_ch) ;
-		}
 
-		bc->need_disconnect=0;
-		
-		stop_bc_tones(ch);
-		hangup_chan(ch);
-	} else {
-	/*	ch=find_holded_l3(cl_te, bc->l3_id,1);
-		if (ch) {
+			/*Check for holded channel, to implement transfer*/
+			if (holded_ch && holded_ch != ch && ch->ast && ch->state == MISDN_CONNECTED) {
+				cb_log(1, bc->port, " --> found holded ch\n");
+				misdn_transfer_bc(ch, holded_ch) ;
+			}
+
+			bc->need_disconnect = 0;
+
+			stop_bc_tones(ch);
 			hangup_chan(ch);
+#if 0
+		} else {
+			ch = find_holded_l3(cl_te, bc->l3_id,1);
+			if (ch) {
+				hangup_chan(ch);
+			}
+#endif
 		}
-	*/
-	}
-	bc->out_cause=-1;
-	if (bc->need_release) misdn_lib_send_event(bc,EVENT_RELEASE);
-	break;
+		bc->out_cause = -1;
+		if (bc->need_release)
+			misdn_lib_send_event(bc, EVENT_RELEASE);
+		break;
 	
 	case EVENT_RELEASE:
 		{
-			bc->need_disconnect=0;
-			bc->need_release=0;
+			bc->need_disconnect = 0;
+			bc->need_release = 0;
 
 			hangup_chan(ch);
 			release_chan(bc);
 		
 			if (bc->need_release_complete) 
-				misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
+				misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE);
 		}
 		break;
 	case EVENT_RELEASE_COMPLETE:
 	{
-		bc->need_disconnect=0;
-		bc->need_release=0;
-		bc->need_release_complete=0;
+		bc->need_disconnect = 0;
+		bc->need_release = 0;
+		bc->need_release_complete = 0;
 
 		stop_bc_tones(ch);
 		hangup_chan(ch);
 
-		if(ch)	
-			ch->state=MISDN_CLEANING;
+		if (ch)
+			ch->state = MISDN_CLEANING;
 
 		release_chan(bc);
 	}
@@ -4500,11 +4348,9 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 	{
 		stop_bc_tones(ch);
 		
-		switch(ch->state) {
-			case MISDN_CALLING:
-				bc->cause=27; /* Destination out of order */
-			break;
-			default:
+		switch (ch->state) {
+		case MISDN_CALLING:
+			bc->cause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
 			break;
 		}
 		
@@ -4515,27 +4361,27 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 
 	case EVENT_TONE_GENERATE:
 	{
-		int tone_len=bc->tone_cnt;
-		struct ast_channel *ast=ch->ast;
+		int tone_len = bc->tone_cnt;
+		struct ast_channel *ast = ch->ast;
 		void *tmp;
 		int res;
 		int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
 
-		chan_misdn_log(9,bc->port,"TONE_GEN: len:%d\n");
+		chan_misdn_log(9, bc->port, "TONE_GEN: len:%d\n");
 
-		if (!ast) break;
+		if (!ast)
+			break;
+
+		if (!ast->generator)
+			break;
 
-		if (!ast->generator) break;
-	
-		
-	
 		tmp = ast->generatordata;
 		ast->generatordata = NULL;
 		generate = ast->generator->generate;
 
-		if (tone_len <0 || tone_len > 512 ) {
-			ast_log(LOG_NOTICE, "TONE_GEN: len was %d, set to 128\n",tone_len);
-			tone_len=128;
+		if (tone_len < 0 || tone_len > 512 ) {
+			ast_log(LOG_NOTICE, "TONE_GEN: len was %d, set to 128\n", tone_len);
+			tone_len = 128;
 		}
 
 		res = generate(ast, tmp, tone_len, tone_len);
@@ -4545,65 +4391,61 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 			ast_log(LOG_WARNING, "Auto-deactivating generator\n");
 			ast_deactivate_generator(ast);
 		} else {
-			bc->tone_cnt=0;
+			bc->tone_cnt = 0;
 		}
 	}
 	break;
-		
+
 	case EVENT_BCHAN_DATA:
 	{
 		if (ch->bc->AOCD_need_export)
 			export_aoc_vars(ch->originator, ch->ast, ch->bc);
-		if ( !misdn_cap_is_speech(ch->bc->capability) ) {
+		if (!misdn_cap_is_speech(ch->bc->capability) ) {
 			struct ast_frame frame;
 			/*In Data Modes we queue frames*/
 			frame.frametype  = AST_FRAME_VOICE; /*we have no data frames yet*/
 			frame.subclass = AST_FORMAT_ALAW;
 			frame.datalen = bc->bframe_len;
-			frame.samples = bc->bframe_len ;
-			frame.mallocd =0 ;
-			frame.offset= 0 ;
-			frame.delivery= ast_tv(0,0) ;
+			frame.samples = bc->bframe_len;
+			frame.mallocd = 0;
+			frame.offset = 0;
+			frame.delivery = ast_tv(0,0);
 			frame.src = NULL;
-			frame.data = bc->bframe ;
-			
+			frame.data = bc->bframe;
+
 			if (ch->ast) 
-				ast_queue_frame(ch->ast,&frame);
+				ast_queue_frame(ch->ast, &frame);
 		} else {
 			fd_set wrfs;
-			struct timeval tv;
-			tv.tv_sec=0;
-			tv.tv_usec=0;
-			
-			
+			struct timeval tv = { 0, 0 };
+			int t;
+
 			FD_ZERO(&wrfs);
-			FD_SET(ch->pipe[1],&wrfs);
-			
-			int t=select(FD_SETSIZE,NULL,&wrfs,NULL,&tv);
+			FD_SET(ch->pipe[1], &wrfs);
+
+			t = select(FD_SETSIZE, NULL, &wrfs, NULL, &tv);
 
 			if (!t) {
 				chan_misdn_log(9, bc->port, "Select Timed out\n");
 				break;
 			}
 			
-			if (t<0) {
-				chan_misdn_log(-1, bc->port, "Select Error (err=%s)\n",strerror(errno));
+			if (t < 0) {
+				chan_misdn_log(-1, bc->port, "Select Error (err=%s)\n", strerror(errno));
 				break;
 			}
 			
-			if (FD_ISSET(ch->pipe[1],&wrfs)) {
-				chan_misdn_log(9, bc->port, "writing %d bytes 2 asterisk\n",bc->bframe_len);
-				int ret=write(ch->pipe[1], bc->bframe, bc->bframe_len);
-				
-				if (ret<=0) {
-					chan_misdn_log(-1, bc->port, "Write returned <=0 (err=%s) --> hanging up channel\n",strerror(errno));
+			if (FD_ISSET(ch->pipe[1], &wrfs)) {
+				chan_misdn_log(9, bc->port, "writing %d bytes 2 asterisk\n", bc->bframe_len);
+				if (write(ch->pipe[1], bc->bframe, bc->bframe_len) <= 0) {
+					chan_misdn_log(-1, bc->port, "Write returned <=0 (err=%s) --> hanging up channel\n", strerror(errno));
 
 					stop_bc_tones(ch);
 					hangup_chan(ch);
 					release_chan(bc);
 				}
 			} else {
-				chan_misdn_log(1, bc->port, "Wripe Pipe full!\n");
+				chan_misdn_log(1, bc->port, "Write Pipe full!\n");
 			}
 		}
 	}
@@ -4611,49 +4453,49 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 	case EVENT_TIMEOUT:
 		{
 		if (ch && bc)
-			chan_misdn_log(1,bc->port,"--> state: %s\n",misdn_get_ch_state(ch));
+			chan_misdn_log(1, bc->port, "--> state: %s\n", misdn_get_ch_state(ch));
 
 		switch (ch->state) {
-			case MISDN_DIALING:
-			case MISDN_PROGRESS:
-				if (bc->nt && !ch->nttimeout) break;
+		case MISDN_DIALING:
+		case MISDN_PROGRESS:
+			if (bc->nt && !ch->nttimeout)
+				break;
 			
-			case MISDN_CALLING:
-			case MISDN_ALERTING:
-			case MISDN_PROCEEDING:
-			case MISDN_CALLING_ACKNOWLEDGE:
-				if (bc->nt) {
-					bc->progress_indicator=8;
-					hanguptone_indicate(ch);
-				}
+		case MISDN_CALLING:
+		case MISDN_ALERTING:
+		case MISDN_PROCEEDING:
+		case MISDN_CALLING_ACKNOWLEDGE:
+			if (bc->nt) {
+				bc->progress_indicator = 8;
+				hanguptone_indicate(ch);
+			}
 				
-				bc->out_cause=1;
-				misdn_lib_send_event(bc,EVENT_DISCONNECT);
+			bc->out_cause = AST_CAUSE_UNALLOCATED;
+			misdn_lib_send_event(bc, EVENT_DISCONNECT);
 			break;
 
-			case MISDN_WAITING4DIGS:
-				if (bc->nt) {
-					bc->progress_indicator=8;
-					bc->out_cause=1;
-					hanguptone_indicate(ch);
-					misdn_lib_send_event(bc,EVENT_DISCONNECT);
-				} else {
-					bc->out_cause=16;
-					misdn_lib_send_event(bc,EVENT_RELEASE);
-				}
+		case MISDN_WAITING4DIGS:
+			if (bc->nt) {
+				bc->progress_indicator = 8;
+				bc->out_cause = AST_CAUSE_UNALLOCATED;
+				hanguptone_indicate(ch);
+				misdn_lib_send_event(bc, EVENT_DISCONNECT);
+			} else {
+				bc->out_cause = AST_CAUSE_NORMAL_CLEARING;
+				misdn_lib_send_event(bc, EVENT_RELEASE);
+			}
 				
 			break;
 
-
-			case MISDN_CLEANING: 
-				chan_misdn_log(1,bc->port," --> in state cleaning .. so ingoring, the stack should clean it for us\n");
+		case MISDN_CLEANING: 
+			chan_misdn_log(1,bc->port," --> in state cleaning .. so ingoring, the stack should clean it for us\n");
 			break;
 
-			default:
-				misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
-			}
+		default:
+			misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
 		}
-		break;
+	}
+	break;
 
     
 	/***************************/
@@ -4661,9 +4503,11 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 	/***************************/
 	case EVENT_RETRIEVE:
 	{
+		struct ast_channel *hold_ast;
+
 		if (!ch) {
 			chan_misdn_log(4, bc->port, " --> no CH, searching in holded");
-			ch=find_holded_l3(cl_te, bc->l3_id,1);
+			ch = find_holded_l3(cl_te, bc->l3_id, 1);
 		}
 
 		if (!ch) {
@@ -4673,19 +4517,19 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 		}
 
 		/*remember the channel again*/
-		ch->bc=bc;
+		ch->bc = bc;
 		ch->state = MISDN_CONNECTED;
 
-		ch->hold_info.port=0;
-		ch->hold_info.channel=0;
-		
-		struct ast_channel *hold_ast=ast_bridged_channel(ch->ast);
-		
+		ch->hold_info.port = 0;
+		ch->hold_info.channel = 0;
+
+		hold_ast = ast_bridged_channel(ch->ast);
+
 		if (hold_ast) {
 			ast_moh_stop(hold_ast);
 		}
-	
-		if ( misdn_lib_send_event(bc, EVENT_RETRIEVE_ACKNOWLEDGE) < 0)
+
+		if (misdn_lib_send_event(bc, EVENT_RETRIEVE_ACKNOWLEDGE) < 0)
 			misdn_lib_send_event(bc, EVENT_RETRIEVE_REJECT);
 	}
 	break;
@@ -4693,19 +4537,19 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 	case EVENT_HOLD:
 	{
 		int hold_allowed;
-		misdn_cfg_get( bc->port, MISDN_CFG_HOLD_ALLOWED, &hold_allowed, sizeof(int));
-		
+		struct ast_channel *bridged = ast_bridged_channel(ch->ast);
+
+		misdn_cfg_get(bc->port, MISDN_CFG_HOLD_ALLOWED, &hold_allowed, sizeof(hold_allowed));
+
 		if (!hold_allowed) {
 
 			chan_misdn_log(-1, bc->port, "Hold not allowed this port.\n");
 			misdn_lib_send_event(bc, EVENT_HOLD_REJECT);
 			break;
 		}
-		
-		struct ast_channel *bridged=ast_bridged_channel(ch->ast);
 
 		if (bridged) {
-			chan_misdn_log(2,bc->port,"Bridge Partner is of type: %s\n",bridged->tech->type);
+			chan_misdn_log(2, bc->port, "Bridge Partner is of type: %s\n", bridged->tech->type);
 			ch->state = MISDN_HOLDED;
 			ch->l3id = bc->l3_id;
 			
@@ -4716,9 +4560,9 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 			ast_moh_start(bridged, NULL, NULL);
 
 			/*forget the channel now*/
-			ch->bc=NULL;
-			ch->hold_info.port=bc->port;
-			ch->hold_info.channel=bc->channel;
+			ch->bc = NULL;
+			ch->hold_info.port = bc->port;
+			ch->hold_info.channel = bc->channel;
 
 		} else {
 			misdn_lib_send_event(bc, EVENT_HOLD_REJECT);
@@ -4739,33 +4583,32 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 		switch (bc->fac_in.Function) {
 		case Fac_CD:
 			{
-				struct ast_channel *bridged=ast_bridged_channel(ch->ast);
+				struct ast_channel *bridged = ast_bridged_channel(ch->ast);
 				struct chan_list *ch_br;
 				if (bridged && MISDN_ASTERISK_TECH_PVT(bridged)) {
-					ch_br=MISDN_ASTERISK_TECH_PVT(bridged);
-					/*ch->state=MISDN_FACILITY_DEFLECTED;*/
+					ch_br = MISDN_ASTERISK_TECH_PVT(bridged);
+					/*ch->state = MISDN_FACILITY_DEFLECTED;*/
 					if (ch_br->bc) {
 						if (ast_exists_extension(bridged, ch->context, (char *)bc->fac_in.u.CDeflection.DeflectedToNumber, 1, bc->oad)) {
-							ch_br->state=MISDN_DIALING;
+							ch_br->state = MISDN_DIALING;
 							if (pbx_start_chan(ch_br) < 0) {
 								chan_misdn_log(-1, ch_br->bc->port, "ast_pbx_start returned < 0 in misdn_overlap_dial_task\n");
 							}
 						}
 					}
-
 				}
 				misdn_lib_send_event(bc, EVENT_DISCONNECT);
 			} 
 			break;
 		case Fac_AOCDCurrency:
 			bc->AOCDtype = Fac_AOCDCurrency;
-			memcpy(&(bc->AOCD.currency), &(bc->fac_in.u.AOCDcur), sizeof(struct FacAOCDCurrency));
+			memcpy(&(bc->AOCD.currency), &(bc->fac_in.u.AOCDcur), sizeof(bc->AOCD.currency));
 			bc->AOCD_need_export = 1;
 			export_aoc_vars(ch->originator, ch->ast, bc);
 			break;
 		case Fac_AOCDChargingUnit:
 			bc->AOCDtype = Fac_AOCDChargingUnit;
-			memcpy(&(bc->AOCD.chargingUnit), &(bc->fac_in.u.AOCDchu), sizeof(struct FacAOCDChargingUnit));
+			memcpy(&(bc->AOCD.chargingUnit), &(bc->fac_in.u.AOCDchu), sizeof(bc->AOCD.chargingUnit));
 			bc->AOCD_need_export = 1;
 			export_aoc_vars(ch->originator, ch->ast, bc);
 			break;
@@ -4779,11 +4622,10 @@ cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
 
 		stop_bc_tones(ch);
 		release_chan(bc);
-		
 		break;
-				
+
 	default:
-		chan_misdn_log(1,0, "Got Unknown Event\n");
+		chan_misdn_log(1, 0, "Got Unknown Event\n");
 		break;
 	}
 	
@@ -4808,7 +4650,8 @@ static int unload_module(void)
 
 	misdn_tasks_destroy();
 	
-	if (!g_config_initialized) return 0;
+	if (!g_config_initialized)
+		return 0;
 	
 	ast_cli_unregister_multiple(chan_misdn_clis, sizeof(chan_misdn_clis) / sizeof(struct ast_cli_entry));
 	
@@ -4819,16 +4662,15 @@ static int unload_module(void)
   
 	ast_channel_unregister(&misdn_tech);
 
-
 	free_robin_list();
 	misdn_cfg_destroy();
 	misdn_lib_destroy();
   
 	if (misdn_debug)
-		free(misdn_debug);
+		ast_free(misdn_debug);
 	if (misdn_debug_only)
-		free(misdn_debug_only);
- 	free(misdn_ports);
+		ast_free(misdn_debug_only);
+ 	ast_free(misdn_ports);
  	
 	return 0;
 }
@@ -4836,12 +4678,19 @@ static int unload_module(void)
 static int load_module(void)
 {
 	int i, port;
-	
-	char ports[256]="";
+	int ntflags = 0;
+	char ports[256] = "";
+	char tempbuf[BUFFERSIZE + 1];
+	char ntfile[BUFFERSIZE + 1];
+	struct misdn_lib_iface iface = {
+		.cb_event = cb_events,
+		.cb_log = chan_misdn_log,
+		.cb_jb_empty = chan_misdn_jb_empty,
+	};
 
-	max_ports=misdn_lib_maxports_get();
+	max_ports = misdn_lib_maxports_get();
 	
-	if (max_ports<=0) {
+	if (max_ports <= 0) {
 		ast_log(LOG_ERROR, "Unable to initialize mISDN\n");
 		return AST_MODULE_LOAD_DECLINE;
 	}
@@ -4850,71 +4699,64 @@ static int load_module(void)
 		ast_log(LOG_ERROR, "Unable to initialize misdn_config.\n");
 		return AST_MODULE_LOAD_DECLINE;
 	}
-	g_config_initialized=1;
+	g_config_initialized = 1;
 	
-	misdn_debug = (int *)malloc(sizeof(int) * (max_ports+1));
-	misdn_ports = (int *)malloc(sizeof(int) * (max_ports+1));
-	misdn_cfg_get( 0, MISDN_GEN_DEBUG, &misdn_debug[0], sizeof(int));
+	misdn_debug = ast_malloc(sizeof(int) * (max_ports + 1));
+	if (!misdn_debug) {
+		ast_log(LOG_ERROR, "Out of memory for misdn_debug\n");
+		return AST_MODULE_LOAD_DECLINE;
+	}
+	misdn_ports = ast_malloc(sizeof(int) * (max_ports + 1));
+	if (!misdn_ports) {
+		ast_log(LOG_ERROR, "Out of memory for misdn_ports\n");
+		return AST_MODULE_LOAD_DECLINE;
+	}
+	misdn_cfg_get(0, MISDN_GEN_DEBUG, &misdn_debug[0], sizeof(misdn_debug[0]));
 	for (i = 1; i <= max_ports; i++) {
 		misdn_debug[i] = misdn_debug[0];
 		misdn_ports[i] = i;
 	}
 	*misdn_ports = 0;
-	misdn_debug_only = (int *)calloc(max_ports + 1, sizeof(int));
+	misdn_debug_only = ast_calloc(max_ports + 1, sizeof(int));
 
-	{
-		char tempbuf[BUFFERSIZE+1];
-		misdn_cfg_get( 0, MISDN_GEN_TRACEFILE, tempbuf, BUFFERSIZE);
-		if (strlen(tempbuf))
-			tracing = 1;
-	}
-	
-	misdn_in_calls = (int *)malloc(sizeof(int) * (max_ports+1));
-	misdn_out_calls = (int *)malloc(sizeof(int) * (max_ports+1));
+	misdn_cfg_get(0, MISDN_GEN_TRACEFILE, tempbuf, sizeof(tempbuf));
+	if (!ast_strlen_zero(tempbuf))
+		tracing = 1;
+
+	misdn_in_calls = ast_malloc(sizeof(int) * (max_ports + 1));
+	misdn_out_calls = ast_malloc(sizeof(int) * (max_ports + 1));
 
-	for (i=1; i <= max_ports; i++) {
-		misdn_in_calls[i]=0;
-		misdn_out_calls[i]=0;
+	for (i = 1; i <= max_ports; i++) {
+		misdn_in_calls[i] = 0;
+		misdn_out_calls[i] = 0;
 	}
-	
+
 	ast_mutex_init(&cl_te_lock);
 
 	misdn_cfg_update_ptp();
 	misdn_cfg_get_ports_string(ports);
 
-	if (strlen(ports))
-		chan_misdn_log(0, 0, "Got: %s from get_ports\n",ports);
-	
+	if (!ast_strlen_zero(ports))
+		chan_misdn_log(0, 0, "Got: %s from get_ports\n", ports);
+
 	{
-		struct misdn_lib_iface iface = {
-			.cb_event = cb_events,
-			.cb_log = chan_misdn_log,
-			.cb_jb_empty = chan_misdn_jb_empty,
-		};
 		
-		if (misdn_lib_init(ports, &iface, NULL))
-			chan_misdn_log(0, 0, "No te ports initialized\n");
-	
-		int ntflags=0;
-		char ntfile[BUFFERSIZE+1];
+	if (misdn_lib_init(ports, &iface, NULL))
+		chan_misdn_log(0, 0, "No te ports initialized\n");
 
-		misdn_cfg_get( 0, MISDN_GEN_NTDEBUGFLAGS, &ntflags, sizeof(int));
-		misdn_cfg_get( 0, MISDN_GEN_NTDEBUGFILE, &ntfile, BUFFERSIZE);
+	misdn_cfg_get(0, MISDN_GEN_NTDEBUGFLAGS, &ntflags, sizeof(ntflags));
+	misdn_cfg_get(0, MISDN_GEN_NTDEBUGFILE, &ntfile, sizeof(ntfile));
 
-		misdn_lib_nt_debug_init(ntflags,ntfile);
+	misdn_lib_nt_debug_init(ntflags, ntfile);
 
-	}
-
-	{
-		if (ast_channel_register(&misdn_tech)) {
-			ast_log(LOG_ERROR, "Unable to register channel class %s\n", misdn_type);
-			unload_module();
-			return -1;
-		}
+	if (ast_channel_register(&misdn_tech)) {
+		ast_log(LOG_ERROR, "Unable to register channel class %s\n", misdn_type);
+		unload_module();
+		return AST_MODULE_LOAD_DECLINE;
 	}
   
 	ast_cli_register_multiple(chan_misdn_clis, sizeof(chan_misdn_clis) / sizeof(struct ast_cli_entry));
-  
+
 	ast_register_application("misdn_set_opt", misdn_set_opt_exec, "misdn_set_opt",
 				 "misdn_set_opt(:<opt><optarg>:<opt><optarg>..):\n"
 				 "Sets mISDN opts. and optargs\n"
@@ -4960,7 +4802,7 @@ static int load_module(void)
 		);
 
 
-	misdn_cfg_get( 0, MISDN_GEN_TRACEFILE, global_tracefile, BUFFERSIZE);
+	misdn_cfg_get(0, MISDN_GEN_TRACEFILE, global_tracefile, sizeof(global_tracefile));
 
 	/* start the l1 watchers */
 	
@@ -4972,7 +4814,7 @@ static int load_module(void)
 			misdn_tasks_add(l1timeout * 1000, misdn_l1_task, &misdn_ports[port]);  
 		}
 	}
-	
+
 	chan_misdn_log(0, 0, "-- mISDN Channel Driver Registered --\n");
 
 	return 0;
@@ -4992,11 +4834,11 @@ static int reload(void)
 static int misdn_facility_exec(struct ast_channel *chan, void *data)
 {
 	struct chan_list *ch = MISDN_ASTERISK_TECH_PVT(chan);
-	char *tok, *tokb;
+	char *parse, *tok, *tokb;
 
-	chan_misdn_log(0,0,"TYPE: %s\n",chan->tech->type);
+	chan_misdn_log(0, 0, "TYPE: %s\n", chan->tech->type);
 	
-	if (strcasecmp(chan->tech->type,"mISDN")) {
+	if (strcasecmp(chan->tech->type, "mISDN")) {
 		ast_log(LOG_WARNING, "misdn_facility makes only sense with chan_misdn channels!\n");
 		return -1;
 	}
@@ -5005,54 +4847,63 @@ static int misdn_facility_exec(struct ast_channel *chan, void *data)
 		ast_log(LOG_WARNING, "misdn_facility Requires arguments\n");
 		return -1;
 	}
-	
-	tok=strtok_r((char*)data,"|", &tokb) ;
-	
+
+	parse = ast_strdupa(data);
+	tok = strtok_r(parse, "|", &tokb) ;
+
 	if (!tok) {
 		ast_log(LOG_WARNING, "misdn_facility Requires arguments\n");
 		return -1;
 	}
-	
-	if (!strcasecmp(tok,"calldeflect")) {
-		tok=strtok_r(NULL,"|", &tokb) ;
+
+	if (!strcasecmp(tok, "calldeflect")) {
+		tok = strtok_r(NULL, "|", &tokb) ;
 		
 		if (!tok) {
 			ast_log(LOG_WARNING, "Facility: Call Defl Requires arguments\n");
 		}
-	
+
 		if (strlen(tok) >= sizeof(ch->bc->fac_out.u.CDeflection.DeflectedToNumber)) {
 			ast_log(LOG_WARNING, "Facility: Number argument too long (up to 15 digits are allowed). Ignoring.\n");
 			return 0; 
 		}
 		ch->bc->fac_out.Function = Fac_CD;
-		strncpy((char *)ch->bc->fac_out.u.CDeflection.DeflectedToNumber, tok, sizeof(ch->bc->fac_out.u.CDeflection.DeflectedToNumber));
+		ast_copy_string((char *)ch->bc->fac_out.u.CDeflection.DeflectedToNumber, tok, sizeof(ch->bc->fac_out.u.CDeflection.DeflectedToNumber));
 		misdn_lib_send_event(ch->bc, EVENT_FACILITY);
 	} else {
-		chan_misdn_log(1, ch->bc->port, "Unknown Facility: %s\n",tok);
+		chan_misdn_log(1, ch->bc->port, "Unknown Facility: %s\n", tok);
 	}
-	
+
 	return 0;
-	
 }
 
 static int misdn_check_l2l1(struct ast_channel *chan, void *data)
 {
-	if (strcasecmp(chan->tech->type,"mISDN")) {
-		ast_log(LOG_WARNING, "misdn_check_l2l1 makes only sense with chan_misdn channels!\n");
-		return -1;
-	}
+	char *parse;
+	char group[BUFFERSIZE + 1];
+	char *port_str;
+	int port = 0;
+	int timeout;
+	int dowait = 0;
+	int port_up;
 
 	AST_DECLARE_APP_ARGS(args,
 			AST_APP_ARG(grouppar);
 			AST_APP_ARG(timeout);
 	);
 
+	if (strcasecmp(chan->tech->type, "mISDN")) {
+		ast_log(LOG_WARNING, "misdn_check_l2l1 makes only sense with chan_misdn channels!\n");
+		return -1;
+	}
+
 	if (ast_strlen_zero((char *)data)) {
 		ast_log(LOG_WARNING, "misdn_check_l2l1 Requires arguments\n");
 		return -1;
 	}
 
-	AST_STANDARD_APP_ARGS(args, data);
+	parse = ast_strdupa(data);
+	AST_STANDARD_APP_ARGS(args, parse);
 
 	if (args.argc != 2) {
 		ast_log(LOG_WARNING, "Wrong argument count\n");
@@ -5060,31 +4911,23 @@ static int misdn_check_l2l1(struct ast_channel *chan, void *data)
 	}
 
 	/*ast_log(LOG_NOTICE, "Arguments: group/port '%s' timeout '%s'\n", args.grouppar, args.timeout);*/
-	char group[BUFFERSIZE+1];
-	char *port_str;
+	timeout = atoi(args.timeout);
+	port_str = args.grouppar;
 
-	int port=0;
-	int timeout=atoi(args.timeout);
-	int dowait=0;
-
-	port_str=args.grouppar;
-
-	int port_up;
-	if (port_str[0]=='g' && port_str[1]==':' ) {
+	if (port_str[0] == 'g' && port_str[1] == ':' ) {
 		/* We make a group call lets checkout which ports are in my group */
 		port_str += 2;
-		strncpy(group, port_str, BUFFERSIZE);
-		group[BUFFERSIZE-1] = 0;
-		chan_misdn_log(2, 0, "Checking Ports in group: %s\n",group);
+		ast_copy_string(group, port_str, sizeof(group));
+		chan_misdn_log(2, 0, "Checking Ports in group: %s\n", group);
 
 		for (	port = misdn_cfg_get_next_port(port); 
 			port > 0;
 			port = misdn_cfg_get_next_port(port)) {
-			
-			chan_misdn_log(2,0,"trying port %d\n",port);
+			char cfg_group[BUFFERSIZE + 1];
 
-			char cfg_group[BUFFERSIZE+1];
-			misdn_cfg_get(port, MISDN_CFG_GROUPNAME, cfg_group, BUFFERSIZE);
+			chan_misdn_log(2, 0, "trying port %d\n", port);
+
+			misdn_cfg_get(port, MISDN_CFG_GROUPNAME, cfg_group, sizeof(cfg_group));
 
 			if (!strcasecmp(cfg_group, group)) {
 				port_up = misdn_lib_port_up(port, 1);
@@ -5092,7 +4935,7 @@ static int misdn_check_l2l1(struct ast_channel *chan, void *data)
 				if (!port_up) {
 					chan_misdn_log(2, 0, " --> port '%d'\n", port);
 					misdn_lib_get_port_up(port);
-					dowait=1;
+					dowait = 1;
 				}
 			}
 		}
@@ -5103,14 +4946,13 @@ static int misdn_check_l2l1(struct ast_channel *chan, void *data)
 		port_up = misdn_lib_port_up(port, 1);
 		if (!port_up) {
 			misdn_lib_get_port_up(port);
-			dowait=1;
+			dowait = 1;
 		}
-
 	}
 
 	if (dowait) {
-		chan_misdn_log(2, 0, "Waiting for '%d' seconds\n",timeout);
-		sleep(timeout);
+		chan_misdn_log(2, 0, "Waiting for '%d' seconds\n", timeout);
+		ast_safe_sleep(chan, timeout * 1000);
 	}
 
 	return 0;
@@ -5119,13 +4961,13 @@ static int misdn_check_l2l1(struct ast_channel *chan, void *data)
 static int misdn_set_opt_exec(struct ast_channel *chan, void *data)
 {
 	struct chan_list *ch = MISDN_ASTERISK_TECH_PVT(chan);
-	char *tok,*tokb;
-	int  keyidx=0;
-	int rxgain=0;
-	int txgain=0;
-	int change_jitter=0;
-	
-	if (strcasecmp(chan->tech->type,"mISDN")) {
+	char *tok, *tokb, *parse;
+	int  keyidx = 0;
+	int rxgain = 0;
+	int txgain = 0;
+	int change_jitter = 0;
+
+	if (strcasecmp(chan->tech->type, "mISDN")) {
 		ast_log(LOG_WARNING, "misdn_set_opt makes only sense with chan_misdn channels!\n");
 		return -1;
 	}
@@ -5135,185 +4977,180 @@ static int misdn_set_opt_exec(struct ast_channel *chan, void *data)
 		return -1;
 	}
 
-	for (tok=strtok_r((char*)data, ":",&tokb);
+	parse = ast_strdupa(data);
+	for (tok = strtok_r(parse, ":", &tokb);
 	     tok;
-	     tok=strtok_r(NULL,":",&tokb) ) {
-		int neglect=0;
-		
+	     tok = strtok_r(NULL, ":", &tokb) ) {
+		int neglect = 0;
+
 		if (tok[0] == '!' ) {
-			neglect=1;
+			neglect = 1;
 			tok++;
 		}
 		
 		switch(tok[0]) {
 			
 		case 'd' :
-			ast_copy_string(ch->bc->display,++tok,84);
-			chan_misdn_log(1, ch->bc->port, "SETOPT: Display:%s\n",ch->bc->display);
+			ast_copy_string(ch->bc->display, ++tok, sizeof(ch->bc->display));
+			chan_misdn_log(1, ch->bc->port, "SETOPT: Display:%s\n", ch->bc->display);
 			break;
 			
 		case 'n':
 			chan_misdn_log(1, ch->bc->port, "SETOPT: No DSP\n");
-			ch->bc->nodsp=1;
+			ch->bc->nodsp = 1;
 			break;
 
 		case 'j':
 			chan_misdn_log(1, ch->bc->port, "SETOPT: jitter\n");
 			tok++;
-			change_jitter=1;
-			
+			change_jitter = 1;
+
 			switch ( tok[0] ) {
-			case 'b' :
-				ch->jb_len=atoi(++tok);
-				chan_misdn_log(1, ch->bc->port, " --> buffer_len:%d\n",ch->jb_len);
+			case 'b':
+				ch->jb_len = atoi(++tok);
+				chan_misdn_log(1, ch->bc->port, " --> buffer_len:%d\n", ch->jb_len);
 				break;
 			case 't' :
-				ch->jb_upper_threshold=atoi(++tok);
-				chan_misdn_log(1, ch->bc->port, " --> upper_threshold:%d\n",ch->jb_upper_threshold);
+				ch->jb_upper_threshold = atoi(++tok);
+				chan_misdn_log(1, ch->bc->port, " --> upper_threshold:%d\n", ch->jb_upper_threshold);
 				break;
-
 			case 'n':
-				ch->bc->nojitter=1;
+				ch->bc->nojitter = 1;
 				chan_misdn_log(1, ch->bc->port, " --> nojitter\n");
 				break;
-				
 			default:
-				ch->jb_len=4000;
-				ch->jb_upper_threshold=0;
-				chan_misdn_log(1, ch->bc->port, " --> buffer_len:%d (default)\n",ch->jb_len);
-				chan_misdn_log(1, ch->bc->port, " --> upper_threshold:%d (default)\n",ch->jb_upper_threshold);
+				ch->jb_len = 4000;
+				ch->jb_upper_threshold = 0;
+				chan_misdn_log(1, ch->bc->port, " --> buffer_len:%d (default)\n", ch->jb_len);
+				chan_misdn_log(1, ch->bc->port, " --> upper_threshold:%d (default)\n", ch->jb_upper_threshold);
 			}
-			
 			break;
-      
 		case 'v':
 			tok++;
 
-			switch ( tok[0] ) {
+			switch (tok[0]) {
 			case 'r' :
-				rxgain=atoi(++tok);
-				if (rxgain<-8) rxgain=-8;
-				if (rxgain>8) rxgain=8;
-				ch->bc->rxgain=rxgain;
-				chan_misdn_log(1, ch->bc->port, "SETOPT: Volume:%d\n",rxgain);
+				rxgain = atoi(++tok);
+				if (rxgain < -8)
+					rxgain = -8;
+				if (rxgain > 8)
+					rxgain = 8;
+				ch->bc->rxgain = rxgain;
+				chan_misdn_log(1, ch->bc->port, "SETOPT: Volume:%d\n", rxgain);
 				break;
 			case 't':
-				txgain=atoi(++tok);
-				if (txgain<-8) txgain=-8;
-				if (txgain>8) txgain=8;
-				ch->bc->txgain=txgain;
-				chan_misdn_log(1, ch->bc->port, "SETOPT: Volume:%d\n",txgain);
+				txgain = atoi(++tok);
+				if (txgain < -8)
+					txgain = -8;
+				if (txgain > 8)
+					txgain = 8;
+				ch->bc->txgain = txgain;
+				chan_misdn_log(1, ch->bc->port, "SETOPT: Volume:%d\n", txgain);
 				break;
 			}
 			break;
       
 		case 'c':
-			keyidx=atoi(++tok);
-      
-			char keys[4096];
-			char *key=NULL, *tmp;
-			int i;
-			misdn_cfg_get( 0, MISDN_GEN_CRYPT_KEYS, keys, sizeof(keys));
+			keyidx = atoi(++tok);
+			{
+				char keys[4096];
+				char *key = NULL, *tmp = keys;
+				int i;
+				misdn_cfg_get(0, MISDN_GEN_CRYPT_KEYS, keys, sizeof(keys));
 
-			tmp=keys;
+				for (i = 0; i < keyidx; i++) {
+					key = strsep(&tmp, ",");
+				}
 
-			for (i=0; i<keyidx; i++) {
-				key=strsep(&tmp,",");
-			}
+				if (key) {
+					ast_copy_string(ch->bc->crypt_key, key, sizeof(ch->bc->crypt_key));
+				}
 
-			if (key) {
-				ast_copy_string(ch->bc->crypt_key, key, sizeof(ch->bc->crypt_key));
+				chan_misdn_log(0, ch->bc->port, "SETOPT: crypt with key:%s\n", ch->bc->crypt_key);
+				break;
 			}
-
-			chan_misdn_log(0, ch->bc->port, "SETOPT: crypt with key:%s\n",ch->bc->crypt_key);
-			break;
-
 		case 'e':
 			chan_misdn_log(1, ch->bc->port, "SETOPT: EchoCancel\n");
 			
 			if (neglect) {
 				chan_misdn_log(1, ch->bc->port, " --> disabled\n");
 #ifdef MISDN_1_2
-				*ch->bc->pipeline=0;
+				*ch->bc->pipeline = 0;
 #else
-				ch->bc->ec_enable=0;
+				ch->bc->ec_enable = 0;
 #endif
 			} else {
 #ifdef MISDN_1_2
 				update_pipeline_config(ch->bc);
 #else
-				ch->bc->ec_enable=1;
-				ch->bc->orig=ch->originator;
+				ch->bc->ec_enable = 1;
+				ch->bc->orig = ch->originator;
 				tok++;
 				if (*tok) {
-					ch->bc->ec_deftaps=atoi(tok);
+					ch->bc->ec_deftaps = atoi(tok);
 				}
 #endif
 			}
 			
 			break;
-      
 		case 'h':
 			chan_misdn_log(1, ch->bc->port, "SETOPT: Digital\n");
 			
-			if (strlen(tok) > 1 && tok[1]=='1') {
+			if (strlen(tok) > 1 && tok[1] == '1') {
 				chan_misdn_log(1, ch->bc->port, "SETOPT: HDLC \n");
 				if (!ch->bc->hdlc) {
-					ch->bc->hdlc=1;
+					ch->bc->hdlc = 1;
 					misdn_lib_setup_bc(ch->bc);
 				}
-			}  
-			ch->bc->capability=INFO_CAPABILITY_DIGITAL_UNRESTRICTED;
+			}
+			ch->bc->capability = INFO_CAPABILITY_DIGITAL_UNRESTRICTED;
 			break;
             
 		case 's':
 			chan_misdn_log(1, ch->bc->port, "SETOPT: Send DTMF\n");
-			ch->bc->send_dtmf=1;
+			ch->bc->send_dtmf = 1;
 			break;
 			
 		case 'f':
 			chan_misdn_log(1, ch->bc->port, "SETOPT: Faxdetect\n");
-			ch->faxdetect=1;
+			ch->faxdetect = 1;
 			misdn_cfg_get(ch->bc->port, MISDN_CFG_FAXDETECT_TIMEOUT, &ch->faxdetect_timeout, sizeof(ch->faxdetect_timeout));
 			break;
 
 		case 'a':
 			chan_misdn_log(1, ch->bc->port, "SETOPT: AST_DSP (for DTMF)\n");
-			ch->ast_dsp=1;
+			ch->ast_dsp = 1;
 			break;
 
 		case 'p':
-			chan_misdn_log(1, ch->bc->port, "SETOPT: callerpres: %s\n",&tok[1]);
+			chan_misdn_log(1, ch->bc->port, "SETOPT: callerpres: %s\n", &tok[1]);
 			/* CRICH: callingpres!!! */
-			if (strstr(tok,"allowed") ) {
-				ch->bc->pres=0;
-			} else if (strstr(tok,"not_screened")) {
-				ch->bc->pres=1;
+			if (strstr(tok,"allowed")) {
+				ch->bc->pres = 0;
+			} else if (strstr(tok, "not_screened")) {
+				ch->bc->pres = 1;
 			}
-			
-			
-			break;
-      
-      
-		default:
+
 			break;
 		}
 	}
 
 	if (change_jitter)
 		config_jitterbuffer(ch);
-	
-	
+
 	if (ch->faxdetect || ch->ast_dsp) {
-		if (!ch->dsp) ch->dsp = ast_dsp_new();
-		if (ch->dsp) ast_dsp_set_features(ch->dsp, DSP_FEATURE_DTMF_DETECT| DSP_FEATURE_FAX_DETECT);
-		if (!ch->trans) ch->trans=ast_translator_build_path(AST_FORMAT_SLINEAR, AST_FORMAT_ALAW);
+		if (!ch->dsp)
+			ch->dsp = ast_dsp_new();
+		if (ch->dsp)
+			ast_dsp_set_features(ch->dsp, DSP_FEATURE_DTMF_DETECT | DSP_FEATURE_FAX_DETECT);
+		if (!ch->trans)
+			ch->trans = ast_translator_build_path(AST_FORMAT_SLINEAR, AST_FORMAT_ALAW);
 	}
 
 	if (ch->ast_dsp) {
-		chan_misdn_log(1,ch->bc->port,"SETOPT: with AST_DSP we deactivate mISDN_dsp\n");
-		ch->bc->nodsp=1;
-		ch->bc->nojitter=1;
+		chan_misdn_log(1, ch->bc->port, "SETOPT: with AST_DSP we deactivate mISDN_dsp\n");
+		ch->bc->nodsp = 1;
+		ch->bc->nojitter = 1;
 	}
 	
 	return 0;
@@ -5322,7 +5159,7 @@ static int misdn_set_opt_exec(struct ast_channel *chan, void *data)
 
 int chan_misdn_jb_empty ( struct misdn_bchannel *bc, char *buf, int len) 
 {
-	struct chan_list *ch=find_chan_by_bc(cl_te, bc);
+	struct chan_list *ch = find_chan_by_bc(cl_te, bc);
 	
 	if (ch && ch->jb) {
 		return misdn_jb_empty(ch->jb, buf, len);
@@ -5341,35 +5178,44 @@ int chan_misdn_jb_empty ( struct misdn_bchannel *bc, char *buf, int len)
 /* allocates the jb-structure and initialise the elements*/
 struct misdn_jb *misdn_jb_init(int size, int upper_threshold)
 {
-    int i;
-    struct misdn_jb *jb = (struct misdn_jb*) malloc(sizeof(struct misdn_jb));
-    jb->size = size;
-    jb->upper_threshold = upper_threshold;
-    jb->wp = 0;
-    jb->rp = 0;
-    jb->state_full = 0;
-    jb->state_empty = 0;
-    jb->bytes_wrote = 0;
-    jb->samples = (char *)malloc(size*sizeof(char));
-
-    if (!jb->samples) {
-	    chan_misdn_log(-1,0,"No free Mem for jb->samples\n");
-	    return NULL;
-    }
-    
-    jb->ok = (char *)malloc(size*sizeof(char));
+	int i;
+	struct misdn_jb *jb;
 
-    if (!jb->ok) {
-	    chan_misdn_log(-1,0,"No free Mem for jb->ok\n");
+	jb = ast_malloc(sizeof(*jb));
+	if (!jb) {
+	    chan_misdn_log(-1, 0, "No free Mem for jb\n");
 	    return NULL;
-    }
+	}
+	jb->size = size;
+	jb->upper_threshold = upper_threshold;
+	jb->wp = 0;
+	jb->rp = 0;
+	jb->state_full = 0;
+	jb->state_empty = 0;
+	jb->bytes_wrote = 0;
+	jb->samples = ast_malloc(size * sizeof(char));
+
+	if (!jb->samples) {
+		ast_free(jb);
+		chan_misdn_log(-1, 0, "No free Mem for jb->samples\n");
+		return NULL;
+	}
+	
+	jb->ok = ast_malloc(size * sizeof(char));
 
-    for(i=0; i<size; i++)
- 	jb->ok[i]=0;
+	if (!jb->ok) {
+		ast_free(jb->samples);
+		ast_free(jb);
+		chan_misdn_log(-1, 0, "No free Mem for jb->ok\n");
+		return NULL;
+	}
+
+	for (i = 0; i < size; i++)
+		jb->ok[i] = 0;
 
-    ast_mutex_init(&jb->mutexjb);
+	ast_mutex_init(&jb->mutexjb);
 
-    return jb;
+	return jb;
 }
 
 /* frees the data and destroys the given jitterbuffer struct */
@@ -5377,69 +5223,66 @@ void misdn_jb_destroy(struct misdn_jb *jb)
 {
 	ast_mutex_destroy(&jb->mutexjb);
 	
-	free(jb->samples);
-	free(jb);
+	ast_free(jb->samples);
+	ast_free(jb);
 }
 
 /* fills the jitterbuffer with len data returns < 0 if there was an
    error (bufferoverflow). */
 int misdn_jb_fill(struct misdn_jb *jb, const char *data, int len)
 {
-    int i, j, rp, wp;
+	int i, j, rp, wp;
 
-    if (!jb || ! data) return 0;
+	if (!jb || ! data)
+		return 0;
 
-    ast_mutex_lock (&jb->mutexjb);
-    
-    wp=jb->wp;
-    rp=jb->rp;
+	ast_mutex_lock(&jb->mutexjb);
 	
-    for(i=0; i<len; i++)
-    {
-	jb->samples[wp]=data[i];
-	jb->ok[wp]=1;
-	wp = (wp!=jb->size-1 ? wp+1 : 0);
-
-	if(wp==jb->rp)
-	    jb->state_full=1;
-    }
-    
-    if(wp>=rp)
-      jb->state_buffer=wp-rp;
-    else
-      jb->state_buffer= jb->size-rp+wp;
-    chan_misdn_log(9,0,"misdn_jb_fill: written:%d | Bufferstatus:%d p:%x\n",len,jb->state_buffer,jb);
-    
-    if(jb->state_full)
-    {
-	jb->wp=wp;
-
-	rp=wp;
-	for(j=0; j<jb->upper_threshold; j++)
-	    rp = (rp!=0 ? rp-1 : jb->size-1);
-	jb->rp=rp;
-	jb->state_full=0;
-	jb->state_empty=1;
-
-	ast_mutex_unlock (&jb->mutexjb);
+	wp = jb->wp;
+	rp = jb->rp;
 	
-	return -1;
-    }
+	for (i = 0; i < len; i++) {
+		jb->samples[wp] = data[i];
+		jb->ok[wp] = 1;
+		wp = (wp != jb->size - 1) ? wp + 1 : 0;
 
-    if(!jb->state_empty)
-    {
-	jb->bytes_wrote+=len;
-	if(jb->bytes_wrote>=jb->upper_threshold)
-	{
-	    jb->state_empty=1;
-	    jb->bytes_wrote=0;
+		if (wp == jb->rp)
+			jb->state_full = 1;
 	}
-    }
-    jb->wp=wp;
 
-    ast_mutex_unlock (&jb->mutexjb);
-    
-    return 0;
+	if (wp >= rp)
+		jb->state_buffer = wp - rp;
+	else
+		jb->state_buffer = jb->size - rp + wp;
+	chan_misdn_log(9, 0, "misdn_jb_fill: written:%d | Bufferstatus:%d p:%x\n", len, jb->state_buffer, jb);
+
+	if (jb->state_full) {
+		jb->wp = wp;
+
+		rp = wp;
+		for (j = 0; j < jb->upper_threshold; j++)
+			rp = rp != 0 ? rp - 1 : jb->size - 1;
+		jb->rp = rp;
+		jb->state_full = 0;
+		jb->state_empty = 1;
+
+		ast_mutex_unlock(&jb->mutexjb);
+
+		return -1;
+	}
+
+	if (!jb->state_empty) {
+		jb->bytes_wrote += len;
+		if (jb->bytes_wrote >= jb->upper_threshold) {
+			jb->state_empty = 1;
+			jb->bytes_wrote = 0;
+		}
+	}
+	jb->wp = wp;
+
+	ast_mutex_unlock(&jb->mutexjb);
+	
+	return 0;
 }
 
 /* gets len bytes out of the jitterbuffer if available, else only the
@@ -5447,52 +5290,45 @@ available data is returned and the return value indicates the number
 of data. */
 int misdn_jb_empty(struct misdn_jb *jb, char *data, int len)
 {
-    int i, wp, rp, read=0;
+	int i, wp, rp, read = 0;
 
-    ast_mutex_lock (&jb->mutexjb);
+	ast_mutex_lock(&jb->mutexjb);
 
-    rp=jb->rp;
-    wp=jb->wp;
+	rp = jb->rp;
+	wp = jb->wp;
 
-    if(jb->state_empty)
-    {	
-	for(i=0; i<len; i++)
-	{
-	    if(wp==rp)
-	    {
-		jb->rp=rp;
-		jb->state_empty=0;
+	if (jb->state_empty) {	
+		for (i = 0; i < len; i++) {
+			if (wp == rp) {
+				jb->rp = rp;
+				jb->state_empty = 0;
 
-		ast_mutex_unlock (&jb->mutexjb);
-		
-		return read;
-	    }
-	    else
-	    {
-		if(jb->ok[rp]==1)
-		{
-		    data[i]=jb->samples[rp];
-		    jb->ok[rp]=0;
-		    rp=(rp!=jb->size-1 ? rp+1 : 0);
-		    read+=1;
+				ast_mutex_unlock(&jb->mutexjb);
+
+				return read;
+			} else {
+				if (jb->ok[rp] == 1) {
+					data[i] = jb->samples[rp];
+					jb->ok[rp] = 0;
+					rp = (rp != jb->size - 1) ? rp + 1 : 0;
+					read += 1;
+				}
+			}
 		}
-	    }
-	}
 
-	if(wp >= rp)
-		jb->state_buffer=wp-rp;
-	else
-		jb->state_buffer= jb->size-rp+wp;
-	chan_misdn_log(9,0,"misdn_jb_empty: read:%d | Bufferstatus:%d p:%x\n",len,jb->state_buffer,jb);
-	
-	jb->rp=rp;
-    }
-    else
-	    chan_misdn_log(9,0,"misdn_jb_empty: Wait...requested:%d p:%x\n",len,jb);
-    
-    ast_mutex_unlock (&jb->mutexjb);
+		if (wp >= rp)
+			jb->state_buffer = wp - rp;
+		else
+			jb->state_buffer = jb->size - rp + wp;
+		chan_misdn_log(9, 0, "misdn_jb_empty: read:%d | Bufferstatus:%d p:%x\n", len, jb->state_buffer, jb);
 
-    return read;
+		jb->rp = rp;
+	} else
+		chan_misdn_log(9, 0, "misdn_jb_empty: Wait...requested:%d p:%x\n", len, jb);
+
+	ast_mutex_unlock(&jb->mutexjb);
+
+	return read;
 }
 
 
@@ -5507,26 +5343,27 @@ int misdn_jb_empty(struct misdn_jb *jb, char *data, int len)
 
 void chan_misdn_log(int level, int port, char *tmpl, ...)
 {
-	if (! ((0 <= port) && (port <= max_ports))) {
-		ast_log(LOG_WARNING, "cb_log called with out-of-range port number! (%d)\n", port);
-		port=0;
-		level=-1;
-	}
-		
 	va_list ap;
 	char buf[1024];
 	char port_buf[8];
-	sprintf(port_buf,"P[%2d] ",port);
-	
+
+	if (! ((0 <= port) && (port <= max_ports))) {
+		ast_log(LOG_WARNING, "cb_log called with out-of-range port number! (%d)\n", port);
+		port = 0;
+		level = -1;
+	}
+
+	snprintf(port_buf, sizeof(port_buf), "P[%2d] ", port);
+
 	va_start(ap, tmpl);
-	vsnprintf( buf, 1023, tmpl, ap );
+	vsnprintf(buf, sizeof(buf), tmpl, ap);
 	va_end(ap);
 
 	if (level == -1)
 		ast_log(LOG_WARNING, buf);
 
 	else if (misdn_debug_only[port] ? 
-			(level==1 && misdn_debug[port]) || (level==misdn_debug[port]) 
+			(level == 1 && misdn_debug[port]) || (level == misdn_debug[port]) 
 		 : level <= misdn_debug[port]) {
 		
 		ast_console_puts(port_buf);
@@ -5534,13 +5371,15 @@ void chan_misdn_log(int level, int port, char *tmpl, ...)
 	}
 	
 	if ((level <= misdn_debug[0]) && !ast_strlen_zero(global_tracefile) ) {
+		char ctimebuf[30];
 		time_t tm = time(NULL);
-		char *tmp=ctime(&tm),*p;
-		
-		FILE *fp= fopen(global_tracefile, "a+");
-		
-		p=strchr(tmp,'\n');
-		if (p) *p=':';
+		char *tmp = ctime_r(&tm, ctimebuf), *p;
+
+		FILE *fp = fopen(global_tracefile, "a+");
+
+		p = strchr(tmp, '\n');
+		if (p)
+			*p = ':';
 		
 		if (!fp) {
 			ast_console_puts("Error opening Tracefile: [ ");
@@ -5552,9 +5391,9 @@ void chan_misdn_log(int level, int port, char *tmpl, ...)
 			return ;
 		}
 		
-		fputs(tmp,fp);
+		fputs(tmp, fp);
 		fputs(" ", fp);
-		fputs(port_buf,fp);
+		fputs(port_buf, fp);
 		fputs(" ", fp);
 		fputs(buf, fp);
 
@@ -5563,7 +5402,7 @@ void chan_misdn_log(int level, int port, char *tmpl, ...)
 }
 
 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Channel driver for mISDN Support (BRI/PRI)",
-		.load = load_module,
-		.unload = unload_module,
-		.reload = reload,
-	       );
+	.load = load_module,
+	.unload = unload_module,
+	.reload = reload,
+);
diff --git a/channels/chan_oss.c b/channels/chan_oss.c
index 4308e837d201682e3036928126a8ba76cf4f5013..b101ed8ff02dcb7d33024691b3c5f7cd7a3385fd 100644
--- a/channels/chan_oss.c
+++ b/channels/chan_oss.c
@@ -1306,7 +1306,7 @@ static char *console_dial(struct ast_cli_entry *e, int cmd, struct ast_cli_args
 	} else
 		ast_cli(a->fd, "No such extension '%s' in context '%s'\n", mye, myc);
 	if (s)
-		free(s);
+		ast_free(s);
 	return CLI_SUCCESS;
 }
 
@@ -1362,7 +1362,7 @@ static int console_transfer(int fd, int argc, char *argv[])
 			ast_cli(fd, "Failed to transfer :(\n");
 	}
 	if (tmp)
-		free(tmp);
+		ast_free(tmp);
 	return RESULT_SUCCESS;
 }
 
@@ -1470,7 +1470,7 @@ static void store_mixer(struct chan_oss_pvt *o, char *s)
 		}
 	}
 	if (o->mixer_cmd)
-		free(o->mixer_cmd);
+		ast_free(o->mixer_cmd);
 	o->mixer_cmd = ast_strdup(s);
 	ast_log(LOG_WARNING, "setting mixer %s\n", s);
 }
@@ -1543,7 +1543,7 @@ static struct chan_oss_pvt *store_config(struct ast_config *cfg, char *ctg)
 		asprintf(&cmd, "mixer %s", o->mixer_cmd);
 		ast_log(LOG_WARNING, "running [%s]\n", cmd);
 		system(cmd);
-		free(cmd);
+		ast_free(cmd);
 	}
 	if (o == &oss_default)		/* we are done with the default */
 		return NULL;
@@ -1574,7 +1574,7 @@ static struct chan_oss_pvt *store_config(struct ast_config *cfg, char *ctg)
 
   error:
 	if (o != &oss_default)
-		free(o);
+		ast_free(o);
 	return NULL;
 }
 
diff --git a/channels/chan_sip.c b/channels/chan_sip.c
index d103ef743dad064fa9a2556018eb589bebbc87cc..2a4495a19fccaf1e8a7870818914e918a0fa4b62 100644
--- a/channels/chan_sip.c
+++ b/channels/chan_sip.c
@@ -1791,7 +1791,7 @@ static int proxy_update(struct sip_proxy *proxy)
 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
 {
 	struct sip_proxy *proxy;
-	proxy = ast_calloc(1, sizeof(struct sip_proxy));
+	proxy = ast_calloc(1, sizeof(*proxy));
 	if (!proxy)
 		return NULL;
 	proxy->force = force;
@@ -2015,7 +2015,7 @@ static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
 	if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
 		return;
 	if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
-		free(hist);
+		ast_free(hist);
 		return;
 	}
 	memcpy(hist->event, buf, l);
@@ -2141,7 +2141,7 @@ static int retrans_pkt(void *data)
 		if (cur == pkt) {
 			UNLINK(cur, pkt->owner->packets, prev);
 			sip_pvt_unlock(pkt->owner);
-			free(pkt);
+			ast_free(pkt);
 			return 0;
 		}
 	}
@@ -2300,7 +2300,7 @@ static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
 				cur->retransid = -1;
 			}
 			UNLINK(cur, p->packets, prev);
-			free(cur);
+			ast_free(cur);
 			break;
 		}
 	}
@@ -2708,7 +2708,7 @@ static void sip_destroy_peer(struct sip_peer *peer)
 		ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name);
 
 	if (peer->outboundproxy)
-		free(peer->outboundproxy);
+		ast_free(peer->outboundproxy);
 
 	/* Delete it, it needs to disappear */
 	if (peer->call)
@@ -2745,7 +2745,7 @@ static void sip_destroy_peer(struct sip_peer *peer)
 	peer->auth = NULL;
 	if (peer->dnsmgr)
 		ast_dnsmgr_release(peer->dnsmgr);
-	free(peer);
+	ast_free(peer);
 }
 
 /*! \brief Update peer data in database (if used) */
@@ -2903,7 +2903,7 @@ static void sip_destroy_user(struct sip_user *user)
 		ruserobjs--;
 	else
 		suserobjs--;
-	free(user);
+	ast_free(user);
 }
 
 /*! \brief Load user from realtime storage
@@ -3304,7 +3304,7 @@ static void sip_registry_destroy(struct sip_registry *reg)
 		ast_sched_del(sched, reg->timeout);
 	ast_string_field_free_pools(reg);
 	regobjs--;
-	free(reg);
+	ast_free(reg);
 	
 }
 
@@ -3331,7 +3331,7 @@ static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
 		sip_dump_history(p);
 
 	if (p->options)
-		free(p->options);
+		ast_free(p->options);
 
 	if (p->stateid > -1)
 		ast_extension_state_del(p->stateid, NULL);
@@ -3349,7 +3349,7 @@ static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
 	if (p->udptl)
 		ast_udptl_destroy(p->udptl);
 	if (p->refer)
-		free(p->refer);
+		ast_free(p->refer);
 	if (p->route) {
 		free_old_route(p->route);
 		p->route = NULL;
@@ -3374,8 +3374,8 @@ static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
 	if (p->history) {
 		struct sip_history *hist;
 		while( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) )
-			free(hist);
-		free(p->history);
+			ast_free(hist);
+		ast_free(p->history);
 		p->history = NULL;
 	}
 
@@ -3400,7 +3400,7 @@ static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
 		p->packets = p->packets->next;
 		if (cp->retransid > -1)
 			ast_sched_del(sched, cp->retransid);
-		free(cp);
+		ast_free(cp);
 	}
 	if (p->chanvars) {
 		ast_variables_destroy(p->chanvars);
@@ -3410,7 +3410,7 @@ static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
 
 	ast_string_field_free_pools(p);
 
-	free(p);
+	ast_free(p);
 }
 
 /*! \brief  update_call_counter: Handle call_limit for SIP users 
@@ -4686,7 +4686,7 @@ static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *si
 		return NULL;
 
 	if (ast_string_field_init(p, 512)) {
-		free(p);
+		ast_free(p);
 		return NULL;
 	}
 
@@ -4738,7 +4738,7 @@ static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *si
 				ast_variables_destroy(p->chanvars);
 				p->chanvars = NULL;
 			}
-			free(p);
+			ast_free(p);
 			return NULL;
 		}
 		ast_rtp_setqos(p->rtp, global_tos_audio, global_cos_audio);
@@ -4997,7 +4997,7 @@ static int sip_register(char *value, int lineno)
 
 	if (ast_string_field_init(reg, 256)) {
 		ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
-		free(reg);
+		ast_free(reg);
 		return -1;
 	}
 
@@ -6334,7 +6334,7 @@ static void temp_pvt_cleanup(void *data)
 
 	ast_string_field_free_pools(p);
 
-	free(data);
+	ast_free(data);
 }
 
 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
@@ -8601,7 +8601,7 @@ static void free_old_route(struct sip_route *route)
 
 	while (route) {
 		next = route->next;
-		free(route);
+		ast_free(route);
 		route = next;
 	}
 }
@@ -13572,7 +13572,7 @@ static void *sip_park_thread(void *stuff)
 	transferee = d->chan1;
 	transferer = d->chan2;
 	copy_request(&req, &d->req);
-	free(d);
+	ast_free(d);
 
 	if (!transferee || !transferer) {
 		ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
@@ -13704,7 +13704,7 @@ static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct
 		d->seqno = seqno;
 		if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
 			/* Could not start thread */
-			free(d);	/* We don't need it anymore. If thread is created, d will be free'd
+			ast_free(d);	/* We don't need it anymore. If thread is created, d will be free'd
 					   by sip_park_thread() */
 			return 0;
 		}
@@ -16664,7 +16664,7 @@ static void clear_sip_domains(void)
 
 	AST_LIST_LOCK(&domain_list);
 	while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
-		free(d);
+		ast_free(d);
 	AST_LIST_UNLOCK(&domain_list);
 }
 
@@ -16737,7 +16737,7 @@ static int clear_realm_authentication(struct sip_auth *authlist)
 	while (a) {
 		b = a;
 		a = a->next;
-		free(b);
+		ast_free(b);
 	}
 
 	return 1;
@@ -17225,7 +17225,7 @@ static struct sip_peer *build_peer(const char *name, struct ast_variable *v, str
 		asprintf(&reg_string, "%s:%s@%s/%s", peer->username, peer->secret, peer->tohost, callback);
 		if (reg_string) {
 			sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
-			free(reg_string);
+			ast_free(reg_string);
 		}
 	}
 	return peer;
@@ -18646,7 +18646,7 @@ static int unload_module(void)
 	sched_context_destroy(sched);
 
 	if (global_disclaimer)
-		free(global_disclaimer);
+		ast_free(global_disclaimer);
 
 	return 0;
 }
diff --git a/channels/chan_skinny.c b/channels/chan_skinny.c
index ab0c944528eaad1cbee70c7f79596c214924cb35..a2d843183b2a142addc85b96bf99ff0baed87203 100644
--- a/channels/chan_skinny.c
+++ b/channels/chan_skinny.c
@@ -2125,7 +2125,7 @@ static struct skinny_device *build_device(const char *cat, struct ast_variable *
 	int speeddialInstance = 1;
 	int y = 0;
 
-	if (!(d = ast_calloc(1, sizeof(struct skinny_device)))) {
+	if (!(d = ast_calloc(1, sizeof(*d)))) {
 		return NULL;
 	} else {
 		ast_copy_string(d->name, cat, sizeof(d->name));
@@ -2137,7 +2137,7 @@ static struct skinny_device *build_device(const char *cat, struct ast_variable *
 		while(v) {
 			if (!strcasecmp(v->name, "host")) {
 				if (ast_get_ip(&d->addr, v->value)) {
-					free(d);
+					ast_free(d);
 					return NULL;
 				}
 			} else if (!strcasecmp(v->name, "port")) {
@@ -2203,7 +2203,7 @@ static struct skinny_device *build_device(const char *cat, struct ast_variable *
 			} else if (!strcasecmp(v->name, "linelabel")) {
 				ast_copy_string(linelabel, v->value, sizeof(linelabel));
 			} else if (!strcasecmp(v->name, "speeddial")) {
-				if (!(sd = ast_calloc(1, sizeof(struct skinny_speeddial)))) {
+				if (!(sd = ast_calloc(1, sizeof(*sd)))) {
 					return NULL;
 				} else {
 					char *stringp, *exten, *context, *label;
@@ -2232,7 +2232,7 @@ static struct skinny_device *build_device(const char *cat, struct ast_variable *
 					d->speeddials = sd;
 				}
 			} else if (!strcasecmp(v->name, "addon")) {
-				if (!(a = ast_calloc(1, sizeof(struct skinny_addon)))) {
+				if (!(a = ast_calloc(1, sizeof(*a)))) {
 					return NULL;
 				} else {
 					ast_mutex_init(&a->lock);
@@ -2242,7 +2242,7 @@ static struct skinny_device *build_device(const char *cat, struct ast_variable *
 					d->addons = a;
 				}
 			} else if (!strcasecmp(v->name, "trunk") || !strcasecmp(v->name, "line")) {
-				if (!(l = ast_calloc(1, sizeof(struct skinny_line)))) {
+				if (!(l = ast_calloc(1, sizeof(*l)))) {
 					return NULL;
 				} else {
 					ast_mutex_init(&l->lock);
@@ -2850,7 +2850,7 @@ static struct ast_channel *skinny_new(struct skinny_line *l, int state)
 		ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
 		return NULL;
 	} else {
-		sub = ast_calloc(1, sizeof(struct skinny_subchannel));
+		sub = ast_calloc(1, sizeof(*sub));
 		if (!sub) {
 			ast_log(LOG_WARNING, "Unable to allocate Skinny subchannel\n");
 			return NULL;
@@ -4250,7 +4250,7 @@ static int handle_message(struct skinny_req *req, struct skinnysession *s)
 
 	if ((!s->device) && (letohl(req->e) != REGISTER_MESSAGE && letohl(req->e) != ALARM_MESSAGE)) {
 		ast_log(LOG_WARNING, "Client sent message #%d without first registering.\n", req->e);
-		free(req);
+		ast_free(req);
 		return 0;
 	}
 
@@ -4398,7 +4398,7 @@ static int handle_message(struct skinny_req *req, struct skinnysession *s)
 		break;
 	}
 	if (res >= 0 && req)
-		free(req);
+		ast_free(req);
 	return res;
 }
 
@@ -4424,7 +4424,7 @@ static void destroy_session(struct skinnysession *s)
 			close(s->fd);
 		}
 		ast_mutex_destroy(&s->lock);
-		free(s);
+		ast_free(s);
 	} else {
 		ast_log(LOG_WARNING, "Trying to delete nonexistent session %p?\n", s);
 	}
@@ -4521,7 +4521,7 @@ static struct skinny_req *skinny_req_parse(struct skinnysession *s)
 
 	if (letohl(req->e) < 0) {
 		ast_log(LOG_ERROR, "Event Message is NULL from socket %d, This is bad\n", s->fd);
-		free(req);
+		ast_free(req);
 		return NULL;
 	}
 
@@ -4896,25 +4896,25 @@ static void delete_devices(void)
 			llast = l;
 			l = l->next;
 			ast_mutex_destroy(&llast->lock);
-			free(llast);
+			ast_free(llast);
 		}
 		/* Delete all speeddials for this device */
 		for (sd=d->speeddials;sd;) {
 			sdlast = sd;
 			sd = sd->next;
 			ast_mutex_destroy(&sdlast->lock);
-			free(sdlast);
+			ast_free(sdlast);
 		}
 		/* Delete all addons for this device */
 		for (a=d->addons;a;) {
 			alast = a;
 			a = a->next;
 			ast_mutex_destroy(&alast->lock);
-			free(alast);
+			ast_free(alast);
 		}
 		dlast = d;
 		d = d->next;
-		free(dlast);
+		ast_free(dlast);
 	}
 	devices=NULL;
 	ast_mutex_unlock(&devicelock);
@@ -4999,7 +4999,7 @@ static int unload_module(void)
 		if (slast->fd > -1)
 			close(slast->fd);
 		ast_mutex_destroy(&slast->lock);
-		free(slast);
+		ast_free(slast);
 	}
 	sessions = NULL;
 	ast_mutex_unlock(&sessionlock);
diff --git a/channels/chan_vpb.cc b/channels/chan_vpb.cc
index 3cacf0313785db448a177d108bc54d91d8d310cc..748f58f7b063c752987a1bbda4e5be08c4b200c1 100644
--- a/channels/chan_vpb.cc
+++ b/channels/chan_vpb.cc
@@ -679,10 +679,10 @@ static void get_callerid(struct vpb_pvt *p)
 		if ((rc=vpb_cid_decode2(cli_struct, buf, CID_MSECS*8)) == VPB_OK ) {
 			/*
 			if (owner->cid.cid_num)
-				free(owner->cid.cid_num);
+				ast_free(owner->cid.cid_num);
 			owner->cid.cid_num=NULL;
 			if (owner->cid.cid_name)
-				free(owner->cid.cid_name);
+				ast_free(owner->cid.cid_name);
 			owner->cid.cid_name=NULL;
 			*/
 			
@@ -791,11 +791,11 @@ static void get_callerid_ast(struct vpb_pvt *p)
 		ast_log(LOG_ERROR, "%s: Failed to create Caller ID struct\n", p->dev );
 	}
 	if (owner->cid.cid_num) {
-		free(owner->cid.cid_num);
+		ast_free(owner->cid.cid_num);
 		owner->cid.cid_num = NULL;
 	}
 	if (owner->cid.cid_name) {
-		free(owner->cid.cid_name);
+		ast_free(owner->cid.cid_name);
 		owner->cid.cid_name = NULL;
 	}
 	if (number)
@@ -1239,10 +1239,10 @@ static inline int monitor_handle_notowned(struct vpb_pvt *p, VPB_EVENT *e)
 						if (owner){
 							/*
 							if (owner->cid.cid_num)
-								free(owner->cid.cid_num);
+								ast_free(owner->cid.cid_num);
 							owner->cid.cid_num=NULL;
 							if (owner->cid.cid_name)
-								free(owner->cid.cid_name);
+								ast_free(owner->cid.cid_name);
 							owner->cid.cid_name=NULL;
 							owner->cid.cid_num = strdup(p->callerid);
 							*/
@@ -1499,11 +1499,10 @@ static void mkbrd(vpb_model_t model, int echo_cancel)
 	if(!bridges) {
 		if(model==vpb_model_v4pci) 
 			max_bridges = MAX_BRIDGES_V4PCI;
-		bridges = (vpb_bridge_t *)malloc(max_bridges * sizeof(vpb_bridge_t) );
+		bridges = ast_calloc(1, max_bridges * sizeof(vpb_bridge_t));
 		if(!bridges) 
 			ast_log(LOG_ERROR, "Failed to initialize bridges\n");
 		else {
-			memset(bridges,0,max_bridges * sizeof(vpb_bridge_t));
 			for(int i = 0; i < max_bridges; i++ ) {
 				ast_mutex_init(&bridges[i].lock);
 				ast_cond_init(&bridges[i].cond, NULL);
@@ -1544,7 +1543,7 @@ static struct vpb_pvt *mkif(int board, int channel, int mode, int gains, float t
 	struct vpb_pvt *tmp;
 	char buf[64];
 
-	tmp = (struct vpb_pvt *)calloc(1, sizeof *tmp);
+	tmp = ast_calloc(1, sizeof(*tmp));
 
 	if (!tmp)
 		return NULL;
@@ -1554,7 +1553,7 @@ static struct vpb_pvt *mkif(int board, int channel, int mode, int gains, float t
 	if (tmp->handle < 0) {	  
 		ast_log(LOG_WARNING, "Unable to create channel vpb/%d-%d: %s\n", 
 					board, channel, strerror(errno));
-		free(tmp);
+		ast_free(tmp);
 		return NULL;
 	}
 	       
@@ -2741,7 +2740,7 @@ static struct ast_channel *vpb_request(const char *type, int format, void *data,
 		ast_verbose(VERBOSE_PREFIX_2 " %s requested, got: [%s]\n",
 		name, tmp ? tmp->name : "None");
 
-	free(name);
+	ast_free(name);
 
 	restart_monitor();
 	return tmp;
@@ -2814,7 +2813,7 @@ int unload_module()
 
 			iflist = iflist->next;
 
-			free(p);
+			ast_free(p);
 		}
 		iflist = NULL;
 	} ast_mutex_unlock(&iflock);
@@ -2827,7 +2826,7 @@ int unload_module()
 		ast_mutex_destroy(&bridges[i].lock);
 		ast_cond_destroy(&bridges[i].cond);
 	}
-	free(bridges);
+	ast_free(bridges);
 
 	return 0;
 }
diff --git a/channels/chan_zap.c b/channels/chan_zap.c
index a72ed27638b4478b3030309a0eae056ad09e87d7..861210318e335d8299319b9bdcaca45bb11108b0 100644
--- a/channels/chan_zap.c
+++ b/channels/chan_zap.c
@@ -1878,7 +1878,7 @@ static int send_callerid(struct zt_pvt *p)
 			return 0;
 		p->cidpos += res;
 	}
-	free(p->cidspill);
+	ast_free(p->cidspill);
 	p->cidspill = NULL;
 	if (p->callwaitcas) {
 		/* Wait for CID/CW to expire */
@@ -1894,7 +1894,7 @@ static int zt_callwait(struct ast_channel *ast)
 	p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
 	if (p->cidspill) {
 		ast_log(LOG_WARNING, "Spill already exists?!?\n");
-		free(p->cidspill);
+		ast_free(p->cidspill);
 	}
 	if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
 		return -1;
@@ -1971,7 +1971,7 @@ static int zt_call(struct ast_channel *ast, char *rdest, int timeout)
 				/* Generate the Caller-ID spill if desired */
 				if (p->cidspill) {
 					ast_log(LOG_WARNING, "cidspill already exists??\n");
-					free(p->cidspill);
+					ast_free(p->cidspill);
 				}
 				p->callwaitcas = 0;
 				if ((p->cidspill = ast_malloc(MAX_CALLERID_SIZE))) {
@@ -2413,7 +2413,7 @@ static void destroy_zt_pvt(struct zt_pvt **pvt)
 	if (p->mwi_event_sub)
 		ast_event_unsubscribe(p->mwi_event_sub);
 	ast_mutex_destroy(&p->lock);
-	free(p);
+	ast_free(p);
 	*pvt = NULL;
 }
 
@@ -2636,12 +2636,12 @@ static int zt_hangup(struct ast_channel *ast)
 	restore_gains(p);
 	if (p->origcid_num) {
 		ast_copy_string(p->cid_num, p->origcid_num, sizeof(p->cid_num));
-		free(p->origcid_num);
+		ast_free(p->origcid_num);
 		p->origcid_num = NULL;
 	}	
 	if (p->origcid_name) {
 		ast_copy_string(p->cid_name, p->origcid_name, sizeof(p->cid_name));
-		free(p->origcid_name);
+		ast_free(p->origcid_name);
 		p->origcid_name = NULL;
 	}	
 	if (p->dsp)
@@ -2904,7 +2904,7 @@ static int zt_hangup(struct ast_channel *ast)
 			tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
 		}
 		if (p->cidspill)
-			free(p->cidspill);
+			ast_free(p->cidspill);
 		if (p->sig)
 			zt_disable_ec(p);
 		x = 0;
@@ -3891,7 +3891,7 @@ static void zt_handle_dtmfup(struct ast_channel *ast, int index, struct ast_fram
 			if (option_debug)
 				ast_log(LOG_DEBUG, "Got some DTMF, but it's for the CAS\n");
 			if (p->cidspill)
-				free(p->cidspill);
+				ast_free(p->cidspill);
 			send_cwcidspill(p);
 		}
 		if ((f->subclass != 'm') && (f->subclass != 'u')) 
@@ -4289,7 +4289,7 @@ static struct ast_frame *zt_handle_event(struct ast_channel *ast)
 						ast_log(LOG_DEBUG, "channel %d answered\n", p->channel);
 					if (p->cidspill) {
 						/* Cancel any running CallerID spill */
-						free(p->cidspill);
+						ast_free(p->cidspill);
 						p->cidspill = NULL;
 					}
 					p->dialing = 0;
@@ -4419,7 +4419,7 @@ static struct ast_frame *zt_handle_event(struct ast_channel *ast)
 			ast->rings++;
 			if ((ast->rings > p->cidrings) && (p->cidspill)) {
 				ast_log(LOG_WARNING, "Didn't finish Caller-ID spill.  Cancelling.\n");
-				free(p->cidspill);
+				ast_free(p->cidspill);
 				p->cidspill = NULL;
 				p->callwaitcas = 0;
 			}
@@ -6240,10 +6240,10 @@ static void *ss_thread(void *data)
 				/* Disable Caller*ID if enabled */
 				p->hidecallerid = 1;
 				if (chan->cid.cid_num)
-					free(chan->cid.cid_num);
+					ast_free(chan->cid.cid_num);
 				chan->cid.cid_num = NULL;
 				if (chan->cid.cid_name)
-					free(chan->cid.cid_name);
+					ast_free(chan->cid.cid_name);
 				chan->cid.cid_name = NULL;
 				res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
 				if (res) {
@@ -6322,10 +6322,10 @@ static void *ss_thread(void *data)
 				/* Enable Caller*ID if enabled */
 				p->hidecallerid = 0;
 				if (chan->cid.cid_num)
-					free(chan->cid.cid_num);
+					ast_free(chan->cid.cid_num);
 				chan->cid.cid_num = NULL;
 				if (chan->cid.cid_name)
-					free(chan->cid.cid_name);
+					ast_free(chan->cid.cid_name);
 				chan->cid.cid_name = NULL;
 				ast_set_callerid(chan, p->cid_num, p->cid_name, NULL);
 				res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
@@ -6952,7 +6952,7 @@ static int handle_init_event(struct zt_pvt *i, int event)
 				break;
 			if (i->cidspill) {
 				/* Cancel VMWI spill */
-				free(i->cidspill);
+				ast_free(i->cidspill);
 				i->cidspill = NULL;
 			}
 			if (i->immediate) {
@@ -7152,7 +7152,7 @@ static void *do_monitor(void *data)
 		ast_mutex_lock(&iflock);
 		if (!pfds || (lastalloc != ifcount)) {
 			if (pfds)
-				free(pfds);
+				ast_free(pfds);
 			if (ifcount) {
 				if (!(pfds = ast_calloc(1, ifcount * sizeof(*pfds)))) {
 					ast_mutex_unlock(&iflock);
@@ -7273,7 +7273,7 @@ static void *do_monitor(void *data)
 						if (res2 > 0) {
 							i->cidpos += res2;
 							if (i->cidpos >= i->cidlen) {
-								free(i->cidspill);
+								ast_free(i->cidspill);
 								i->cidspill = 0;
 								i->cidpos = 0;
 								i->cidlen = 0;
@@ -10618,7 +10618,7 @@ static int handle_pri_show_span(int fd, int argc, char *argv[])
 			info_str = pri_dump_info_str(pris[span-1].pri);
 			if (info_str) {
 				ast_cli(fd, "%s", info_str);
-				free(info_str);
+				ast_free(info_str);
 			}
 #else
 			pri_dump_info(pris[span-1].pri);
@@ -11414,7 +11414,7 @@ static int __unload_module(void)
 	while (p) {
 		/* Free any callerid */
 		if (p->cidspill)
-			free(p->cidspill);
+			ast_free(p->cidspill);
 		/* Close the zapata thingy */
 		if (p->subs[SUB_REAL].zfd > -1)
 			zt_close(p->subs[SUB_REAL].zfd);
@@ -12872,7 +12872,7 @@ static int zt_sendtext(struct ast_channel *c, const char *text)
 		len = tdd_generate(p->tdd, buf, text);
 		if (len < 1) {
 			ast_log(LOG_ERROR, "TDD generate (len %d) failed!!\n", (int)strlen(text));
-			free(mybuf);
+			ast_free(mybuf);
 			return -1;
 		}
 	}
@@ -12881,7 +12881,7 @@ static int zt_sendtext(struct ast_channel *c, const char *text)
 	fd = p->subs[index].zfd;
 	while (len) {
 		if (ast_check_hangup(c)) {
-			free(mybuf);
+			ast_free(mybuf);
 			return -1;
 		}
 		size = len;
@@ -12907,7 +12907,7 @@ static int zt_sendtext(struct ast_channel *c, const char *text)
 		res = write(fd, buf, size);
 		if (res != size) {
 			if (res == -1) {
-				free(mybuf);
+				ast_free(mybuf);
 				return -1;
 			}
 			if (option_debug)
@@ -12917,7 +12917,7 @@ static int zt_sendtext(struct ast_channel *c, const char *text)
 		len -= size;
 		buf += size;
 	}
-	free(mybuf);
+	ast_free(mybuf);
 	return(0);
 }
 
diff --git a/channels/iax2-parser.c b/channels/iax2-parser.c
index 28bb0723057eb4ea71de9b137bce6e6b6c420e56..423976ce959815d1ba986b5ae24c465d727602e6 100644
--- a/channels/iax2-parser.c
+++ b/channels/iax2-parser.c
@@ -922,7 +922,7 @@ int iax_parse_ies(struct iax_ies *ies, unsigned char *data, int datalen)
 						prev->next = var;
 					else
 						ies->vars = var;
-					free(var2);
+					ast_free(var2);
 					break;
 				}
 			}
@@ -1048,14 +1048,14 @@ void iax_frame_free(struct iax_frame *fr)
 
 #if !defined(LOW_MEMORY)
 	if (!fr->cacheable || !(iax_frames = ast_threadstorage_get(&frame_cache, sizeof(*iax_frames)))) {
-		free(fr);
+		ast_free(fr);
 		return;
 	}
 
 	fr->direction = 0;
 	AST_LIST_INSERT_HEAD(iax_frames, fr, list);
 #else
-	free(fr);
+	ast_free(fr);
 #endif
 }
 
@@ -1066,9 +1066,9 @@ static void frame_cache_cleanup(void *data)
 	struct iax_frame *cur;
 
 	while ((cur = AST_LIST_REMOVE_HEAD(frames, list)))
-		free(cur);
+		ast_free(cur);
 
-	free(frames);
+	ast_free(frames);
 }
 #endif
 
diff --git a/channels/iax2-provision.c b/channels/iax2-provision.c
index 5a484fda54a287ef72a74d4bd53066ecca83b8b1..31016b2ad451b363cc2447971b14c128fc1c94c1 100644
--- a/channels/iax2-provision.c
+++ b/channels/iax2-provision.c
@@ -376,13 +376,12 @@ static int iax_process_template(struct ast_config *cfg, char *s, char *def)
 	}
 	if (!cur) {
 		mallocd = 1;
-		cur = malloc(sizeof(struct iax_template));
+		cur = ast_calloc(1, sizeof(*cur));
 		if (!cur) {
 			ast_log(LOG_WARNING, "Out of memory!\n");
 			return -1;
 		}
 		/* Initialize entry */
-		memset(cur, 0, sizeof(*cur));
 		strncpy(cur->name, s, sizeof(cur->name) - 1);
 		cur->dead = 1;
 	}
@@ -527,7 +526,7 @@ int iax_provision_reload(void)
 				prev->next = next;
 			else
 				templates = next;
-			free(cur);
+			ast_free(cur);
 		} else 
 			prev = cur;
 		cur = next;
diff --git a/channels/misdn_config.c b/channels/misdn_config.c
index 69b35ccbf1c86e191d233635b36e4584611f17d8..0aca65c809c71188b6a7e6cb01643b401adaa15f 100644
--- a/channels/misdn_config.c
+++ b/channels/misdn_config.c
@@ -452,8 +452,8 @@ static void _free_msn_list (struct msn_list* iter)
 	if (iter->next)
 		_free_msn_list(iter->next);
 	if (iter->msn)
-		free(iter->msn);
-	free(iter);
+		ast_free(iter->msn);
+	ast_free(iter);
 }
 
 static void _free_port_cfg (void)
@@ -483,7 +483,7 @@ static void _free_port_cfg (void)
 				if (port_spec[i].type == MISDN_CTYPE_MSNLIST)
 					_free_msn_list(free_list[j][i].ml);
 				else
-					free(free_list[j][i].any);
+					ast_free(free_list[j][i].any);
 			}
 		}
 	}
@@ -495,10 +495,10 @@ static void _free_general_cfg (void)
 
 	for (i = 0; i < NUM_GEN_ELEMENTS; i++) 
 		if (general_cfg[i].any)
-			free(general_cfg[i].any);
+			ast_free(general_cfg[i].any);
 }
 
-void misdn_cfg_get (int port, enum misdn_cfg_elements elem, void *buf, int bufsize)
+void misdn_cfg_get(int port, enum misdn_cfg_elements elem, void *buf, int bufsize)
 {
 	int place;
 
@@ -514,18 +514,16 @@ void misdn_cfg_get (int port, enum misdn_cfg_elements elem, void *buf, int bufsi
 			memset(buf, 0, bufsize);
 	} else {
 		if ((place = map[elem]) < 0) {
-			memset (buf, 0, bufsize);
+			memset(buf, 0, bufsize);
 			ast_log(LOG_WARNING, "Invalid call to misdn_cfg_get! Invalid element (%d) requested.\n", elem);
 		} else {
 			if (elem < MISDN_CFG_LAST) {
 				switch (port_spec[place].type) {
 				case MISDN_CTYPE_STR:
 					if (port_cfg[port][place].str) {
-						if (!memccpy(buf, port_cfg[port][place].str, 0, bufsize))
-							memset(buf, 0, 1);
+						ast_copy_string(buf, port_cfg[port][place].str, bufsize);
 					} else if (port_cfg[0][place].str) {
-						if (!memccpy(buf, port_cfg[0][place].str, 0, bufsize))
-							memset(buf, 0, 1);
+						ast_copy_string(buf, port_cfg[0][place].str, bufsize);
 					}
 					break;
 				default:
@@ -539,8 +537,7 @@ void misdn_cfg_get (int port, enum misdn_cfg_elements elem, void *buf, int bufsi
 			} else {
 				switch (gen_spec[place].type) {
 				case MISDN_CTYPE_STR:
-					if (!general_cfg[place].str || !memccpy(buf, general_cfg[place].str, 0, bufsize))
-						memset(buf, 0, 1);
+					ast_copy_string(buf, S_OR(general_cfg[place].str, ""), bufsize);
 					break;
 				default:
 					if (general_cfg[place].any)
@@ -554,7 +551,7 @@ void misdn_cfg_get (int port, enum misdn_cfg_elements elem, void *buf, int bufsi
 	misdn_cfg_unlock();
 }
 
-enum misdn_cfg_elements misdn_cfg_get_elem (char *name)
+enum misdn_cfg_elements misdn_cfg_get_elem(char *name)
 {
 	int pos;
 
@@ -564,18 +561,18 @@ enum misdn_cfg_elements misdn_cfg_get_elem (char *name)
 	if (!strcmp(name, "name"))
 		return MISDN_CFG_FIRST;
 
-	pos = get_cfg_position (name, PORT_CFG);
+	pos = get_cfg_position(name, PORT_CFG);
 	if (pos >= 0)
 		return port_spec[pos].elem;
 	
-	pos = get_cfg_position (name, GEN_CFG);
+	pos = get_cfg_position(name, GEN_CFG);
 	if (pos >= 0)
 		return gen_spec[pos].elem;
 	
 	return MISDN_CFG_FIRST;
 }
 
-void misdn_cfg_get_name (enum misdn_cfg_elements elem, void *buf, int bufsize)
+void misdn_cfg_get_name(enum misdn_cfg_elements elem, void *buf, int bufsize)
 {
 	struct misdn_cfg_spec *spec = NULL;
 	int place = map[elem];
@@ -592,14 +589,13 @@ void misdn_cfg_get_name (enum misdn_cfg_elements elem, void *buf, int bufsize)
 			memset(buf, 0, 1);
 		return;
 	}
-	
+
 	if ((elem > MISDN_CFG_FIRST) && (elem < MISDN_CFG_LAST))
 		spec = (struct misdn_cfg_spec *)port_spec;
 	else if ((elem > MISDN_GEN_FIRST) && (elem < MISDN_GEN_LAST))
 		spec = (struct misdn_cfg_spec *)gen_spec;
 
-	if (!spec || !memccpy(buf, spec[place].name, 0, bufsize))
-		memset(buf, 0, 1);
+	ast_copy_string(buf, spec ? spec[place].name : "", bufsize);
 }
 
 void misdn_cfg_get_desc (enum misdn_cfg_elements elem, void *buf, int bufsize, void *buf_default, int bufsize_default)
@@ -609,8 +605,7 @@ void misdn_cfg_get_desc (enum misdn_cfg_elements elem, void *buf, int bufsize, v
 
 	/* here comes a hack to replace the (not existing) "name" elemet with the "ports" element */
 	if (elem == MISDN_CFG_GROUPNAME) {
-		if (!memccpy(buf, ports_description, 0, bufsize))
-			memset(buf, 0, 1);
+		ast_copy_string(buf, ports_description, bufsize);
 		if (buf_default && bufsize_default)
 			memset(buf_default, 0, 1);
 		return;
@@ -624,13 +619,12 @@ void misdn_cfg_get_desc (enum misdn_cfg_elements elem, void *buf, int bufsize, v
 	if (!spec || !spec[place].desc)
 		memset(buf, 0, 1);
 	else {
-		if (!memccpy(buf, spec[place].desc, 0, bufsize))
-			memset(buf, 0, 1);
+		ast_copy_string(buf, spec[place].desc, bufsize);
 		if (buf_default && bufsize) {
 			if (!strcmp(spec[place].def, NO_DEFAULT))
 				memset(buf_default, 0, 1);
-			else if (!memccpy(buf_default, spec[place].def, 0, bufsize_default))
-				memset(buf_default, 0, 1);
+			else
+				ast_copy_string(buf_default, spec[place].def, bufsize_default);
 		}
 	}
 }
@@ -857,11 +851,11 @@ static int _parse (union misdn_cfg_pt *dest, char *value, enum misdn_cfg_type ty
 	switch (type) {
 	case MISDN_CTYPE_STR:
 		if ((len = strlen(value))) {
-			dest->str = (char *)malloc((len + 1) * sizeof(char));
+			dest->str = ast_malloc((len + 1) * sizeof(char));
 			strncpy(dest->str, value, len);
 			dest->str[len] = 0;
 		} else {
-			dest->str = (char *)malloc( sizeof(char));
+			dest->str = ast_malloc(sizeof(char));
 			dest->str[0] = 0;
 		}
 		break;
@@ -873,18 +867,18 @@ static int _parse (union misdn_cfg_pt *dest, char *value, enum misdn_cfg_type ty
 		else
 			pat="%d";
 		if (sscanf(value, pat, &tmp)) {
-			dest->num = (int *)malloc(sizeof(int));
+			dest->num = ast_malloc(sizeof(int));
 			memcpy(dest->num, &tmp, sizeof(int));
 		} else
 			re = -1;
 	}
 		break;
 	case MISDN_CTYPE_BOOL:
-		dest->num = (int *)malloc(sizeof(int));
+		dest->num = ast_malloc(sizeof(int));
 		*(dest->num) = (ast_true(value) ? 1 : 0);
 		break;
 	case MISDN_CTYPE_BOOLINT:
-		dest->num = (int *)malloc(sizeof(int));
+		dest->num = ast_malloc(sizeof(int));
 		if (sscanf(value, "%d", &tmp)) {
 			memcpy(dest->num, &tmp, sizeof(int));
 		} else {
@@ -894,8 +888,8 @@ static int _parse (union misdn_cfg_pt *dest, char *value, enum misdn_cfg_type ty
 	case MISDN_CTYPE_MSNLIST:
 		for (valtmp = strsep(&value, ","); valtmp; valtmp = strsep(&value, ",")) {
 			if ((len = strlen(valtmp))) {
-				struct msn_list *ml = (struct msn_list *)malloc(sizeof(struct msn_list));
-				ml->msn = (char *)calloc(len+1, sizeof(char));
+				struct msn_list *ml = ast_malloc(sizeof(*ml));
+				ml->msn = ast_calloc(len+1, sizeof(char));
 				strncpy(ml->msn, valtmp, len);
 				ml->next = dest->ml;
 				dest->ml = ml;
@@ -903,7 +897,7 @@ static int _parse (union misdn_cfg_pt *dest, char *value, enum misdn_cfg_type ty
 		}
 		break;
 	case MISDN_CTYPE_ASTGROUP:
-		dest->grp = (ast_group_t *)malloc(sizeof(ast_group_t));
+		dest->grp = ast_malloc(sizeof(ast_group_t));
 		*(dest->grp) = ast_get_group(value);
 		break;
 	}
@@ -1066,10 +1060,10 @@ void misdn_cfg_destroy (void)
 	_free_port_cfg();
 	_free_general_cfg();
 
-	free(port_cfg);
-	free(general_cfg);
-	free(ptp);
-	free(map);
+	ast_free(port_cfg);
+	ast_free(general_cfg);
+	ast_free(ptp);
+	ast_free(map);
 
 	misdn_cfg_unlock();
 	ast_mutex_destroy(&config_mutex);
@@ -1095,10 +1089,10 @@ int misdn_cfg_init (int this_max_ports)
 	if (this_max_ports) {
 		/* this is the first run */
 		max_ports = this_max_ports;
-		map = (int *)calloc(MISDN_GEN_LAST + 1, sizeof(int));
+		map = ast_calloc(MISDN_GEN_LAST + 1, sizeof(int));
 		if (_enum_array_map())
 			return -1;
-		p = (char *)calloc(1, (max_ports + 1) * sizeof(union misdn_cfg_pt *)
+		p = ast_calloc(1, (max_ports + 1) * sizeof(union misdn_cfg_pt *)
 						   + (max_ports + 1) * NUM_PORT_ELEMENTS * sizeof(union misdn_cfg_pt));
 		port_cfg = (union misdn_cfg_pt **)p;
 		p += (max_ports + 1) * sizeof(union misdn_cfg_pt *);
@@ -1106,8 +1100,8 @@ int misdn_cfg_init (int this_max_ports)
 			port_cfg[i] = (union misdn_cfg_pt *)p;
 			p += NUM_PORT_ELEMENTS * sizeof(union misdn_cfg_pt);
 		}
-		general_cfg = (union misdn_cfg_pt *)calloc(1, sizeof(union misdn_cfg_pt *) * NUM_GEN_ELEMENTS);
-		ptp = (int *)calloc(max_ports + 1, sizeof(int));
+		general_cfg = ast_calloc(1, sizeof(union misdn_cfg_pt *) * NUM_GEN_ELEMENTS);
+		ptp = ast_calloc(max_ports + 1, sizeof(int));
 	}
 	else {
 		/* misdn reload */
diff --git a/codecs/codec_lpc10.c b/codecs/codec_lpc10.c
index 3f46e0af8c42daffdb8927f253d1651212724d5c..723c5d8ce65b138a23364994e72c3b5e300ac273 100644
--- a/codecs/codec_lpc10.c
+++ b/codecs/codec_lpc10.c
@@ -230,7 +230,7 @@ static void lpc10_destroy(struct ast_trans_pvt *arg)
 {
 	struct lpc10_coder_pvt *pvt = arg->pvt;
 	/* Enc and DEC are both just allocated, so they can be freed */
-	free(pvt->lpc10.enc);
+	ast_free(pvt->lpc10.enc);
 }
 
 static struct ast_translator lpc10tolin = {
diff --git a/codecs/codec_zap.c b/codecs/codec_zap.c
index c3c7463e4d7bd0a5da991c5275f227188b6d4a0c..60f7fe2c18efcac3ebb3dbcc13c9a20dcb219227 100644
--- a/codecs/codec_zap.c
+++ b/codecs/codec_zap.c
@@ -265,7 +265,7 @@ static int register_translator(int dst, int src)
 	zt->t.buf_size = BUFFER_SAMPLES * 2;
 	zt->t.desc_size = sizeof(struct pvt);
 	if ((res = ast_register_translator(&zt->t))) {
-		free(zt);
+		ast_free(zt);
 		return -1;
 	}
 
@@ -292,7 +292,7 @@ static void drop_translator(int dst, int src)
 
 		AST_LIST_REMOVE_CURRENT(&translators, entry);
 		ast_unregister_translator(&cur->t);
-		free(cur);
+		ast_free(cur);
 		global_format_map.map[dst][src] = 0;
 		break;
 	}
@@ -307,7 +307,7 @@ static void unregister_translators(void)
 	AST_LIST_LOCK(&translators);
 	while ((cur = AST_LIST_REMOVE_HEAD(&translators, entry))) {
 		ast_unregister_translator(&cur->t);
-		free(cur);
+		ast_free(cur);
 	}
 	AST_LIST_UNLOCK(&translators);
 }
diff --git a/funcs/func_callerid.c b/funcs/func_callerid.c
index c8fd1bb9e2193d1cceb10dd6bea1ad8e8bc94b6c..462f887b5c2c17b54b94d63bef7ce9ebf9bad390 100644
--- a/funcs/func_callerid.c
+++ b/funcs/func_callerid.c
@@ -136,12 +136,12 @@ static int callerid_write(struct ast_channel *chan, const char *cmd, char *data,
 	} else if (!strncasecmp("dnid", data, 4)) {
 		/* do we need to lock chan here? */
 		if (chan->cid.cid_dnid)
-			free(chan->cid.cid_dnid);
+			ast_free(chan->cid.cid_dnid);
 		chan->cid.cid_dnid = ast_strdup(value);
 	} else if (!strncasecmp("rdnis", data, 5)) {
 		/* do we need to lock chan here? */
 		if (chan->cid.cid_rdnis)
-			free(chan->cid.cid_rdnis);
+			ast_free(chan->cid.cid_rdnis);
 		chan->cid.cid_rdnis = ast_strdup(value);
 	} else if (!strncasecmp("pres", data, 4)) {
 		int i;
diff --git a/funcs/func_curl.c b/funcs/func_curl.c
index f7b5ce75f96eb84bb431fb3d1847bb3337ecd2bb..38c63196c6e2f82f23135e972b197ebe50f3b190 100644
--- a/funcs/func_curl.c
+++ b/funcs/func_curl.c
@@ -160,7 +160,7 @@ static int acf_curl_exec(struct ast_channel *chan, const char *cmd, char *info,
 				chunk.memory[chunk.size - 1] = '\0';
 
 			ast_copy_string(buf, chunk.memory, len);
-			free(chunk.memory);
+			ast_free(chunk.memory);
 		}
 	} else {
 		ast_log(LOG_ERROR, "Cannot allocate curl structure\n");
diff --git a/funcs/func_devstate.c b/funcs/func_devstate.c
index cf6070521a78a2b4af249a766b84ed02773754a6..7125ca1b0f0609e5fd40ff068940f77b49f32659 100644
--- a/funcs/func_devstate.c
+++ b/funcs/func_devstate.c
@@ -187,7 +187,7 @@ static int unload_module(void)
 
 	AST_RWLIST_WRLOCK(&custom_devices);
 	while ((dev = AST_RWLIST_REMOVE_HEAD(&custom_devices, entry)))
-		free(dev);
+		ast_free(dev);
 	AST_RWLIST_UNLOCK(&custom_devices);
 
 	return res;
diff --git a/funcs/func_enum.c b/funcs/func_enum.c
index f0cbfba78dcf3d7909acc9e6a7cfe619e3176a1b..6e5e0c0d4a1a33197ba22fec850406908f396b9d 100644
--- a/funcs/func_enum.c
+++ b/funcs/func_enum.c
@@ -132,13 +132,13 @@ static void erds_destroy(struct enum_result_datastore *data)
 	int k;
 
 	for (k = 0; k < data->context->naptr_rrs_count; k++) {
-		free(data->context->naptr_rrs[k].result);
-		free(data->context->naptr_rrs[k].tech);
+		ast_free(data->context->naptr_rrs[k].result);
+		ast_free(data->context->naptr_rrs[k].tech);
 	}
 
-	free(data->context->naptr_rrs);
-	free(data->context);
-	free(data);
+	ast_free(data->context->naptr_rrs);
+	ast_free(data->context);
+	ast_free(data);
 }
 
 static void erds_destroy_cb(void *data) 
@@ -191,7 +191,7 @@ static int enum_query_read(struct ast_channel *chan, const char *cmd, char *data
 		goto finish;
 
 	if (!(erds->context = ast_calloc(1, sizeof(*erds->context)))) {
-		free(erds);
+		ast_free(erds);
 		goto finish;
 	}
 
@@ -200,8 +200,8 @@ static int enum_query_read(struct ast_channel *chan, const char *cmd, char *data
 	snprintf(buf, len, "%u", erds->id);
 
 	if (!(datastore = ast_channel_datastore_alloc(&enum_result_datastore_info, buf))) {
-		free(erds->context);
-		free(erds);
+		ast_free(erds->context);
+		ast_free(erds);
 		goto finish;
 	}
 
diff --git a/funcs/func_odbc.c b/funcs/func_odbc.c
index 3f22cf462639a3e1269737746d6c9dd69205b5ca..5206c2492e501e2536dc9b813522486cf444c239 100644
--- a/funcs/func_odbc.c
+++ b/funcs/func_odbc.c
@@ -603,7 +603,7 @@ static int init_acf_query(struct ast_config *cfg, char *catg, struct acf_odbc_qu
 		ast_copy_string((*query)->sql_read, tmp, sizeof((*query)->sql_read));
 
 	if (!ast_strlen_zero((*query)->sql_read) && ast_strlen_zero((*query)->readhandle[0])) {
-		free(*query);
+		ast_free(*query);
 		*query = NULL;
 		ast_log(LOG_ERROR, "There is SQL, but no ODBC class to be used for reading: %s\n", catg);
 		return EINVAL;
@@ -616,7 +616,7 @@ static int init_acf_query(struct ast_config *cfg, char *catg, struct acf_odbc_qu
 		ast_copy_string((*query)->sql_write, tmp, sizeof((*query)->sql_write));
 
 	if (!ast_strlen_zero((*query)->sql_write) && ast_strlen_zero((*query)->writehandle[0])) {
-		free(*query);
+		ast_free(*query);
 		*query = NULL;
 		ast_log(LOG_ERROR, "There is SQL, but no ODBC class to be used for writing: %s\n", catg);
 		return EINVAL;
@@ -638,7 +638,7 @@ static int init_acf_query(struct ast_config *cfg, char *catg, struct acf_odbc_qu
 
 	(*query)->acf = ast_calloc(1, sizeof(struct ast_custom_function));
 	if (! (*query)->acf) {
-		free(*query);
+		ast_free(*query);
 		*query = NULL;
 		return ENOMEM;
 	}
@@ -650,8 +650,8 @@ static int init_acf_query(struct ast_config *cfg, char *catg, struct acf_odbc_qu
 	}
 
 	if (!((*query)->acf->name)) {
-		free((*query)->acf);
-		free(*query);
+		ast_free((*query)->acf);
+		ast_free(*query);
 		*query = NULL;
 		return ENOMEM;
 	}
@@ -659,9 +659,9 @@ static int init_acf_query(struct ast_config *cfg, char *catg, struct acf_odbc_qu
 	asprintf((char **)&((*query)->acf->syntax), "%s(<arg1>[...[,<argN>]])", (*query)->acf->name);
 
 	if (!((*query)->acf->syntax)) {
-		free((char *)(*query)->acf->name);
-		free((*query)->acf);
-		free(*query);
+		ast_free((char *)(*query)->acf->name);
+		ast_free((*query)->acf);
+		ast_free(*query);
 		*query = NULL;
 		return ENOMEM;
 	}
@@ -691,19 +691,19 @@ static int init_acf_query(struct ast_config *cfg, char *catg, struct acf_odbc_qu
 					"This function may only be set.\nSQL:\n%s\n",
 					(*query)->sql_write);
 	} else {
-		free((char *)(*query)->acf->syntax);
-		free((char *)(*query)->acf->name);
-		free((*query)->acf);
-		free(*query);
+		ast_free((char *)(*query)->acf->syntax);
+		ast_free((char *)(*query)->acf->name);
+		ast_free((*query)->acf);
+		ast_free(*query);
 		ast_log(LOG_WARNING, "Section %s was found, but there was no SQL to execute.  Ignoring.\n", catg);
 		return EINVAL;
 	}
 
 	if (! ((*query)->acf->desc)) {
-		free((char *)(*query)->acf->syntax);
-		free((char *)(*query)->acf->name);
-		free((*query)->acf);
-		free(*query);
+		ast_free((char *)(*query)->acf->syntax);
+		ast_free((char *)(*query)->acf->name);
+		ast_free((*query)->acf);
+		ast_free(*query);
 		*query = NULL;
 		return ENOMEM;
 	}
@@ -728,14 +728,14 @@ static int free_acf_query(struct acf_odbc_query *query)
 	if (query) {
 		if (query->acf) {
 			if (query->acf->name)
-				free((char *)query->acf->name);
+				ast_free((char *)query->acf->name);
 			if (query->acf->syntax)
-				free((char *)query->acf->syntax);
+				ast_free((char *)query->acf->syntax);
 			if (query->acf->desc)
-				free((char *)query->acf->desc);
-			free(query->acf);
+				ast_free((char *)query->acf->desc);
+			ast_free(query->acf);
 		}
-		free(query);
+		ast_free(query);
 	}
 	return 0;
 }
diff --git a/funcs/func_strings.c b/funcs/func_strings.c
index 451c7b1f8f0fa8c430148452225232d41a723720..faf9ef0246ec577e443ff600bf77d224c6e45451 100644
--- a/funcs/func_strings.c
+++ b/funcs/func_strings.c
@@ -191,7 +191,7 @@ static void clearvar_prefix(struct ast_channel *chan, const char *prefix)
 	AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->varshead, var, entries) {
 		if (strncasecmp(prefix, ast_var_name(var), len) == 0) {
 			AST_LIST_REMOVE_CURRENT(&chan->varshead, entries);
-			free(var);
+			ast_free(var);
 		}
 	}
 	AST_LIST_TRAVERSE_SAFE_END
diff --git a/main/acl.c b/main/acl.c
index 55654f714c9ed84a6f0dbfdba213b5a6f42b70c2..3a88c3c1a6418a0c552ce6b67511f15663a9f057 100644
--- a/main/acl.c
+++ b/main/acl.c
@@ -90,7 +90,7 @@ void ast_free_ha(struct ast_ha *ha)
 	while (ha) {
 		hal = ha;
 		ha = ha->next;
-		free(hal);
+		ast_free(hal);
 	}
 }
 
@@ -174,14 +174,14 @@ struct ast_ha *ast_append_ha(char *sense, char *stuff, struct ast_ha *path, int
 			ast_log(LOG_WARNING, "%s is not a valid netmask\n", nm);
 			if (error)
 				*error = 1;
-			free(ha);
+			ast_free(ha);
 			return ret;
 		}
 		if (!inet_aton(tmp, &ha->netaddr)) {
 			ast_log(LOG_WARNING, "%s is not a valid IP\n", tmp);
 			if (error)
 				*error = 1;
-			free(ha);
+			ast_free(ha);
 			return ret;
 		}
 		ha->netaddr.s_addr &= ha->netmask.s_addr;
diff --git a/main/app.c b/main/app.c
index 32e36e9dfbc8f9c2c635f84e68a83910725d237e..b3fd264f14d1b5fdeb04fc86a07772a5ee989648 100644
--- a/main/app.c
+++ b/main/app.c
@@ -306,7 +306,7 @@ static void linear_release(struct ast_channel *chan, void *params)
 	}
 	if (ls->autoclose)
 		close(ls->fd);
-	free(params);
+	ast_free(params);
 }
 
 static int linear_generator(struct ast_channel *chan, void *data, int len, int samples)
@@ -349,7 +349,7 @@ static void *linear_alloc(struct ast_channel *chan, void *params)
 		ls->origwfmt = chan->writeformat;
 		if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
 			ast_log(LOG_WARNING, "Unable to set '%s' to linear format (write)\n", chan->name);
-			free(ls);
+			ast_free(ls);
 			ls = params = NULL;
 		}
 	}
@@ -844,7 +844,7 @@ int ast_app_group_set_channel(struct ast_channel *chan, const char *data)
 			break;
 	}
 	
-	if (!gi && (gi = calloc(1, len))) {
+	if (!gi && (gi = ast_calloc(1, len))) {
 		gi->chan = chan;
 		gi->group = (char *) gi + sizeof(*gi);
 		strcpy(gi->group, group);
@@ -927,7 +927,7 @@ int ast_app_group_discard(struct ast_channel *chan)
 	AST_LIST_TRAVERSE_SAFE_BEGIN(&groups, gi, list) {
 		if (gi->chan == chan) {
 			AST_LIST_REMOVE_CURRENT(&groups, list);
-			free(gi);
+			ast_free(gi);
 		}
 	}
         AST_LIST_TRAVERSE_SAFE_END
@@ -1378,7 +1378,7 @@ char *ast_read_textfile(const char *filename)
 			output[res] = '\0';
 		} else {
 			ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count - 1, strerror(errno));
-			free(output);
+			ast_free(output);
 			output = NULL;
 		}
 	}
diff --git a/main/asterisk.c b/main/asterisk.c
index 18a121339fcafce8ee2a4aa2c506d7d6a6d97df3..48a90ae82621d87e5f7d7bf7ee79921a7ca13892 100644
--- a/main/asterisk.c
+++ b/main/asterisk.c
@@ -294,7 +294,7 @@ void ast_unregister_file_version(const char *file)
 	AST_LIST_TRAVERSE_SAFE_END;
 	AST_LIST_UNLOCK(&file_versions);
 	if (find)
-		free(find);
+		ast_free(find);
 }
 
 struct thread_list_t {
@@ -336,8 +336,8 @@ void ast_unregister_thread(void *id)
 	AST_LIST_TRAVERSE_SAFE_END;
 	AST_LIST_UNLOCK(&thread_list);
 	if (x) {
-		free(x->name);
-		free(x);
+		ast_free(x->name);
+		ast_free(x);
 	}
 }
 
@@ -2036,7 +2036,7 @@ static int ast_cli_display_match_list(char **matches, int len, int max)
 			/* Don't print dupes */
 			if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
 				i--;
-				free(matches[idx]);
+				ast_free(matches[idx]);
 				matches[idx] = NULL;
 				continue;
 			}
@@ -2044,7 +2044,7 @@ static int ast_cli_display_match_list(char **matches, int len, int max)
 			numoutput++;
 			numoutputline++;
 			fprintf(stdout, "%-*s  ", max, matches[idx]);
-			free(matches[idx]);
+			ast_free(matches[idx]);
 			matches[idx] = NULL;
 		}
 		if (numoutputline > 0)
@@ -2113,7 +2113,7 @@ static char *cli_complete(EditLine *el, int ch)
 			mbuf[mlen] = '\0';
 
 			matches = ast_el_strtoarr(mbuf);
-			free(mbuf);
+			ast_free(mbuf);
 		} else
 			matches = (char **) NULL;
 	} else {
@@ -2159,8 +2159,8 @@ static char *cli_complete(EditLine *el, int ch)
 			}
 		}
 		for (i = 0; matches[i]; i++)
-			free(matches[i]);
-		free(matches);
+			ast_free(matches[i]);
+		ast_free(matches);
 	}
 
 	return (char *)(long)retval;
diff --git a/main/autoservice.c b/main/autoservice.c
index 29b915daa249fdedb08bfa9d6030ee867d5028e0..9ce49ac821b4d710c84f08e57ff1b7bcf693fd67 100644
--- a/main/autoservice.c
+++ b/main/autoservice.c
@@ -117,7 +117,7 @@ int ast_autoservice_start(struct ast_channel *chan)
 				/* There will only be a single member in the list at this point,
 				   the one we just added. */
 				AST_RWLIST_REMOVE(&aslist, as, list);
-				free(as);
+				ast_free(as);
 				res = -1;
 			} else
 				pthread_kill(asthread, SIGURG);
@@ -136,7 +136,7 @@ int ast_autoservice_stop(struct ast_channel *chan)
 	AST_RWLIST_TRAVERSE_SAFE_BEGIN(&aslist, as, list) {	
 		if (as->chan == chan) {
 			AST_RWLIST_REMOVE_CURRENT(&aslist, list);
-			free(as);
+			ast_free(as);
 			if (!chan->_softhangup)
 				res = 0;
 			break;
diff --git a/main/callerid.c b/main/callerid.c
index 74b8d9200a41c7e0d4a14b4d3b12e78380b1dbda..c870a462ff0a8ec20bba98a32ec9c0fde8134b99 100644
--- a/main/callerid.c
+++ b/main/callerid.c
@@ -683,7 +683,7 @@ int callerid_feed(struct callerid_state *cid, unsigned char *ubuf, int len, int
 
 void callerid_free(struct callerid_state *cid)
 {
-	free(cid);
+	ast_free(cid);
 }
 
 static int callerid_genmsg(char *msg, int size, const char *number, const char *name, int flags)
diff --git a/main/cdr.c b/main/cdr.c
index 7e3ab5bf953f164515dadf4a898b50243b0ca38f..76b5cfc1c321f6dd4ccae64525f02a0bff01ff7b 100644
--- a/main/cdr.c
+++ b/main/cdr.c
@@ -157,7 +157,7 @@ void ast_cdr_unregister(const char *name)
 			AST_LIST_REMOVE_CURRENT(&be_list, list);
 			if (option_verbose > 1)
 				ast_verbose(VERBOSE_PREFIX_2 "Unregistered '%s' CDR backend\n", name);
-			free(i);
+			ast_free(i);
 			break;
 		}
 	}
@@ -440,7 +440,7 @@ void ast_cdr_free(struct ast_cdr *cdr)
 			ast_log(LOG_NOTICE, "CDR on channel '%s' lacks start\n", chan);
 
 		ast_cdr_free_vars(cdr, 0);
-		free(cdr);
+		ast_free(cdr);
 		cdr = next;
 	}
 }
@@ -452,14 +452,15 @@ void ast_cdr_discard(struct ast_cdr *cdr)
 		struct ast_cdr *next = cdr->next;
 
 		ast_cdr_free_vars(cdr, 0);
-		free(cdr);
+		ast_free(cdr);
 		cdr = next;
 	}
 }
 
 struct ast_cdr *ast_cdr_alloc(void)
 {
-	struct ast_cdr *x = ast_calloc(1, sizeof(struct ast_cdr));
+	struct ast_cdr *x;
+	x = ast_calloc(1, sizeof(*x));
 	if (!x)
 		ast_log(LOG_ERROR,"Allocation Failure for a CDR!\n");
 	return x;
@@ -1024,7 +1025,7 @@ static void *do_batch_backend_process(void *data)
 		ast_cdr_free(batchitem->cdr);
 		processeditem = batchitem;
 		batchitem = batchitem->next;
-		free(processeditem);
+		ast_free(processeditem);
 	}
 
 	return NULL;
diff --git a/main/channel.c b/main/channel.c
index c0aa2326e8433c5d938adb2799353081dcb0c773..64ac4e58393e3f5ea72b9b623dead899ab9eebb3 100644
--- a/main/channel.c
+++ b/main/channel.c
@@ -458,7 +458,7 @@ void ast_channel_unregister(const struct ast_channel_tech *tech)
 	AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
 		if (chan->tech == tech) {
 			AST_LIST_REMOVE_CURRENT(&backends, list);
-			free(chan);
+			ast_free(chan);
 			if (option_verbose > 1)
 				ast_verbose(VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", tech->type);
 			break;	
@@ -648,13 +648,13 @@ struct ast_channel *ast_channel_alloc(int needqueue, int state, const char *cid_
 
 	if (!(tmp->sched = sched_context_create())) {
 		ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
-		free(tmp);
+		ast_free(tmp);
 		return NULL;
 	}
 	
 	if ((ast_string_field_init(tmp, 128))) {
 		sched_context_destroy(tmp->sched);
-		free(tmp);
+		ast_free(tmp);
 		return NULL;
 	}
 
@@ -681,7 +681,7 @@ struct ast_channel *ast_channel_alloc(int needqueue, int state, const char *cid_
 		if (pipe(tmp->alertpipe)) {
 			ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
 			ast_string_field_free_pools(tmp);
-			free(tmp);
+			ast_free(tmp);
 			return NULL;
 		} else {
 			flags = fcntl(tmp->alertpipe[0], F_GETFL);
@@ -1057,15 +1057,15 @@ int ast_safe_sleep(struct ast_channel *chan, int ms)
 static void free_cid(struct ast_callerid *cid)
 {
 	if (cid->cid_dnid)
-		free(cid->cid_dnid);
+		ast_free(cid->cid_dnid);
 	if (cid->cid_num)
-		free(cid->cid_num);	
+		ast_free(cid->cid_num);	
 	if (cid->cid_name)
-		free(cid->cid_name);	
+		ast_free(cid->cid_name);	
 	if (cid->cid_ani)
-		free(cid->cid_ani);
+		ast_free(cid->cid_ani);
 	if (cid->cid_rdnis)
-		free(cid->cid_rdnis);
+		ast_free(cid->cid_rdnis);
 	cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = cid->cid_rdnis = NULL;
 }
 
@@ -1092,7 +1092,7 @@ void ast_channel_free(struct ast_channel *chan)
 	ast_channel_unlock(chan);
 	if (chan->tech_pvt) {
 		ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
-		free(chan->tech_pvt);
+		ast_free(chan->tech_pvt);
 	}
 
 	if (chan->sched)
@@ -1149,7 +1149,7 @@ void ast_channel_free(struct ast_channel *chan)
 	ast_jb_destroy(chan);
 
 	ast_string_field_free_pools(chan);
-	free(chan);
+	ast_free(chan);
 	AST_LIST_UNLOCK(&channels);
 
 	ast_device_state_changed_literal(name);
@@ -1160,13 +1160,13 @@ struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_inf
 	struct ast_datastore *datastore = NULL;
 
 	/* Make sure we at least have type so we can identify this */
-	if (info == NULL) {
+	if (!info) {
 		return NULL;
 	}
 
 	/* Allocate memory for datastore and clear it */
 	datastore = ast_calloc(1, sizeof(*datastore));
-	if (datastore == NULL) {
+	if (!datastore) {
 		return NULL;
 	}
 
@@ -1194,7 +1194,7 @@ int ast_channel_datastore_free(struct ast_datastore *datastore)
 	}
 
 	/* Finally free memory used by ourselves */
-	free(datastore);
+	ast_free(datastore);
 
 	return res;
 }
@@ -1332,7 +1332,7 @@ static void spy_cleanup(struct ast_channel *chan)
 		ast_translator_free_path(chan->spies->read_translator.path);
 	if (chan->spies->write_translator.path)
 		ast_translator_free_path(chan->spies->write_translator.path);
-	free(chan->spies);
+	ast_free(chan->spies);
 	chan->spies = NULL;
 	return;
 }
@@ -2522,7 +2522,7 @@ int ast_recvchar(struct ast_channel *chan, int timeout)
 	if (buf == NULL)
 		return -1;	/* error or timeout */
 	c = *(unsigned char *)buf;
-	free(buf);
+	ast_free(buf);
 	return c;
 }
 
@@ -3702,17 +3702,17 @@ void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char
 {
 	if (callerid) {
 		if (chan->cid.cid_num)
-			free(chan->cid.cid_num);
+			ast_free(chan->cid.cid_num);
 		chan->cid.cid_num = ast_strdup(callerid);
 	}
 	if (calleridname) {
 		if (chan->cid.cid_name)
-			free(chan->cid.cid_name);
+			ast_free(chan->cid.cid_name);
 		chan->cid.cid_name = ast_strdup(calleridname);
 	}
 	if (ani) {
 		if (chan->cid.cid_ani)
-			free(chan->cid.cid_ani);
+			ast_free(chan->cid.cid_ani);
 		chan->cid.cid_ani = ast_strdup(ani);
 	}
 	if (chan->cdr)
@@ -4262,7 +4262,7 @@ static void tonepair_release(struct ast_channel *chan, void *params)
 
 	if (chan)
 		ast_set_write_format(chan, ts->origwfmt);
-	free(ts);
+	ast_free(ts);
 }
 
 static void *tonepair_alloc(struct ast_channel *chan, void *params)
@@ -4670,7 +4670,7 @@ struct ast_silence_generator *ast_channel_start_silence_generator(struct ast_cha
 
 	if (ast_set_write_format(chan, AST_FORMAT_SLINEAR) < 0) {
 		ast_log(LOG_ERROR, "Could not set write format to SLINEAR\n");
-		free(state);
+		ast_free(state);
 		return NULL;
 	}
 
@@ -4695,7 +4695,7 @@ void ast_channel_stop_silence_generator(struct ast_channel *chan, struct ast_sil
 	if (ast_set_write_format(chan, state->old_write_format) < 0)
 		ast_log(LOG_ERROR, "Could not return write format to its original state\n");
 
-	free(state);
+	ast_free(state);
 }
 
 
@@ -4925,6 +4925,6 @@ void ast_channel_whisper_stop(struct ast_channel *chan)
 		ast_set_write_format(chan, chan->whisper->original_format);
 	ast_slinfactory_destroy(&chan->whisper->sf);
 	ast_mutex_destroy(&chan->whisper->lock);
-	free(chan->whisper);
+	ast_free(chan->whisper);
 	chan->whisper = NULL;
 }
diff --git a/main/chanvars.c b/main/chanvars.c
index 7e617c1fb946819686e30e6ae6c3665d0648abe3..858933c9225c4ecc4051f90c656c5931d172e196 100644
--- a/main/chanvars.c
+++ b/main/chanvars.c
@@ -56,7 +56,7 @@ struct ast_var_t *ast_var_assign(const char *name, const char *value)
 void ast_var_delete(struct ast_var_t *var)
 {
 	if (var)
-		free(var);
+		ast_free(var);
 }
 
 const char *ast_var_name(const struct ast_var_t *var)
diff --git a/main/cli.c b/main/cli.c
index 91ab41f59c3a2018cbc75b7f6a2b6c3c14c52ae1..a3a2532c4c33457b6c0f51a7b9c449c8759e849e 100644
--- a/main/cli.c
+++ b/main/cli.c
@@ -626,19 +626,19 @@ static int handle_commandmatchesarray(int fd, int argc, char *argv[])
 				obuf = buf;
 				if (!(buf = ast_realloc(obuf, buflen))) 
 					/* Memory allocation failure...  Just free old buffer and be done */
-					free(obuf);
+					ast_free(obuf);
 			}
 			if (buf)
 				len += sprintf( buf + len, "%s ", matches[x]);
-			free(matches[x]);
+			ast_free(matches[x]);
 			matches[x] = NULL;
 		}
-		free(matches);
+		ast_free(matches);
 	}
 
 	if (buf) {
 		ast_cli(fd, "%s%s",buf, AST_CLI_COMPLETE_EOF);
-		free(buf);
+		ast_free(buf);
 	} else
 		ast_cli(fd, "NULL\n");
 
@@ -670,7 +670,7 @@ static int handle_commandcomplete(int fd, int argc, char *argv[])
 	buf = __ast_cli_generator(argv[2], argv[3], atoi(argv[4]), 0);
 	if (buf) {
 		ast_cli(fd, buf);
-		free(buf);
+		ast_free(buf);
 	} else
 		ast_cli(fd, "NULL\n");
 	return RESULT_SUCCESS;
@@ -1247,12 +1247,12 @@ static int __ast_cli_unregister(struct ast_cli_entry *e, struct ast_cli_entry *e
 		AST_LIST_LOCK(&helpers);
 		AST_LIST_REMOVE(&helpers, e, list);
 		AST_LIST_UNLOCK(&helpers);
-		free(e->_full_cmd);
+		ast_free(e->_full_cmd);
 		e->_full_cmd = NULL;
 		if (e->new_handler) {
 			/* this is a new-style entry. Reset fields and free memory. */
 			bzero((char **)(e->cmda), sizeof(e->cmda));
-			free(e->command);
+			ast_free(e->command);
 			e->command = NULL;
 			e->usage = NULL;
 		}
@@ -1291,7 +1291,7 @@ static int __ast_cli_register(struct ast_cli_entry *e, struct ast_cli_entry *ed)
 	
 	if (find_cli(e->cmda, 1)) {
 		ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n", e->_full_cmd);
-		free(e->_full_cmd);
+		ast_free(e->_full_cmd);
 		e->_full_cmd = NULL;
 		goto done;
 	}
@@ -1525,11 +1525,11 @@ int ast_cli_generatornummatches(const char *text, const char *word)
 		if (!oldbuf || strcmp(buf,oldbuf))
 			matches++;
 		if (oldbuf)
-			free(oldbuf);
+			ast_free(oldbuf);
 		oldbuf = buf;
 	}
 	if (oldbuf)
-		free(oldbuf);
+		ast_free(oldbuf);
 	return matches;
 }
 
@@ -1648,7 +1648,7 @@ static char *__ast_cli_generator(const char *text, const char *word, int state,
 			 */
 			if (matchnum > state)
 				break;
-			free(ret);
+			ast_free(ret);
 			ret = NULL;
 		} else if (ast_strlen_zero(e->cmda[dst])) {
 			/*
@@ -1671,7 +1671,7 @@ static char *__ast_cli_generator(const char *text, const char *word, int state,
 	}
 	if (lock)
 		AST_LIST_UNLOCK(&helpers);
-	free(dup);
+	ast_free(dup);
 	return ret;
 }
 
@@ -1745,6 +1745,6 @@ int ast_cli_command(int fd, const char *s)
 	}
 	ast_atomic_fetchadd_int(&e->inuse, -1);
 done:
-	free(dup);
+	ast_free(dup);
 	return 0;
 }
diff --git a/main/config.c b/main/config.c
index 50979b4313eda363e699968b321dd35c2ea88a45..54e899761d920ca8c846919f37c8f307cc6969cf 100644
--- a/main/config.c
+++ b/main/config.c
@@ -140,7 +140,8 @@ static void CB_RESET(char **comment_buffer, char **lline_buffer)
 
 static struct ast_comment *ALLOC_COMMENT(const char *buffer)
 { 
-	struct ast_comment *x = ast_calloc(1,sizeof(struct ast_comment)+strlen(buffer)+1);
+	struct ast_comment *x;
+	x = ast_calloc(1, sizeof(*x)+strlen(buffer)+1);
 	strcpy(x->cmt, buffer);
 	return x;
 }
@@ -215,7 +216,7 @@ void ast_variables_destroy(struct ast_variable *v)
 	while (v) {
 		vn = v;
 		v = v->next;
-		free(vn);
+		ast_free(vn);
 	}
 }
 
@@ -344,7 +345,7 @@ void ast_category_append(struct ast_config *config, struct ast_category *categor
 void ast_category_destroy(struct ast_category *cat)
 {
 	ast_variables_destroy(cat->root);
-	free(cat);
+	ast_free(cat);
 }
 
 static struct ast_category *next_available_category(struct ast_category *cat)
@@ -522,7 +523,7 @@ int ast_category_delete(struct ast_config *cfg, const char *category)
 				if (cat == cfg->last)
 					cfg->last = NULL;
 			}
-			free(cat);
+			ast_free(cat);
 			return 0;
 		}
 		prev = cat;
@@ -543,7 +544,7 @@ int ast_category_delete(struct ast_config *cfg, const char *category)
 				if (cat == cfg->last)
 					cfg->last = NULL;
 			}
-			free(cat);
+			ast_free(cat);
 			return 0;
 		}
 		prev = cat;
@@ -564,9 +565,9 @@ void ast_config_destroy(struct ast_config *cfg)
 		ast_variables_destroy(cat->root);
 		catn = cat;
 		cat = cat->next;
-		free(catn);
+		ast_free(catn);
 	}
-	free(cfg);
+	ast_free(cfg);
 }
 
 struct ast_category *ast_config_get_current_category(const struct ast_config *cfg)
@@ -934,8 +935,8 @@ static struct ast_config *config_text_file_load(const char *database, const char
 #endif
 
 	if (cfg && cfg->include_level == 1 && withcomments && comment_buffer) {
-		free(comment_buffer);
-		free(lline_buffer);
+		ast_free(comment_buffer);
+		ast_free(lline_buffer);
 		comment_buffer = NULL;
 		lline_buffer = NULL;
 		comment_buffer_size = 0;
@@ -1046,7 +1047,7 @@ static void clear_config_maps(void)
 	while (config_maps) {
 		map = config_maps;
 		config_maps = config_maps->next;
-		free(map);
+		ast_free(map);
 	}
 		
 	ast_mutex_unlock(&config_lock);
@@ -1345,7 +1346,7 @@ struct ast_variable *ast_load_realtime(const char *family, ...)
 	/* Eliminate blank entries */
 	for (cur = res; cur; cur = cur->next) {
 		if (freeme) {
-			free(freeme);
+			ast_free(freeme);
 			freeme = NULL;
 		}
 
diff --git a/main/db.c b/main/db.c
index 34041cba2412149194d0ddfad1eb18762f28bbc6..b7182e60cbafe8d157caa01418bed3f9d9399f68 100644
--- a/main/db.c
+++ b/main/db.c
@@ -466,7 +466,7 @@ void ast_db_freetree(struct ast_db_entry *dbe)
 	while (dbe) {
 		last = dbe;
 		dbe = dbe->next;
-		free(last);
+		ast_free(last);
 	}
 }
 
diff --git a/main/devicestate.c b/main/devicestate.c
index f8e1a337ac36569ebc1c2151f8c1477acf7c4d51..d682602d60dbcc6567e221cb00a87e2a2f28c692 100644
--- a/main/devicestate.c
+++ b/main/devicestate.c
@@ -339,7 +339,7 @@ int ast_devstate_prov_del(const char *label)
 	AST_RWLIST_TRAVERSE_SAFE_BEGIN(&devstate_provs, devcb, list) {
 		if (!strcasecmp(devcb->label, label)) {
 			AST_RWLIST_REMOVE_CURRENT(&devstate_provs, list);
-			free(devcb);
+			ast_free(devcb);
 			res = 0;
 			break;
 		}
@@ -463,7 +463,7 @@ static void *do_devstate_changes(void *data)
 		while ((current = next)) {
 			next = AST_LIST_NEXT(current, list);
 			do_state_change(current->device);
-			free(current);
+			ast_free(current);
 		}
 	}
 
diff --git a/main/dial.c b/main/dial.c
index 507eefcc379213d4da43c581061773aee9539026..8b804fdbb6712fe192195b808a9d767657f91a30 100644
--- a/main/dial.c
+++ b/main/dial.c
@@ -115,10 +115,10 @@ static int answer_exec_disable(void *data)
 
 	/* If arguments are present, free them too */
 	if (answer_exec->args)
-		free(answer_exec->args);
+		ast_free(answer_exec->args);
 
 	/* This is simple - just free the structure */
-	free(answer_exec);
+	ast_free(answer_exec);
 
 	return 0;
 }
@@ -133,7 +133,7 @@ static int music_disable(void *data)
 	if (!data)
 		return -1;
 
-	free(data);
+	ast_free(data);
 
 	return 0;
 }
@@ -707,7 +707,7 @@ int ast_dial_destroy(struct ast_dial *dial)
 			channel->owner = NULL;
 		}
 		/* Free structure */
-		free(channel);
+		ast_free(channel);
 	}
        
 	/* Disable any enabled options globally */
@@ -720,7 +720,7 @@ int ast_dial_destroy(struct ast_dial *dial)
 	}
 
 	/* Free structure */
-	free(dial);
+	ast_free(dial);
 
 	return 0;
 }
diff --git a/main/dlfcn.c b/main/dlfcn.c
index cc6fe40f92959743cb7833743451966cc5f7e7de..9a68b5c1930a59611b05b72a465590b03b84bee3 100644
--- a/main/dlfcn.c
+++ b/main/dlfcn.c
@@ -287,7 +287,7 @@ static const char *searchList()
 	if (!buf)
 	{	
 		buf_size = strlen(ldlp) + strlen(dyldlp) + strlen(stdpath) + 4;
-		buf = malloc(buf_size);
+		buf = ast_malloc(buf_size);
 		snprintf(buf, buf_size, "%s%s%s%s%s%c", dyldlp, (dyldlp[0] ? ":" : ""), ldlp, (ldlp[0] ? ":" : ""),
 				 stdpath, '\0');
 	}
@@ -309,18 +309,18 @@ static const char *getSearchPath(int i)
 	}
 	if (!path)
 	{
-		path = (char **)calloc(MAX_SEARCH_PATHS, sizeof(char **));
+		path = ast_calloc(MAX_SEARCH_PATHS, sizeof(char **));
 	}
 	if (!list && !end)
 		list = searchList();
 	if (i >= (numsize))
 	{
 		debug("Increasing size for long PATH");
-		tmp = (char **)calloc((MAX_SEARCH_PATHS + numsize), sizeof(char **));
+		tmp = ast_calloc((MAX_SEARCH_PATHS + numsize), sizeof(char **));
 		if (tmp)
 		{
 			memcpy(tmp, path, sizeof(char **) * numsize);
-			free(path);
+			ast_free(path);
 			path = tmp;
 			numsize += MAX_SEARCH_PATHS;
 		}
@@ -434,7 +434,7 @@ static struct dlstatus *allocStatus()
 		dls = dls->next;
 	if (!dls)
 #endif
-		dls = malloc(sizeof(*dls));
+		dls = ast_malloc(sizeof(*dls));
 	dls->flags = 0;
 	return dls;
 }
@@ -551,7 +551,7 @@ static inline const char *dyld_error_str()
 	NSLinkEditError(&dylder, &dylderno, &dyldfile, &dylderrstr);
 	if (dylderrstr && strlen(dylderrstr))
 	{
-		retStr = malloc(strlen(dylderrstr) +1);
+		retStr = ast_malloc(strlen(dylderrstr) +1);
 		strcpy((char*)retStr,dylderrstr);
 	}
 	return retStr;
@@ -651,8 +651,8 @@ static void *dlsymIntern(struct dlstatus *dls, const char *symbol, int canSetErr
 			else
 			{
 				if (savedErrorStr)
-					free((char*)savedErrorStr);			
-				savedErrorStr = malloc(256);
+					ast_free(savedErrorStr);			
+				savedErrorStr = ast_malloc(256);
 				snprintf((char*)savedErrorStr, 256, "Symbol \"%s\" not in global context",symbol);	
 			}
 		}
@@ -663,8 +663,8 @@ static void *dlsymIntern(struct dlstatus *dls, const char *symbol, int canSetErr
 		if (!savedErrorStr || !strlen(savedErrorStr))
 		{
 			if (savedErrorStr)
-				free((char*)savedErrorStr);
-			savedErrorStr = malloc(256);
+				ast_free(savedErrorStr);
+			savedErrorStr = ast_malloc(256);
 			snprintf((char*)savedErrorStr, 256,"Symbol \"%s\" not found",symbol);
 		}
 		if (canSetError)
@@ -676,7 +676,7 @@ static void *dlsymIntern(struct dlstatus *dls, const char *symbol, int canSetErr
 			debug(savedErrorStr);
 		}
 		if (savedErrorStr)
-			free((char*)savedErrorStr);
+			ast_free(savedErrorStr);
 		return NULL;
 	}
 	return NSAddressOfSymbol(nssym);
@@ -760,7 +760,7 @@ static struct dlstatus *loadModule(const char *path, const struct stat *sbuf, in
 				error(errstr);
 			if ((dls->flags & DL_IN_LIST) == 0)
 			{
-				free(dls);
+				ast_free(dls);
 			}
 			return NULL;
 		}
@@ -782,7 +782,7 @@ static struct dlstatus *loadModule(const char *path, const struct stat *sbuf, in
 		NSLinkEditError(&ler, &lerno, &file, &errstr);
 		if ((dls->flags & DL_IN_LIST) == 0)
 		{
-			free(dls);
+			ast_free(dls);
 		}
 		error(errstr);
 		return NULL;
@@ -828,10 +828,10 @@ static void dlcompat_cleanup(void)
 	char *data;
 	data = (char *)searchList();
 	if ( data )
-		free( data );
+		ast_free(data);
 	data = 	(char *)getSearchPath(-1);
 	if ( data )
-		free( data );
+		ast_free(data);
 	pthread_mutex_destroy(&dlcompat_mutex);
 	pthread_key_delete(dlerror_key);
 	next = stqueue;
@@ -839,7 +839,7 @@ static void dlcompat_cleanup(void)
 	{
 		dls = next;
 		next = dls->next;
-		free(dls);
+		ast_free(dls);
 	}
 }
 
@@ -852,7 +852,7 @@ static void resetdlerror()
 
 static void dlerrorfree(void *data)
 {
-	free(data);
+	ast_free(data);
 }
 
 /* We kind of want a recursive lock here, but meet a little trouble
@@ -866,7 +866,7 @@ static inline void dolock(void)
 	tss = pthread_getspecific(dlerror_key);
 	if (!tss)
 	{
-		tss = malloc(sizeof(struct dlthread));
+		tss = ast_malloc(sizeof(*tss));
 		tss->lockcnt = 0;
 		tss->errset = 0;
 		if (pthread_setspecific(dlerror_key, tss))
@@ -948,12 +948,12 @@ void *dlsym(void * dl_restrict handle, const char * dl_restrict symbol)
 	void *value = NULL;
 	char *malloc_sym = NULL;
 	dolock();
-	malloc_sym = malloc(sym_len + 2);
+	malloc_sym = ast_malloc(sym_len + 2);
 	if (malloc_sym)
 	{
 		sprintf(malloc_sym, "_%s", symbol);
 		value = dlsymIntern(handle, malloc_sym, 1);
-		free(malloc_sym);
+		ast_free(malloc_sym);
 	}
 	else
 	{
@@ -993,12 +993,12 @@ static void *dlsym_prepend_underscore_intern(void *handle, const char *symbol)
 	int sym_len = strlen(symbol);
 	void *value = NULL;
 	char *malloc_sym = NULL;
-	malloc_sym = malloc(sym_len + 2);
+	malloc_sym = ast_malloc(sym_len + 2);
 	if (malloc_sym)
 	{
 		sprintf(malloc_sym, "_%s", symbol);
 		value = dlsymIntern(handle, malloc_sym, 1);
-		free(malloc_sym);
+		ast_free(malloc_sym);
 	}
 	else
 	{
@@ -1293,12 +1293,12 @@ dlfunc_t dlfunc(void * dl_restrict handle, const char * dl_restrict symbol)
 	int sym_len = strlen(symbol);
 	char *malloc_sym = NULL;
 	dolock();
-	malloc_sym = malloc(sym_len + 2);
+	malloc_sym = ast_malloc(sym_len + 2);
 	if (malloc_sym)
 	{
 		sprintf(malloc_sym, "_%s", symbol);
 		rv.d = dlsymIntern(handle, malloc_sym, 1);
-		free(malloc_sym);
+		ast_free(malloc_sym);
 	}
 	else
 	{
diff --git a/main/dnsmgr.c b/main/dnsmgr.c
index 59c3a9994edea04c8621ae6bd56d3704f308e382..1c5eb050b21ef2cd98e7fd2e6b3a2f5de81aefb3 100644
--- a/main/dnsmgr.c
+++ b/main/dnsmgr.c
@@ -116,7 +116,7 @@ void ast_dnsmgr_release(struct ast_dnsmgr_entry *entry)
 		ast_verbose(VERBOSE_PREFIX_4 "removing dns manager for '%s'\n", entry->name);
 
 	ast_mutex_destroy(&entry->lock);
-	free(entry);
+	ast_free(entry);
 }
 
 int ast_dnsmgr_lookup(const char *name, struct in_addr *result, struct ast_dnsmgr_entry **dnsmgr)
diff --git a/main/dsp.c b/main/dsp.c
index 3d0712bc132c4e6e0e3de6f89ee1bf2e7b9cfbc7..9519c56ccdad87a9174180ade4b2a2c65b715cb9 100644
--- a/main/dsp.c
+++ b/main/dsp.c
@@ -1625,7 +1625,7 @@ void ast_dsp_set_features(struct ast_dsp *dsp, int features)
 
 void ast_dsp_free(struct ast_dsp *dsp)
 {
-	free(dsp);
+	ast_free(dsp);
 }
 
 void ast_dsp_set_threshold(struct ast_dsp *dsp, int threshold)
diff --git a/main/enum.c b/main/enum.c
index 140a38ff984cd6f069f4a4cb8fdb7b017eaa9c07..a860dcb4ca787ebf8e28ac9731adc37975d8aea5 100644
--- a/main/enum.c
+++ b/main/enum.c
@@ -443,7 +443,7 @@ int ast_get_enum(struct ast_channel *chan, const char *number, char *dst, int ds
 	}
 
 	if (chan && ast_autoservice_start(chan) < 0) {
-		free(context);
+		ast_free(context);
 		return -1;
 	}
 
@@ -523,11 +523,11 @@ int ast_get_enum(struct ast_channel *chan, const char *number, char *dst, int ds
 
 	if (!argcontext) {
 		for (k = 0; k < context->naptr_rrs_count; k++) {
-			free(context->naptr_rrs[k].result);
-			free(context->naptr_rrs[k].tech);
+			ast_free(context->naptr_rrs[k].result);
+			ast_free(context->naptr_rrs[k].tech);
 		}
-		free(context->naptr_rrs);
-		free(context);
+		ast_free(context->naptr_rrs);
+		ast_free(context);
 	} else
 		*argcontext = context;
 
@@ -622,7 +622,7 @@ int ast_enum_init(void)
 	while (s) {
 		sl = s;
 		s = s->next;
-		free(sl);
+		ast_free(sl);
 	}
 	toplevs = NULL;
 	cfg = ast_config_load("enum.conf");
diff --git a/main/event.c b/main/event.c
index ffa2912b094e5e8ffe2668b1fd3b53383517505d..905790614fb7850c8e9c2b5ee0cd8cbca6c51dfa 100644
--- a/main/event.c
+++ b/main/event.c
@@ -109,9 +109,9 @@ static AST_RWLIST_HEAD(ast_event_ref_list, ast_event_ref) ast_event_cache[AST_EV
 static void ast_event_ie_val_destroy(struct ast_event_ie_val *ie_val)
 {
 	if (ie_val->ie_pltype == AST_EVENT_IE_PLTYPE_STR)
-		free((void *) ie_val->payload.str);
+		ast_free((void *) ie_val->payload.str);
 
-	free(ie_val);
+	ast_free(ie_val);
 }
 
 enum ast_event_subscriber_res ast_event_check_subscriber(enum ast_event_type type, ...)
@@ -270,7 +270,7 @@ struct ast_event_sub *ast_event_subscribe(enum ast_event_type type, ast_event_cb
 			ie_val->payload.uint = va_arg(ap, uint32_t);
 		else if (ie_val->ie_pltype == AST_EVENT_IE_PLTYPE_STR) {
 			if (!(ie_val->payload.str = ast_strdup(va_arg(ap, const char *)))) {
-				free(ie_val);
+				ast_free(ie_val);
 				continue;
 			}
 		}
@@ -327,7 +327,7 @@ static void ast_event_sub_destroy(struct ast_event_sub *sub)
 	while ((ie_val = AST_LIST_REMOVE_HEAD(&sub->ie_vals, entry)))
 		ast_event_ie_val_destroy(ie_val);
 
-	free(sub);
+	ast_free(sub);
 }
 
 void ast_event_unsubscribe(struct ast_event_sub *sub)
@@ -481,13 +481,13 @@ struct ast_event *ast_event_new(enum ast_event_type type, ...)
 
 void ast_event_destroy(struct ast_event *event)
 {
-	free(event);
+	ast_free(event);
 }
 
 static void ast_event_ref_destroy(struct ast_event_ref *event_ref)
 {
 	ast_event_destroy(event_ref->event);
-	free(event_ref);
+	ast_free(event_ref);
 }
 
 static struct ast_event *ast_event_dup(const struct ast_event *event)
diff --git a/main/file.c b/main/file.c
index 038dd5f3a96e68850988ab18316b9eae1bb63a79..a7c5bfe93c0994012fafcdcddd57cfe86532a048 100644
--- a/main/file.c
+++ b/main/file.c
@@ -112,7 +112,7 @@ int ast_format_unregister(const char *name)
 	AST_RWLIST_TRAVERSE_SAFE_BEGIN(&formats, tmp, list) {
 		if (!strcasecmp(name, tmp->name)) {
 			AST_RWLIST_REMOVE_CURRENT(&formats, list);
-			free(tmp);
+			ast_free(tmp);
 			res = 0;
 		}
 	}
@@ -372,7 +372,7 @@ static int ast_filehelper(const char *filename, const void *arg2, const char *fm
 				continue;
 
 			if ( stat(fn, &st) ) { /* file not existent */
-				free(fn);
+				ast_free(fn);
 				continue;
 			}
 			/* for 'OPEN' we need to be sure that the format matches
@@ -385,23 +385,23 @@ static int ast_filehelper(const char *filename, const void *arg2, const char *fm
 
 				if ( !(chan->writeformat & f->format) &&
 				     !(f->format >= AST_FORMAT_MAX_AUDIO && fmt)) {
-					free(fn);
+					ast_free(fn);
 					continue;	/* not a supported format */
 				}
 				if ( (bfile = fopen(fn, "r")) == NULL) {
-					free(fn);
+					ast_free(fn);
 					continue;	/* cannot open file */
 				}
 				s = get_filestream(f, bfile);
 				if (!s) {
 					fclose(bfile);
-					free(fn);	/* cannot allocate descriptor */
+					ast_free(fn);	/* cannot allocate descriptor */
 					continue;
 				}
 				if (open_wrapper(s)) {
 					fclose(bfile);
-					free(fn);
-					free(s);
+					ast_free(fn);
+					ast_free(s);
 					continue;	/* cannot run open on file */
 				}
 				/* ok this is good for OPEN */
@@ -419,7 +419,7 @@ static int ast_filehelper(const char *filename, const void *arg2, const char *fm
 						ast_closestream(chan->vstream);
 					chan->vstream = s;
 				}
-				free(fn);
+				ast_free(fn);
 				break;
 			}
 			switch (action) {
@@ -446,7 +446,7 @@ static int ast_filehelper(const char *filename, const void *arg2, const char *fm
 						ast_log(LOG_WARNING, "%s(%s,%s) failed: %s\n",
 							action == ACTION_COPY ? "copy" : "rename",
 							 fn, nfn, strerror(errno));
-					free(nfn);
+					ast_free(nfn);
 				}
 			    }
 				break;
@@ -454,7 +454,7 @@ static int ast_filehelper(const char *filename, const void *arg2, const char *fm
 			default:
 				ast_log(LOG_WARNING, "Unknown helper %d\n", action);
 			}
-			free(fn);
+			ast_free(fn);
 		}
 	}
 	AST_RWLIST_UNLOCK(&formats);
@@ -732,16 +732,16 @@ int ast_closestream(struct ast_filestream *f)
 	}
 
 	if (f->filename)
-		free(f->filename);
+		ast_free(f->filename);
 	if (f->realfilename)
-		free(f->realfilename);
+		ast_free(f->realfilename);
 	if (f->fmt->close)
 		f->fmt->close(f);
 	fclose(f->f);
 	if (f->vfs)
 		ast_closestream(f->vfs);
 	ast_module_unref(f->fmt->module);
-	free(f);
+	ast_free(f);
 	return 0;
 }
 
@@ -833,7 +833,7 @@ struct ast_filestream *ast_readfile(const char *filename, const char *type, cons
 				ast_free(fs);
 			if (bfile)
 				fclose(bfile);
-			free(fn);
+			ast_free(fn);
 			continue;
 		}
 		/* found it */
@@ -919,7 +919,7 @@ struct ast_filestream *ast_writefile(const char *filename, const char *type, con
 			strcpy(buf, record_cache_dir);
 			strcat(buf, "/");
 			strcat(buf, fn);
-			free(fn);
+			ast_free(fn);
 			fn = buf;
 			fd = open(fn, flags | myflags, mode);
 			if (fd > -1) {
@@ -966,7 +966,7 @@ struct ast_filestream *ast_writefile(const char *filename, const char *type, con
 		}
 		/* if buf != NULL then fn is already free and pointing to it */
 		if (!buf)
-			free(fn);
+			ast_free(fn);
 	}
 
 	AST_RWLIST_UNLOCK(&formats);
diff --git a/main/fixedjitterbuf.c b/main/fixedjitterbuf.c
index 1d7a5cc301f71f0d0a78c61b1fdb8d33eef6c18a..a9d0f870789331ac86b74f228cb3142b7198ec9d 100644
--- a/main/fixedjitterbuf.c
+++ b/main/fixedjitterbuf.c
@@ -66,12 +66,12 @@ static int resynch_jb(struct fixed_jb *jb, void *data, long ms, long ts, long no
 
 static inline struct fixed_jb_frame *alloc_jb_frame(struct fixed_jb *jb)
 {
-	return ast_calloc(1, sizeof(struct fixed_jb_frame));
+	return ast_calloc(1, sizeof(*jb));
 }
 
 static inline void release_jb_frame(struct fixed_jb *jb, struct fixed_jb_frame *frame)
 {
-	free(frame);
+	ast_free(frame);
 }
 
 static void get_jb_head(struct fixed_jb *jb, struct fixed_jb_frame *frame)
@@ -131,7 +131,7 @@ void fixed_jb_destroy(struct fixed_jb *jb)
 	/* jitterbuf MUST be empty before it can be destroyed */
 	ASSERT(jb->frames == NULL);
 	
-	free(jb);
+	ast_free(jb);
 }
 
 
diff --git a/main/frame.c b/main/frame.c
index 068d46e46a06bb0e9de3cf72e89eeae09671b79c..8f30e4b7e2ca91d227ddd8291984702b7c93e06f 100644
--- a/main/frame.c
+++ b/main/frame.c
@@ -285,7 +285,7 @@ struct ast_frame *ast_smoother_read(struct ast_smoother *s)
 
 void ast_smoother_free(struct ast_smoother *s)
 {
-	free(s);
+	ast_free(s);
 }
 
 static struct ast_frame *ast_frame_header_new(void)
@@ -330,9 +330,9 @@ static void frame_cache_cleanup(void *data)
 	struct ast_frame *f;
 
 	while ((f = AST_LIST_REMOVE_HEAD(&frames->list, frame_list)))
-		free(f);
+		ast_free(f);
 	
-	free(frames);
+	ast_free(frames);
 }
 #endif
 
@@ -358,11 +358,11 @@ void ast_frame_free(struct ast_frame *fr, int cache)
 	
 	if (fr->mallocd & AST_MALLOCD_DATA) {
 		if (fr->data) 
-			free(fr->data - fr->offset);
+			ast_free(fr->data - fr->offset);
 	}
 	if (fr->mallocd & AST_MALLOCD_SRC) {
 		if (fr->src)
-			free((char *)fr->src);
+			ast_free((char *)fr->src);
 	}
 	if (fr->mallocd & AST_MALLOCD_HDR) {
 #ifdef TRACE_FRAMES
@@ -371,7 +371,7 @@ void ast_frame_free(struct ast_frame *fr, int cache)
 		AST_LIST_REMOVE(&headerlist, fr, frame_list);
 		AST_LIST_UNLOCK(&headerlist);
 #endif			
-		free(fr);
+		ast_free(fr);
 	}
 }
 
@@ -409,7 +409,7 @@ struct ast_frame *ast_frisolate(struct ast_frame *fr)
 		if (fr->src) {
 			if (!(out->src = ast_strdup(fr->src))) {
 				if (out != fr)
-					free(out);
+					ast_free(out);
 				return NULL;
 			}
 		}
@@ -419,9 +419,9 @@ struct ast_frame *ast_frisolate(struct ast_frame *fr)
 	if (!(fr->mallocd & AST_MALLOCD_DATA))  {
 		if (!(newdata = ast_malloc(fr->datalen + AST_FRIENDLY_OFFSET))) {
 			if (out->src != fr->src)
-				free((void *) out->src);
+				ast_free((void *) out->src);
 			if (out != fr)
-				free(out);
+				ast_free(out);
 			return NULL;
 		}
 		newdata += AST_FRIENDLY_OFFSET;
diff --git a/main/http.c b/main/http.c
index 5d652b8dcc8f3d7757922e40f1614a555b4a2e31..2967298e7b89a54fd37a2b0d27c454b27e20dcd0 100644
--- a/main/http.c
+++ b/main/http.c
@@ -206,7 +206,7 @@ static struct ast_str *static_callback(struct sockaddr_in *req, const char *uri,
 	*contentlength = read(fd, result->str + result->used, st.st_size);
 	if (*contentlength < 0) {
 		close(fd);
-		free(result);
+		ast_free(result);
 		goto out403;
 	}
 	result->used += *contentlength;
@@ -747,7 +747,7 @@ static void *make_file_from_fd(void *data)
 	if (!ser->f) {
 		close(ser->fd);
 		ast_log(LOG_WARNING, "FILE * open failed!\n");
-		free(ser);
+		ast_free(ser);
 		return NULL;
 	}
 	return ser->parent->worker_fn(ser);
@@ -888,14 +888,14 @@ static void *httpd_helper_thread(void *data)
 				fwrite(tmp + 4, 1, contentlength, ser->f);
 			}
 		}
-		free(out);
+		ast_free(out);
 	}
 	if (title)
-		free(title);
+		ast_free(title);
 
 done:
 	fclose(ser->f);
-	free(ser);
+	ast_free(ser);
 	return NULL;
 }
 
@@ -938,7 +938,7 @@ void *server_root(void *data)
 		if (ast_pthread_create_detached_background(&launched, NULL, make_file_from_fd, ser)) {
 			ast_log(LOG_WARNING, "Unable to launch helper thread: %s\n", strerror(errno));
 			close(ser->fd);
-			free(ser);
+			ast_free(ser);
 		}
 
 	}
@@ -1107,10 +1107,10 @@ static void add_redirect(const char *value)
 static void destroy_post_mapping(struct ast_http_post_mapping *post_map)
 {
 	if (post_map->from)
-		free(post_map->from);
+		ast_free(post_map->from);
 	if (post_map->to)
-		free(post_map->to);
-	free(post_map);
+		ast_free(post_map->to);
+	ast_free(post_map);
 }
 
 static void destroy_post_mappings(void)
@@ -1168,15 +1168,15 @@ static int __ast_http_load(int reload)
 
 	http_tls_cfg.enabled = 0;
 	if (http_tls_cfg.certfile)
-		free(http_tls_cfg.certfile);
+		ast_free(http_tls_cfg.certfile);
 	http_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
 	if (http_tls_cfg.cipher)
-		free(http_tls_cfg.cipher);
+		ast_free(http_tls_cfg.cipher);
 	http_tls_cfg.cipher = ast_strdup("");
 
 	AST_RWLIST_WRLOCK(&uri_redirects);
 	while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry)))
-		free(redirect);
+		ast_free(redirect);
 	AST_RWLIST_UNLOCK(&uri_redirects);
 
 	destroy_post_mappings();
@@ -1192,10 +1192,10 @@ static int __ast_http_load(int reload)
 			else if (!strcasecmp(v->name, "sslbindport"))
 				https_desc.sin.sin_port = htons(atoi(v->value));
 			else if (!strcasecmp(v->name, "sslcert")) {
-				free(http_tls_cfg.certfile);
+				ast_free(http_tls_cfg.certfile);
 				http_tls_cfg.certfile = ast_strdup(v->value);
 			} else if (!strcasecmp(v->name, "sslcipher")) {
-				free(http_tls_cfg.cipher);
+				ast_free(http_tls_cfg.cipher);
 				http_tls_cfg.cipher = ast_strdup(v->value);
 			}
 			else if (!strcasecmp(v->name, "enablestatic"))
diff --git a/main/indications.c b/main/indications.c
index c58a51660df0f0fea1a3c35f58e6fbd8915bc9da..cc714707f5f3b35e095341b8118d08b91ea6f079 100644
--- a/main/indications.c
+++ b/main/indications.c
@@ -108,9 +108,9 @@ static void playtones_release(struct ast_channel *chan, void *params)
 	if (chan)
 		ast_set_write_format(chan, ps->origwfmt);
 	if (ps->items)
-		free(ps->items);
+		ast_free(ps->items);
 
-	free(ps);
+	ast_free(ps);
 }
 
 static void * playtones_alloc(struct ast_channel *chan, void *params)
@@ -324,7 +324,7 @@ int ast_playtones_start(struct ast_channel *chan, int vol, const char *playlst,
 	}
 
 	if (ast_activate_generator(chan, &playtones, &d)) {
-		free(d.items);
+		ast_free(d.items);
 		return -1;
 	}
 	return 0;
@@ -453,16 +453,16 @@ static inline void free_zone(struct ind_tone_zone* zone)
 {
 	while (zone->tones) {
 		struct ind_tone_zone_sound *tmp = zone->tones->next;
-		free((void*)zone->tones->name);
-		free((void*)zone->tones->data);
-		free(zone->tones);
+		ast_free((void *)zone->tones->name);
+		ast_free((void *)zone->tones->data);
+		ast_free(zone->tones);
 		zone->tones = tmp;
 	}
 
 	if (zone->ringcadence)
-		free(zone->ringcadence);
+		ast_free(zone->ringcadence);
 
-	free(zone);
+	ast_free(zone);
 }
 
 /*--------------------------------------------*/
@@ -543,8 +543,8 @@ int ast_register_indication(struct ind_tone_zone *zone, const char *indication,
 	for (ps=NULL,ts=zone->tones; ts; ps=ts,ts=ts->next) {
 		if (strcasecmp(indication,ts->name)==0) {
 			/* indication already there, replace */
-			free((void*)ts->name);
-			free((void*)ts->data);
+			ast_free((void*)ts->name);
+			ast_free((void*)ts->data);
 			break;
 		}
 	}
@@ -588,9 +588,9 @@ int ast_unregister_indication(struct ind_tone_zone *zone, const char *indication
 				ps->next = tmp;
 			else
 				zone->tones = tmp;
-			free((void*)ts->name);
-			free((void*)ts->data);
-			free(ts);
+			ast_free((void*)ts->name);
+			ast_free((void*)ts->data);
+			ast_free(ts);
 			ts = tmp;
 			res = 0;
 		}
diff --git a/main/io.c b/main/io.c
index 209f279264f3be5064ba5e68c39024a2c89e1b8b..a2ab1663590ab788270a68df56627d81c56967c7 100644
--- a/main/io.c
+++ b/main/io.c
@@ -87,12 +87,12 @@ struct io_context *io_context_create(void)
 	tmp->current_ioc = -1;
 	
 	if (!(tmp->fds = ast_calloc(1, (GROW_SHRINK_SIZE / 2) * sizeof(*tmp->fds)))) {
-		free(tmp);
+		ast_free(tmp);
 		tmp = NULL;
 	} else {
 		if (!(tmp->ior = ast_calloc(1, (GROW_SHRINK_SIZE / 2) * sizeof(*tmp->ior)))) {
-			free(tmp->fds);
-			free(tmp);
+			ast_free(tmp->fds);
+			ast_free(tmp);
 			tmp = NULL;
 		}
 	}
@@ -104,11 +104,11 @@ void io_context_destroy(struct io_context *ioc)
 {
 	/* Free associated memory with an I/O context */
 	if (ioc->fds)
-		free(ioc->fds);
+		ast_free(ioc->fds);
 	if (ioc->ior)
-		free(ioc->ior);
+		ast_free(ioc->ior);
 
-	free(ioc);
+	ast_free(ioc);
 }
 
 /*! \brief
@@ -250,7 +250,7 @@ int ast_io_remove(struct io_context *ioc, int *_id)
 	for (x = 0; x < ioc->fdcnt; x++) {
 		if (ioc->ior[x].id == _id) {
 			/* Free the int immediately and set to NULL so we know it's unused now */
-			free(ioc->ior[x].id);
+			ast_free(ioc->ior[x].id);
 			ioc->ior[x].id = NULL;
 			ioc->fds[x].events = 0;
 			ioc->fds[x].revents = 0;
diff --git a/main/jitterbuf.c b/main/jitterbuf.c
index f41e0d38274df5bdbac8e3852534f1c3b1b97912..177e2e625237ee1a3be915ff4f45f8c371b9ae93 100644
--- a/main/jitterbuf.c
+++ b/main/jitterbuf.c
@@ -106,12 +106,12 @@ void jb_destroy(jitterbuf *jb)
 	frame = jb->free;
 	while (frame != NULL) {
 		jb_frame *next = frame->next;
-		free(frame);
+		ast_free(frame);
 		frame = next;
 	}
 
 	/* free ourselves! */ 
-	free(jb);
+	ast_free(jb);
 }
 
 
diff --git a/main/loader.c b/main/loader.c
index c1b7597c914c328a8f125a0e54d5f055548d72fd..060243ccc0f5cb8840a69ae64f6abe138cc51702 100644
--- a/main/loader.c
+++ b/main/loader.c
@@ -170,7 +170,7 @@ void ast_module_unregister(const struct ast_module_info *info)
 
 	if (mod) {
 		AST_LIST_HEAD_DESTROY(&mod->users);
-		free(mod);
+		ast_free(mod);
 	}
 }
 
@@ -201,7 +201,7 @@ void __ast_module_user_remove(struct ast_module *mod, struct ast_module_user *u)
 	AST_LIST_REMOVE(&mod->users, u, entry);
 	AST_LIST_UNLOCK(&mod->users);
 	ast_atomic_fetchadd_int(&mod->usecount, -1);
-	free(u);
+	ast_free(u);
 
 	ast_update_use_count();
 }
@@ -214,7 +214,7 @@ void __ast_module_user_hangup_all(struct ast_module *mod)
 	while ((u = AST_LIST_REMOVE_HEAD(&mod->users, entry))) {
 		ast_softhangup(u->chan, AST_SOFTHANGUP_APPUNLOAD);
 		ast_atomic_fetchadd_int(&mod->usecount, -1);
-		free(u);
+		ast_free(u);
 	}
 	AST_LIST_UNLOCK(&mod->users);
 
@@ -359,7 +359,7 @@ static struct ast_module *load_dynamic_module(const char *resource_in, unsigned
 
 	if (!(lib = dlopen(fn, RTLD_LAZY | RTLD_LOCAL))) {
 		ast_log(LOG_WARNING, "Error loading module '%s': %s\n", resource_in, dlerror());
-		free(resource_being_loaded);
+		ast_free(resource_being_loaded);
 		return NULL;
 	}
 
@@ -396,7 +396,7 @@ static struct ast_module *load_dynamic_module(const char *resource_in, unsigned
 	if (!dlopen(fn, RTLD_NOLOAD | (wants_global ? RTLD_LAZY | RTLD_GLOBAL : RTLD_NOW | RTLD_LOCAL))) {
 		ast_log(LOG_WARNING, "Unable to promote flags on module '%s': %s\n", resource_in, dlerror());
 		while (!dlclose(lib));
-		free(resource_being_loaded);
+		ast_free(resource_being_loaded);
 		return NULL;
 	}
 #else
@@ -412,7 +412,7 @@ static struct ast_module *load_dynamic_module(const char *resource_in, unsigned
 
 	if (!(lib = dlopen(fn, wants_global ? RTLD_LAZY | RTLD_GLOBAL : RTLD_NOW | RTLD_LOCAL))) {
 		ast_log(LOG_WARNING, "Error loading module '%s': %s\n", resource_in, dlerror());
-		free(resource_being_loaded);
+		ast_free(resource_being_loaded);
 		return NULL;
 	}
 
@@ -816,8 +816,8 @@ int load_modules(unsigned int preload_only)
 		AST_LIST_TRAVERSE_SAFE_BEGIN(&load_order, order, entry) {
 			if (!resource_name_match(order->resource, v->value)) {
 				AST_LIST_REMOVE_CURRENT(&load_order, entry);
-				free(order->resource);
-				free(order);
+				ast_free(order->resource);
+				ast_free(order);
 			}
 		}
 		AST_LIST_TRAVERSE_SAFE_END;
@@ -840,8 +840,8 @@ int load_modules(unsigned int preload_only)
 		case AST_MODULE_LOAD_SUCCESS:
 		case AST_MODULE_LOAD_DECLINE:
 			AST_LIST_REMOVE_CURRENT(&load_order, entry);
-			free(order->resource);
-			free(order);
+			ast_free(order->resource);
+			ast_free(order);
 			break;
 		case AST_MODULE_LOAD_FAILURE:
 			res = -1;
@@ -859,8 +859,8 @@ int load_modules(unsigned int preload_only)
 		case AST_MODULE_LOAD_SUCCESS:
 		case AST_MODULE_LOAD_DECLINE:
 			AST_LIST_REMOVE_CURRENT(&load_order, entry);
-			free(order->resource);
-			free(order);
+			ast_free(order->resource);
+			ast_free(order);
 			break;
 		case AST_MODULE_LOAD_FAILURE:
 			res = -1;
@@ -874,8 +874,8 @@ int load_modules(unsigned int preload_only)
 
 done:
 	while ((order = AST_LIST_REMOVE_HEAD(&load_order, entry))) {
-		free(order->resource);
-		free(order);
+		ast_free(order->resource);
+		ast_free(order);
 	}
 
 	AST_LIST_UNLOCK(&module_list);
diff --git a/main/manager.c b/main/manager.c
index 102ce69dc33a4cc8e4ba9294f92d2400f7dd76d6..6bffad2f613f01209460d63c7e49ef87e6e92136 100644
--- a/main/manager.c
+++ b/main/manager.c
@@ -295,7 +295,7 @@ static void purge_events(void)
 	while ( (ev = AST_LIST_FIRST(&all_events)) &&
 	    ev->usecount == 0 && AST_LIST_NEXT(ev, eq_next)) {
 		AST_LIST_REMOVE_HEAD(&all_events, eq_next);
-		free(ev);
+		ast_free(ev);
 	}
 	AST_LIST_UNLOCK(&all_events);
 }
@@ -696,7 +696,7 @@ static void free_session(struct mansession *s)
 	if (s->f != NULL)
 		fclose(s->f);
 	ast_mutex_destroy(&s->__lock);
-	free(s);
+	ast_free(s);
 	unref_event(eqe);
 }
 
@@ -1889,7 +1889,7 @@ static void *fast_originate(void *data)
 	/* Locked by ast_pbx_outgoing_exten or ast_pbx_outgoing_app */
 	if (chan)
 		ast_channel_unlock(chan);
-	free(in);
+	ast_free(in);
 	return NULL;
 }
 
@@ -2501,7 +2501,7 @@ static void *session_do(void *data)
 	destroy_session(s);
 
 done:
-	free(ser);
+	ast_free(ser);
 	return NULL;
 }
 
@@ -2641,7 +2641,7 @@ int ast_manager_unregister(char *action)
 				prev->next = cur->next;
 			else
 				first_action = cur->next;
-			free(cur);
+			ast_free(cur);
 			if (option_verbose > 1)
 				ast_verbose(VERBOSE_PREFIX_2 "Manager unregistered action %s\n", action);
 			break;
@@ -3273,10 +3273,10 @@ int init_manager(void)
 
 	ami_tls_cfg.enabled = 0;
 	if (ami_tls_cfg.certfile)
-		free(ami_tls_cfg.certfile);
+		ast_free(ami_tls_cfg.certfile);
 	ami_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
 	if (ami_tls_cfg.cipher)
-		free(ami_tls_cfg.cipher);
+		ast_free(ami_tls_cfg.cipher);
 	ami_tls_cfg.cipher = ast_strdup("");
 
 	for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
@@ -3293,10 +3293,10 @@ int init_manager(void)
 				ast_log(LOG_WARNING, "Invalid bind address '%s'\n", val);
 			}
 		} else if (!strcasecmp(var->name, "sslcert")) {
-			free(ami_tls_cfg.certfile);
+			ast_free(ami_tls_cfg.certfile);
 			ami_tls_cfg.certfile = ast_strdup(val);
 		} else if (!strcasecmp(var->name, "sslcipher")) {
-			free(ami_tls_cfg.cipher);
+			ast_free(ami_tls_cfg.cipher);
 			ami_tls_cfg.cipher = ast_strdup(val);
 		} else if (!strcasecmp(var->name, "enabled")) {
 			manager_enabled = ast_true(val);
@@ -3359,23 +3359,23 @@ int init_manager(void)
 		while (var) {
 			if (!strcasecmp(var->name, "secret")) {
 				if (user->secret)
-					free(user->secret);
+					ast_free(user->secret);
 				user->secret = ast_strdup(var->value);
 			} else if (!strcasecmp(var->name, "deny") ) {
 				if (user->deny)
-					free(user->deny);
+					ast_free(user->deny);
 				user->deny = ast_strdup(var->value);
 			} else if (!strcasecmp(var->name, "permit") ) {
 				if (user->permit)
-					free(user->permit);
+					ast_free(user->permit);
 				user->permit = ast_strdup(var->value);
 			}  else if (!strcasecmp(var->name, "read") ) {
 				if (user->read)
-					free(user->read);
+					ast_free(user->read);
 				user->read = ast_strdup(var->value);
 			}  else if (!strcasecmp(var->name, "write") ) {
 				if (user->write)
-					free(user->write);
+					ast_free(user->write);
 				user->write = ast_strdup(var->value);
 			}  else if (!strcasecmp(var->name, "displayconnects") )
 				user->displayconnects = ast_true(var->value);
@@ -3397,16 +3397,16 @@ int init_manager(void)
 		AST_LIST_REMOVE_CURRENT(&users, list);
 		/* Free their memory now */
 		if (user->secret)
-			free(user->secret);
+			ast_free(user->secret);
 		if (user->deny)
-			free(user->deny);
+			ast_free(user->deny);
 		if (user->permit)
-			free(user->permit);
+			ast_free(user->permit);
 		if (user->read)
-			free(user->read);
+			ast_free(user->read);
 		if (user->write)
-			free(user->write);
-		free(user);
+			ast_free(user->write);
+		ast_free(user);
 	}
 	AST_LIST_TRAVERSE_SAFE_END
 
diff --git a/main/netsock.c b/main/netsock.c
index 2ce60b8c43a794ce856b72c5131e88faa5dac7d2..e57c376eec02c687e11222bf7016bf30725e795d 100644
--- a/main/netsock.c
+++ b/main/netsock.c
@@ -80,7 +80,7 @@ static void ast_netsock_destroy(struct ast_netsock *netsock)
 {
 	ast_io_remove(netsock->ioc, netsock->ioref);
 	close(netsock->sockfd);
-	free(netsock);
+	ast_free(netsock);
 }
 
 struct ast_netsock_list *ast_netsock_list_alloc(void)
@@ -147,7 +147,7 @@ struct ast_netsock *ast_netsock_bindaddr(struct ast_netsock_list *list, struct i
 		
 	ast_enable_packet_fragmentation(netsocket);
 
-	if (!(ns = ast_calloc(1, sizeof(struct ast_netsock)))) {
+	if (!(ns = ast_calloc(1, sizeof(*ns)))) {
 		close(netsocket);
 		return NULL;
 	}
@@ -155,7 +155,7 @@ struct ast_netsock *ast_netsock_bindaddr(struct ast_netsock_list *list, struct i
 	/* Establish I/O callback for socket read */
 	if (!(ioref = ast_io_add(ioc, netsocket, callback, AST_IO_IN, ns))) {
 		close(netsocket);
-		free(ns);
+		ast_free(ns);
 		return NULL;
 	}	
 	ASTOBJ_INIT(ns);
diff --git a/main/pbx.c b/main/pbx.c
index ac32bffe7a1002ba9704ab915a94a030bff00aed..90dd7ed7431d6934a02207cde0f60e12343a7006 100644
--- a/main/pbx.c
+++ b/main/pbx.c
@@ -609,7 +609,7 @@ static inline int include_valid(struct ast_include *i)
 
 static void pbx_destroy(struct ast_pbx *p)
 {
-	free(p);
+	ast_free(p);
 }
 
 /*
@@ -2022,7 +2022,7 @@ static void *device_state_thread(void *data)
 
 		handle_statechange(sc->dev);
 
-		free(sc);
+		ast_free(sc);
 	}
 
 	return NULL;
@@ -2133,7 +2133,7 @@ int ast_extension_state_del(int id, ast_state_cb_type callback)
 	if (p_cur && *p_cur) {
 		struct ast_state_cb *cur = *p_cur;
 		*p_cur = cur->next;
-		free(cur);
+		ast_free(cur);
 		ret = 0;
 	}
 	AST_RWLIST_UNLOCK(&hints);
@@ -2215,11 +2215,11 @@ static int ast_remove_hint(struct ast_exten *e)
 				cbprev = cblist;
 				cblist = cblist->next;
 				cbprev->callback(hint->exten->parent->name, hint->exten->exten, AST_EXTENSION_DEACTIVATED, cbprev->data);
-				free(cbprev);
+				ast_free(cbprev);
 	    		}
 	    		hint->callbacks = NULL;
 			AST_RWLIST_REMOVE_CURRENT(&hints, list);
-	    		free(hint);
+	    		ast_free(hint);
 	   		res = 0;
 			break;
 		}
@@ -2326,7 +2326,7 @@ static int __ast_pbx_run(struct ast_channel *c)
 	if (c->pbx) {
 		ast_log(LOG_WARNING, "%s already has PBX structure??\n", c->name);
 		/* XXX and now what ? */
-		free(c->pbx);
+		ast_free(c->pbx);
 	}
 	if (!(c->pbx = ast_calloc(1, sizeof(*c->pbx))))
 		return -1;
@@ -2335,7 +2335,7 @@ static int __ast_pbx_run(struct ast_channel *c)
 			c->cdr = ast_cdr_alloc();
 			if (!c->cdr) {
 				ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
-				free(c->pbx);
+				ast_free(c->pbx);
 				return -1;
 			}
 			ast_cdr_init(c->cdr, c);
@@ -2593,7 +2593,7 @@ static void destroy_exten(struct ast_exten *e)
 
 	if (e->datad)
 		e->datad(e->data);
-	free(e);
+	ast_free(e);
 }
 
 static void *pbx_thread(void *data)
@@ -2722,7 +2722,7 @@ int ast_context_remove_include2(struct ast_context *con, const char *include, co
 			else
 				con->includes = i->next;
 			/* free include and return */
-			free(i);
+			ast_free(i);
 			ret = 0;
 			break;
 		}
@@ -2772,7 +2772,7 @@ int ast_context_remove_switch2(struct ast_context *con, const char *sw, const ch
 			(!registrar || !strcmp(i->registrar, registrar))) {
 			/* found, remove from list */
 			AST_LIST_REMOVE_CURRENT(&con->alts, list);
-			free(i); /* free switch and return */
+			ast_free(i); /* free switch and return */
 			ret = 0;
 			break;
 		}
@@ -3925,7 +3925,7 @@ int ast_unregister_application(const char *app)
 			AST_RWLIST_REMOVE_CURRENT(&apps, list);
 			if (option_verbose > 1)
 				ast_verbose( VERBOSE_PREFIX_2 "Unregistered application '%s'\n", tmp->name);
-			free(tmp);
+			ast_free(tmp);
 			break;
 		}
 	}
@@ -4083,7 +4083,7 @@ void ast_merge_contexts_and_delete(struct ast_context **extcontexts, const char
 				prevcb = thiscb;
 				thiscb = thiscb->next;
 				prevcb->callback(this->context, this->exten, AST_EXTENSION_REMOVED, prevcb->data);
-				free(prevcb);
+				ast_free(prevcb);
 	    		}
 		} else {
 			thiscb = this->callbacks;
@@ -4093,7 +4093,7 @@ void ast_merge_contexts_and_delete(struct ast_context **extcontexts, const char
 			hint->callbacks = this->callbacks;
 			hint->laststate = this->laststate;
 		}
-		free(this);
+		ast_free(this);
 	}
 
 	AST_RWLIST_UNLOCK(&hints);
@@ -4406,7 +4406,7 @@ int ast_context_add_include2(struct ast_context *con, const char *value,
 	/* ... go to last include and check if context is already included too... */
 	for (i = con->includes; i; i = i->next) {
 		if (!strcasecmp(i->name, new_include->name)) {
-			free(new_include);
+			ast_free(new_include);
 			ast_unlock_context(con);
 			errno = EEXIST;
 			return -1;
@@ -4497,7 +4497,7 @@ int ast_context_add_switch2(struct ast_context *con, const char *value,
 	/* ... go to last sw and check if context is already swd too... */
 	AST_LIST_TRAVERSE(&con->alts, i, list) {
 		if (!strcasecmp(i->name, new_sw->name) && !strcasecmp(i->data, new_sw->data)) {
-			free(new_sw);
+			ast_free(new_sw);
 			ast_unlock_context(con);
 			errno = EEXIST;
 			return -1;
@@ -4542,10 +4542,10 @@ int ast_context_remove_ignorepat2(struct ast_context *con, const char *ignorepat
 			(!registrar || (registrar == ip->registrar))) {
 			if (ipl) {
 				ipl->next = ip->next;
-				free(ip);
+				ast_free(ip);
 			} else {
 				con->ignorepats = ip->next;
-				free(ip);
+				ast_free(ip);
 			}
 			ast_unlock_context(con);
 			return 0;
@@ -4766,7 +4766,7 @@ static int add_pri(struct ast_context *con, struct ast_exten *tmp,
 			ast_log(LOG_WARNING, "Unable to register extension '%s', priority %d in '%s', already in use\n", tmp->exten, tmp->priority, con->name);
 			if (tmp->datad)
 				tmp->datad(tmp->data);
-			free(tmp);
+			ast_free(tmp);
 			return -1;
 		}
 		/* we are replacing e, so copy the link fields and then update
@@ -4785,7 +4785,7 @@ static int add_pri(struct ast_context *con, struct ast_exten *tmp,
 		/* Destroy the old one */
 		if (e->datad)
 			e->datad(e->data);
-		free(e);
+		ast_free(e);
 	} else {	/* Slip ourselves in just before e */
 		tmp->peer = e;
 		tmp->next = e->next;	/* extension chain, or NULL if e is not the first extension */
@@ -5020,7 +5020,7 @@ static void *async_wait(void *data)
 			}
 		}
 	}
-	free(as);
+	ast_free(as);
 	if (chan)
 		ast_hangup(chan);
 	return NULL;
@@ -5162,7 +5162,7 @@ int ast_pbx_outgoing_exten(const char *type, int format, void *data, int timeout
 				ast_channel_lock(chan);
 		}
 		if (!chan) {
-			free(as);
+			ast_free(as);
 			res = -1;
 			goto outgoing_exten_cleanup;
 		}
@@ -5175,7 +5175,7 @@ int ast_pbx_outgoing_exten(const char *type, int format, void *data, int timeout
 			ast_cdr_setaccount(chan, account);
 		if (ast_pthread_create_detached(&as->p, NULL, async_wait, as)) {
 			ast_log(LOG_WARNING, "Failed to start async wait\n");
-			free(as);
+			ast_free(as);
 			if (channel) {
 				*channel = NULL;
 				ast_channel_unlock(chan);
@@ -5211,7 +5211,7 @@ static void *ast_pbx_run_app(void *data)
 	} else
 		ast_log(LOG_WARNING, "No such application '%s'\n", tmp->app);
 	ast_hangup(tmp->chan);
-	free(tmp);
+	ast_free(tmp);
 	return NULL;
 }
 
@@ -5241,7 +5241,7 @@ int ast_pbx_outgoing_app(const char *type, int format, void *data, int timeout,
 				chan->cdr = ast_cdr_alloc();   /* allocate a cdr for the channel */
 				if (!chan->cdr) {
 					/* allocation of the cdr failed */
-					free(chan->pbx);
+					ast_free(chan->pbx);
 					res = -1;
 					goto outgoing_app_cleanup;
 				}
@@ -5273,7 +5273,7 @@ int ast_pbx_outgoing_app(const char *type, int format, void *data, int timeout,
 							ast_channel_lock(chan);
 						if (ast_pthread_create_detached(&tmp->t, NULL, ast_pbx_run_app, tmp)) {
 							ast_log(LOG_WARNING, "Unable to spawn execute thread on %s: %s\n", chan->name, strerror(errno));
-							free(tmp);
+							ast_free(tmp);
 							if (locked_channel)
 								ast_channel_unlock(chan);
 							ast_hangup(chan);
@@ -5316,7 +5316,7 @@ int ast_pbx_outgoing_app(const char *type, int format, void *data, int timeout,
 		}
 		chan = __ast_request_and_dial(type, format, data, timeout, reason, cid_num, cid_name, &oh);
 		if (!chan) {
-			free(as);
+			ast_free(as);
 			res = -1;
 			goto outgoing_app_cleanup;
 		}
@@ -5333,7 +5333,7 @@ int ast_pbx_outgoing_app(const char *type, int format, void *data, int timeout,
 			ast_channel_lock(chan);
 		if (ast_pthread_create_detached(&as->p, NULL, async_wait, as)) {
 			ast_log(LOG_WARNING, "Failed to start async wait\n");
-			free(as);
+			ast_free(as);
 			if (locked_channel)
 				ast_channel_unlock(chan);
 			ast_hangup(chan);
@@ -5383,15 +5383,15 @@ void __ast_context_destroy(struct ast_context *con, const char *registrar)
 		for (tmpi = tmp->includes; tmpi; ) { /* Free includes */
 			struct ast_include *tmpil = tmpi;
 			tmpi = tmpi->next;
-			free(tmpil);
+			ast_free(tmpil);
 		}
 		for (ipi = tmp->ignorepats; ipi; ) { /* Free ignorepats */
 			struct ast_ignorepat *ipl = ipi;
 			ipi = ipi->next;
-			free(ipl);
+			ast_free(ipl);
 		}
 		while ((sw = AST_LIST_REMOVE_HEAD(&tmp->alts, list)))
-			free(sw);
+			ast_free(sw);
 		for (e = tmp->root; e;) {
 			for (en = e->peer; en;) {
 				el = en;
@@ -5403,7 +5403,7 @@ void __ast_context_destroy(struct ast_context *con, const char *registrar)
 			destroy_exten(el);
 		}
 		ast_rwlock_destroy(&tmp->lock);
-		free(tmp);
+		ast_free(tmp);
 		/* if we have a specific match, we are done, otherwise continue */
 		tmp = con ? NULL : next;
 	}
diff --git a/main/rtp.c b/main/rtp.c
index 1ae1edc1baa7e5bbf1829976ed4281af30352998..617136b55ad79bd35fad9640a09296e84fa84210 100644
--- a/main/rtp.c
+++ b/main/rtp.c
@@ -1936,7 +1936,7 @@ static struct ast_rtcp *ast_rtcp_new(void)
 	rtcp->them.sin_family = AF_INET;
 
 	if (rtcp->s < 0) {
-		free(rtcp);
+		ast_free(rtcp);
 		ast_log(LOG_WARNING, "Unable to allocate RTCP socket: %s\n", strerror(errno));
 		return NULL;
 	}
@@ -1977,7 +1977,7 @@ struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io
 
 	rtp->s = rtp_socket();
 	if (rtp->s < 0) {
-		free(rtp);
+		ast_free(rtp);
 		ast_log(LOG_ERROR, "Unable to allocate socket: %s\n", strerror(errno));
 		return NULL;
 	}
@@ -2017,9 +2017,9 @@ struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io
 			close(rtp->s);
 			if (rtp->rtcp) {
 				close(rtp->rtcp->s);
-				free(rtp->rtcp);
+				ast_free(rtp->rtcp);
 			}
-			free(rtp);
+			ast_free(rtp);
 			return NULL;
 		}
 		/* The port was used, increment it (by two). */
@@ -2035,9 +2035,9 @@ struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io
 			close(rtp->s);
 			if (rtp->rtcp) {
 				close(rtp->rtcp->s);
-				free(rtp->rtcp);
+				ast_free(rtp->rtcp);
 			}
-			free(rtp);
+			ast_free(rtp);
 			return NULL;
 		}
 	}
@@ -2204,13 +2204,13 @@ void ast_rtp_destroy(struct ast_rtp *rtp)
 		if (rtp->rtcp->schedid > 0)
 			ast_sched_del(rtp->sched, rtp->rtcp->schedid);
 		close(rtp->rtcp->s);
-		free(rtp->rtcp);
+		ast_free(rtp->rtcp);
 		rtp->rtcp=NULL;
 	}
 #ifdef P2P_INTENSE
 	ast_mutex_destroy(&rtp->bridge_lock);
 #endif
-	free(rtp);
+	ast_free(rtp);
 }
 
 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
diff --git a/main/say.c b/main/say.c
index 582ffb2ec51c5d4da492376b59654f1fa3573be9..92fec372e7cf35a2531efc00102aead931e45013 100644
--- a/main/say.c
+++ b/main/say.c
@@ -1962,7 +1962,7 @@ and combinations of eg.: 20_1, 30m_3m, etc...
 	static odmiana *odmiana_zenska = NULL; 
 
 	if (odmiana_nieosobowa == NULL) {
-		odmiana_nieosobowa = (odmiana *) malloc(sizeof(odmiana));
+		odmiana_nieosobowa = ast_malloc(sizeof(*odmiana_nieosobowa));
 
 		odmiana_nieosobowa->separator_dziesiatek = " ";
 
@@ -1975,7 +1975,7 @@ and combinations of eg.: 20_1, 30m_3m, etc...
 	}
 
 	if (odmiana_zenska == NULL) {
-		odmiana_zenska = (odmiana *) malloc(sizeof(odmiana));
+		odmiana_zenska = ast_malloc(sizeof(*odmiana_zenska));
 
 		odmiana_zenska->separator_dziesiatek = " ";
 
@@ -1988,7 +1988,7 @@ and combinations of eg.: 20_1, 30m_3m, etc...
 	}
 
 	if (odmiana_meska == NULL) {
-		odmiana_meska = (odmiana *) malloc(sizeof(odmiana));
+		odmiana_meska = ast_malloc(sizeof(*odmiana_meska));
 
 		odmiana_meska->separator_dziesiatek = " ";
 
@@ -6908,7 +6908,7 @@ static int ast_say_number_full_ge(struct ast_channel *chan, int num, const char
 
 	while (res == 0 && (s = strstr(remainder, " "))) {
 		size_t len = s - remainder;
-		char* new_string = malloc(len + 1 + strlen("digits/"));
+		char* new_string = ast_malloc(len + 1 + strlen("digits/"));
 
 		sprintf(new_string, "digits/");
 		strncat(new_string, remainder, len);  /* we can't sprintf() it, it's not null-terminated. */
@@ -6922,7 +6922,7 @@ static int ast_say_number_full_ge(struct ast_channel *chan, int num, const char
 		}
 		ast_stopstream(chan);
 
-		free(new_string);
+		ast_free(new_string);
 
 		remainder = s + 1;  /* position just after the found space char. */
 		while(*remainder == ' ')  /* skip multiple spaces */
@@ -6933,7 +6933,7 @@ static int ast_say_number_full_ge(struct ast_channel *chan, int num, const char
 	/* the last chunk. */
 	if (res == 0 && *remainder) {
 
-		char* new_string = malloc(strlen(remainder) + 1 + strlen("digits/"));
+		char* new_string = ast_malloc(strlen(remainder) + 1 + strlen("digits/"));
 		sprintf(new_string, "digits/%s", remainder);
 
 		if (!ast_streamfile(chan, new_string, language)) {
@@ -6944,7 +6944,7 @@ static int ast_say_number_full_ge(struct ast_channel *chan, int num, const char
 		}
 		ast_stopstream(chan);
 
-		free(new_string);
+		ast_free(new_string);
 
 	}
 
diff --git a/main/sched.c b/main/sched.c
index 851e07db54b7488aa0c2acbf39c5a354bc5459de..9aac2cde7e9d4c9965f67558c008781da7a0b48e 100644
--- a/main/sched.c
+++ b/main/sched.c
@@ -94,17 +94,17 @@ void sched_context_destroy(struct sched_context *con)
 #ifdef SCHED_MAX_CACHE
 	/* Eliminate the cache */
 	while ((s = AST_LIST_REMOVE_HEAD(&con->schedc, list)))
-		free(s);
+		ast_free(s);
 #endif
 
 	/* And the queue */
 	while ((s = AST_LIST_REMOVE_HEAD(&con->schedq, list)))
-		free(s);
+		ast_free(s);
 	
 	/* And the context */
 	ast_mutex_unlock(&con->lock);
 	ast_mutex_destroy(&con->lock);
-	free(con);
+	ast_free(con);
 }
 
 static struct sched *sched_alloc(struct sched_context *con)
@@ -138,7 +138,7 @@ static void sched_release(struct sched_context *con, struct sched *tmp)
 		con->schedccnt++;
 	} else
 #endif
-		free(tmp);
+		ast_free(tmp);
 }
 
 /*! \brief
diff --git a/main/strcompat.c b/main/strcompat.c
index dbad22b75777fde28f0a29656dfa83dca86e494b..912f64dea2af588cbaa6c39b7e9d0e2965959b86 100644
--- a/main/strcompat.c
+++ b/main/strcompat.c
@@ -141,7 +141,7 @@ size_t strnlen(const char *s, size_t n)
 char *strndup(const char *s, size_t n)
 {
 	size_t len = strnlen(s, n);
-	char *new = malloc(len + 1);
+	char *new = ast_malloc(len + 1);
 
 	if (!new)
 		return NULL;
@@ -162,7 +162,7 @@ int vasprintf(char **strp, const char *fmt, va_list ap)
 	va_copy(ap2, ap);
 	size = vsnprintf(&s, 1, fmt, ap2);
 	va_end(ap2);
-	*strp = malloc(size + 1);
+	*strp = ast_malloc(size + 1);
 	if (!*strp)
 		return -1;
 	vsnprintf(*strp, size + 1, fmt, ap);
diff --git a/main/tdd.c b/main/tdd.c
index 7189f490e6a23dc3d5894fbc93beb5b41f99a410..a3ef39282a8e4978eb2c849c7f87b4c86de760c7 100644
--- a/main/tdd.c
+++ b/main/tdd.c
@@ -101,9 +101,8 @@ void tdd_init(void)
 struct tdd_state *tdd_new(void)
 {
 	struct tdd_state *tdd;
-	tdd = malloc(sizeof(struct tdd_state));
+	tdd = calloc(1, sizeof(*tdd));
 	if (tdd) {
-		memset(tdd, 0, sizeof(struct tdd_state));
 		tdd->fskd.spb = 176;        /* 45.5 baud */
 		tdd->fskd.hdlc = 0;         /* Async */
 		tdd->fskd.nbit = 5;         /* 5 bits */
@@ -143,13 +142,12 @@ int tdd_feed(struct tdd_state *tdd, unsigned char *ubuf, int len)
 	int b = 'X';
 	int res;
 	int c,x;
-	short *buf = malloc(2 * len + tdd->oldlen);
+	short *buf = calloc(1, 2 * len + tdd->oldlen);
 	short *obuf = buf;
 	if (!buf) {
 		ast_log(LOG_WARNING, "Out of memory\n");
 		return -1;
 	}
-	memset(buf, 0, 2 * len + tdd->oldlen);
 	memcpy(buf, tdd->oldstuff, tdd->oldlen);
 	mylen += tdd->oldlen/2;
 	for (x = 0; x < len; x++) 
diff --git a/main/threadstorage.c b/main/threadstorage.c
index b481343df9cd183c8c4af877f621267146c3c448..26f3e1c192a8ca13278c46b60e4a5ef20cb332f0 100644
--- a/main/threadstorage.c
+++ b/main/threadstorage.c
@@ -85,7 +85,7 @@ void __ast_threadstorage_object_remove(void *key)
 	AST_LIST_TRAVERSE_SAFE_END;
 	AST_RWLIST_UNLOCK(&tls_objects);
 	if (to)
-		free(to);
+		ast_free(to);
 }
 
 void __ast_threadstorage_object_replace(void *key_old, void *key_new, size_t len)
diff --git a/main/translate.c b/main/translate.c
index f13f6274661f42311785701561d624a2aacd6843..b80c280de192785b71e2864154fb15e60048f0cb 100644
--- a/main/translate.c
+++ b/main/translate.c
@@ -129,7 +129,7 @@ static void *newpvt(struct ast_translator *t)
 		pvt->outbuf = ofs + AST_FRIENDLY_OFFSET;
 	/* call local init routine, if present */
 	if (t->newpvt && t->newpvt(pvt)) {
-		free(pvt);
+		ast_free(pvt);
 		return NULL;
 	}
 	ast_module_ref(t->module);
@@ -142,7 +142,7 @@ static void destroy(struct ast_trans_pvt *pvt)
 
 	if (t->destroy)
 		t->destroy(pvt);
-	free(pvt);
+	ast_free(pvt);
 	ast_module_unref(t->module);
 }
 
diff --git a/main/udptl.c b/main/udptl.c
index d255f93755f0889ec156c2e03b0a60d12ebe05b1..34b5b872f6bbb615b77121db2dbe191e49a6d452 100644
--- a/main/udptl.c
+++ b/main/udptl.c
@@ -824,7 +824,7 @@ struct ast_udptl *ast_udptl_new_with_bindaddr(struct sched_context *sched, struc
 	udptl->us.sin_family = AF_INET;
 
 	if ((udptl->fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
-		free(udptl);
+		ast_free(udptl);
 		ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
 		return NULL;
 	}
@@ -845,7 +845,7 @@ struct ast_udptl *ast_udptl_new_with_bindaddr(struct sched_context *sched, struc
 		if (errno != EADDRINUSE) {
 			ast_log(LOG_WARNING, "Unexpected bind error: %s\n", strerror(errno));
 			close(udptl->fd);
-			free(udptl);
+			ast_free(udptl);
 			return NULL;
 		}
 		if (++x > udptlend)
@@ -853,7 +853,7 @@ struct ast_udptl *ast_udptl_new_with_bindaddr(struct sched_context *sched, struc
 		if (x == startplace) {
 			ast_log(LOG_WARNING, "No UDPTL ports remaining\n");
 			close(udptl->fd);
-			free(udptl);
+			ast_free(udptl);
 			return NULL;
 		}
 	}
@@ -908,7 +908,7 @@ void ast_udptl_destroy(struct ast_udptl *udptl)
 		ast_io_remove(udptl->io, udptl->ioid);
 	if (udptl->fd > -1)
 		close(udptl->fd);
-	free(udptl);
+	ast_free(udptl);
 }
 
 int ast_udptl_write(struct ast_udptl *s, struct ast_frame *f)
diff --git a/main/utils.c b/main/utils.c
index 498184a41d9e78af49f0f25a49cd2adaf78fabb9..7570ca608d265165dcd70f608d11c733645df3fe 100644
--- a/main/utils.c
+++ b/main/utils.c
@@ -539,7 +539,7 @@ static void *dummy_start(void *data)
 	   keep a copy of the pointer and then ast_unregister_thread will
 	   free the memory
 	*/
-	free(data);
+	ast_free(data);
 	ast_register_thread(a.name);
 	pthread_cleanup_push(ast_unregister_thread, (void *) pthread_self());
 	ret = a.start_routine(a.data);
diff --git a/res/res_agi.c b/res/res_agi.c
index f1a1f2ff0d2fa2394aaafddb526ad2453eeb6aee..46a26a4c914d309a7e36e9dd4b565d3f05da179b 100644
--- a/res/res_agi.c
+++ b/res/res_agi.c
@@ -130,7 +130,7 @@ static void agi_debug_cli(int fd, char *fmt, ...)
 		if (agidebug)
 			ast_verbose("AGI Tx >> %s\n", stuff);
 		ast_carefulwrite(fd, stuff, strlen(stuff), 100);
-		free(stuff);
+		ast_free(stuff);
 	}
 }
 
@@ -476,7 +476,7 @@ static int handle_recvtext(struct ast_channel *chan, AGI *agi, int argc, char *a
 	buf = ast_recvtext(chan,atoi(argv[2]));
 	if (buf) {
 		fdprintf(agi->fd, "200 result=1 (%s)\n", buf);
-		free(buf);
+		ast_free(buf);
 	} else {	
 		fdprintf(agi->fd, "200 result=-1\n");
 	}
diff --git a/res/res_config_pgsql.c b/res/res_config_pgsql.c
index 624522744c3b3ce6aa8fc96d138d216202b642dd..5b2a7ad1c21b3faec5fe444cc7519702846bd790 100644
--- a/res/res_config_pgsql.c
+++ b/res/res_config_pgsql.c
@@ -193,7 +193,7 @@ static struct ast_variable *realtime_pgsql(const char *database, const char *tab
 				}
 			}
 		}
-		free(fieldnames);
+		ast_free(fieldnames);
 	} else {
 		ast_log(LOG_WARNING,
 				"Postgresql RealTime: Could not find any rows in table %s.\n", table);
@@ -347,7 +347,7 @@ static struct ast_config *realtime_multi_pgsql(const char *database, const char
 			}
 			ast_category_append(cfg, cat);
 		}
-		free(fieldnames);
+		ast_free(fieldnames);
 	} else {
 		ast_log(LOG_WARNING,
 				"Postgresql RealTime: Could not find any rows in table %s.\n", table);
@@ -747,7 +747,7 @@ static int pgsql_reconnect(const char *database)
 		pgsqlConn = PQconnectdb(connInfo);
 		if (option_debug)
 			ast_log(LOG_DEBUG, "%u connInfo=%s\n", size, connInfo);
-		free(connInfo);
+		ast_free(connInfo);
 		connInfo = NULL;
 		if (option_debug)
 			ast_log(LOG_DEBUG, "pgsqlConn=%p\n", pgsqlConn);
diff --git a/res/res_config_sqlite.c b/res/res_config_sqlite.c
index 076282e80bafac7165689af4a84e07b06e532949..01bc7a4939169e8fa47ed3473c860c13a8e2f536 100644
--- a/res/res_config_sqlite.c
+++ b/res/res_config_sqlite.c
@@ -593,7 +593,7 @@ static char *sql_get_config_table =
 static int set_var(char **var, char *name, char *value)
 {
 	if (*var)
-		free(*var);
+		ast_free(*var);
 
 	*var = ast_strdup(value);
 
@@ -654,11 +654,11 @@ static int load_config(void)
 
 static void unload_config(void)
 {
-	free(dbfile);
+	ast_free(dbfile);
 	dbfile = NULL;
-	free(config_table);
+	ast_free(config_table);
 	config_table = NULL;
-	free(cdr_table);
+	ast_free(cdr_table);
 	cdr_table = NULL;
 }
 
@@ -684,7 +684,7 @@ static int cdr_handler(struct ast_cdr *cdr)
 
 	if (error) {
 		ast_log(LOG_ERROR, "%s\n", errormsg);
-		free(errormsg);
+		ast_free(errormsg);
 		return 1;
 	}
 
@@ -711,7 +711,7 @@ static int add_cfg_entry(void *arg, int argc, char **argv, char **columnNames)
 			return 1;
 		}
 
-		free(args->cat_name);
+		ast_free(args->cat_name);
 		args->cat_name = ast_strdup(argv[RES_SQLITE_CONFIG_CATEGORY]);
 
 		if (!args->cat_name) {
@@ -763,11 +763,11 @@ static struct ast_config *config_handler(const char *database,
 
 	ast_mutex_unlock(&mutex);
 
-	free(args.cat_name);
+	ast_free(args.cat_name);
 
 	if (error) {
 		ast_log(LOG_ERROR, "%s\n", errormsg);
-		free(errormsg);
+		ast_free(errormsg);
 		return NULL;
 	}
 
@@ -785,15 +785,15 @@ static size_t get_params(va_list ap, const char ***params_ptr, const char ***val
 
 	while ((param = va_arg(ap, const char *)) && (val = va_arg(ap, const char *))) {
 		if (!(tmp = ast_realloc(params, (params_count + 1) * sizeof(char *)))) {
-			free(params);
-			free(vals);
+			ast_free(params);
+			ast_free(vals);
 			return 0;
 		}
 		params = tmp;
 
 		if (!(tmp = ast_realloc(vals, (params_count + 1) * sizeof(char *)))) {
-			free(params);
-			free(vals);
+			ast_free(params);
+			ast_free(vals);
 			return 0;
 		}
 		vals = tmp;
@@ -872,8 +872,8 @@ realtime_handler(const char *database, const char *table, va_list ap)
 
 	if (!query) {
 		ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
-		free(params);
-		free(vals);
+		ast_free(params);
+		ast_free(vals);
 		return NULL;
 	}
 
@@ -888,8 +888,8 @@ realtime_handler(const char *database, const char *table, va_list ap)
 
 			if (!tmp_str) {
 				ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
-				free(params);
-				free(vals);
+				ast_free(params);
+				ast_free(vals);
 				return NULL;
 			}
 
@@ -897,8 +897,8 @@ realtime_handler(const char *database, const char *table, va_list ap)
 		}
 	}
 
-	free(params);
-	free(vals);
+	ast_free(params);
+	ast_free(vals);
 
 	tmp_str = sqlite_mprintf("%s LIMIT 1;", query);
 	sqlite_freemem(query);
@@ -925,7 +925,7 @@ realtime_handler(const char *database, const char *table, va_list ap)
 
 	if (error) {
 		ast_log(LOG_WARNING, "%s\n", errormsg);
-		free(errormsg);
+		ast_free(errormsg);
 		ast_variables_destroy(args.var);
 		return NULL;
 	}
@@ -1008,8 +1008,8 @@ static struct ast_config *realtime_multi_handler(const char *database,
 
 	if (!(initfield = ast_strdup(params[0]))) {
 		ast_config_destroy(cfg);
-		free(params);
-		free(vals);
+		ast_free(params);
+		ast_free(vals);
 		return NULL;
 	}
 
@@ -1034,9 +1034,9 @@ static struct ast_config *realtime_multi_handler(const char *database,
 	if (!(query = sqlite_mprintf(QUERY, table, params[0], op, tmp_str))) {
 		ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
 		ast_config_destroy(cfg);
-		free(params);
-		free(vals);
-		free(initfield);
+		ast_free(params);
+		ast_free(vals);
+		ast_free(initfield);
 		return NULL;
 	}
 
@@ -1052,9 +1052,9 @@ static struct ast_config *realtime_multi_handler(const char *database,
 			if (!tmp_str) {
 				ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
 				ast_config_destroy(cfg);
-				free(params);
-				free(vals);
-				free(initfield);
+				ast_free(params);
+				ast_free(vals);
+				ast_free(initfield);
 				return NULL;
 			}
 
@@ -1062,13 +1062,13 @@ static struct ast_config *realtime_multi_handler(const char *database,
 		}
 	}
 
-	free(params);
-	free(vals);
+	ast_free(params);
+	ast_free(vals);
 
 	if (!(tmp_str = sqlite_mprintf("%s ORDER BY %q;", query, initfield))) {
 		ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
 		ast_config_destroy(cfg);
-		free(initfield);
+		ast_free(initfield);
 		return NULL;
 	}
 
@@ -1087,11 +1087,11 @@ static struct ast_config *realtime_multi_handler(const char *database,
 	ast_mutex_unlock(&mutex);
 
 	sqlite_freemem(query);
-	free(initfield);
+	ast_free(initfield);
 
 	if (error) {
 		ast_log(LOG_WARNING, "%s\n", errormsg);
-		free(errormsg);
+		ast_free(errormsg);
 		ast_config_destroy(cfg);
 		return NULL;
 	}
@@ -1123,8 +1123,8 @@ static int realtime_update_handler(const char *database, const char *table,
 
 	if (!(query = sqlite_mprintf(QUERY, table, params[0], vals[0]))) {
 		ast_log(LOG_WARNING, "Unable to allocate SQL query\n");
-		free(params);
-		free(vals);
+		ast_free(params);
+		ast_free(vals);
 		return -1;
 	}
 
@@ -1138,8 +1138,8 @@ static int realtime_update_handler(const char *database, const char *table,
 
 			if (!tmp_str) {
 				ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
-				free(params);
-				free(vals);
+				ast_free(params);
+				ast_free(vals);
 				return -1;
 			}
 
@@ -1147,8 +1147,8 @@ static int realtime_update_handler(const char *database, const char *table,
 		}
 	}
 
-	free(params);
-	free(vals);
+	ast_free(params);
+	ast_free(vals);
 
 	if (!(tmp_str = sqlite_mprintf("%s WHERE %q = '%q';", query, keyfield, entity))) {
 		ast_log(LOG_WARNING, "Unable to reallocate SQL query\n");
@@ -1176,7 +1176,7 @@ static int realtime_update_handler(const char *database, const char *table,
 
 	if (error) {
 		ast_log(LOG_WARNING, "%s\n", errormsg);
-		free(errormsg);
+		ast_free(errormsg);
 	}
 
 	return rows_num;
@@ -1239,7 +1239,7 @@ static int load_module(void)
 
 	if (!(db = sqlite_open(dbfile, 0660, &errormsg))) {
 		ast_log(LOG_ERROR, "%s\n", errormsg);
-		free(errormsg);
+		ast_free(errormsg);
 		unload_module();
 		return 1;
 	}
@@ -1258,7 +1258,7 @@ static int load_module(void)
 			 */
 			if (error != SQLITE_ERROR) {
 				ast_log(LOG_ERROR, "%s\n", errormsg);
-				free(errormsg);
+				ast_free(errormsg);
 				unload_module();
 				return 1;
 			}
@@ -1270,7 +1270,7 @@ static int load_module(void)
 
 			if (error) {
 				ast_log(LOG_ERROR, "%s\n", errormsg);
-				free(errormsg);
+				ast_free(errormsg);
 				unload_module();
 				return 1;
 			}
diff --git a/res/res_features.c b/res/res_features.c
index cbb59a9151b23234771d3c9c994e0ba4c7a0fc02..b4feda26c2189c1e248ce2f678074d2d69b104e5 100644
--- a/res/res_features.c
+++ b/res/res_features.c
@@ -287,7 +287,7 @@ static void *ast_bridge_call_thread(void *data)
 		ast_hangup(tobj->peer);
 	}
 
-	free(tobj);
+	ast_free(tobj);
 
 	return NULL;
 }
@@ -375,7 +375,7 @@ int ast_park_call(struct ast_channel *chan, struct ast_channel *peer, int timeou
 	if (!ast_strlen_zero(parkingexten)) {
 		if (ast_exists_extension(NULL, parking_con, parkingexten, 1, NULL)) {
 			ast_mutex_unlock(&parking_lock);
-			free(pu);
+			ast_free(pu);
 			ast_log(LOG_WARNING, "Requested parking extension already exists: %s@%s\n", parkingexten, parking_con);
 			return -1; /* We failed to park this call, plain and simple so we need to error out */
 		}
@@ -398,7 +398,7 @@ int ast_park_call(struct ast_channel *chan, struct ast_channel *peer, int timeou
 
 		if (!(i < parking_range)) {
 			ast_log(LOG_WARNING, "No more parking spaces\n");
-			free(pu);
+			ast_free(pu);
 			ast_mutex_unlock(&parking_lock);
 			return -1;
 		}
@@ -1069,7 +1069,7 @@ static struct feature_group* register_group(const char *fgname)
 		return NULL;
 
 	if (ast_string_field_init(fg, 128)) {
-		free(fg);
+		ast_free(fg);
 		return NULL;
 	}
 
@@ -1093,7 +1093,7 @@ static void register_group_feature(struct feature_group *fg, const char *exten,
 		return;
 
 	if (ast_string_field_init(fge, 128)) {
-		free(fge);
+		ast_free(fge);
 		return;
 	}
 
@@ -1127,7 +1127,7 @@ void ast_unregister_feature(struct ast_call_feature *feature)
 	AST_LIST_LOCK(&feature_list);
 	AST_LIST_REMOVE(&feature_list,feature,feature_entry);
 	AST_LIST_UNLOCK(&feature_list);
-	free(feature);
+	ast_free(feature);
 }
 
 /*! \brief Remove all features in the list */
@@ -1137,7 +1137,7 @@ static void ast_unregister_features(void)
 
 	AST_LIST_LOCK(&feature_list);
 	while ((feature = AST_LIST_REMOVE_HEAD(&feature_list,feature_entry)))
-		free(feature);
+		ast_free(feature);
 	AST_LIST_UNLOCK(&feature_list);
 }
 
@@ -1164,11 +1164,11 @@ static void ast_unregister_groups(void)
 	while ((fg = AST_LIST_REMOVE_HEAD(&feature_groups, entry))) {
 		while ((fge = AST_LIST_REMOVE_HEAD(&fg->features, entry))) {
 			ast_string_field_free_all(fge);
-			free(fge);
+			ast_free(fge);
 		}
 
 		ast_string_field_free_all(fg);
-		free(fg);
+		ast_free(fg);
 	}
 	AST_RWLIST_UNLOCK(&feature_groups);
 }
@@ -1675,7 +1675,7 @@ int ast_bridge_call(struct ast_channel *chan,struct ast_channel *peer,struct ast
 		} else
 			ast_cdr_setuserfield(chan, peer->cdr->userfield);
 		/* free the peer's cdr without ast_cdr_free complaining */
-		free(peer->cdr);
+		ast_free(peer->cdr);
 		peer->cdr = NULL;
 	}
 
@@ -1986,7 +1986,7 @@ static void *do_parking_thread(void *ignore)
 						notify_metermaids(pt->parkingexten, parking_con);
 				} else
 					ast_log(LOG_WARNING, "Whoa, no parking context?\n");
-				free(pt);
+				ast_free(pt);
 			} else {	/* still within parking time, process descriptors */
 				for (x = 0; x < AST_MAX_FDS; x++) {
 					struct ast_frame *f;
@@ -2026,7 +2026,7 @@ static void *do_parking_thread(void *ignore)
 								notify_metermaids(pt->parkingexten, parking_con);
 						} else
 							ast_log(LOG_WARNING, "Whoa, no parking context?\n");
-						free(pt);
+						ast_free(pt);
 						break;
 					} else {
 						/*! \todo XXX Maybe we could do something with packets, like dial "0" for operator or something XXX */
@@ -2158,7 +2158,7 @@ static int park_exec(struct ast_channel *chan, void *data)
 			S_OR(pu->chan->cid.cid_name, "<unknown>")
 			);
 
-		free(pu);
+		ast_free(pu);
 	}
 	/* JK02: it helps to answer the channel if not already up */
 	if (chan->_state != AST_STATE_UP)
diff --git a/res/res_indications.c b/res/res_indications.c
index d149e21ba92dc5dbdb57816530ff706243910f1c..1a8aafc761077efb5e962fc53f8c28fc17642406 100644
--- a/res/res_indications.c
+++ b/res/res_indications.c
@@ -100,7 +100,7 @@ static int handle_add_indication(int fd, int argc, char *argv[])
 		ast_copy_string(tz->country,argv[2],sizeof(tz->country));
 		if (ast_register_indication_country(tz)) {
 			ast_log(LOG_WARNING, "Unable to register new country\n");
-			free(tz);
+			ast_free(tz);
 			return -1;
 		}
 		created_country = 1;
@@ -293,7 +293,7 @@ static int ind_load_module(void)
 					ast_copy_string(azone->alias, cxt, sizeof(azone->alias));
 					if (ast_register_indication_country(azone)) {
 						ast_log(LOG_WARNING, "Unable to register indication alias at line %d.\n",v->lineno);
-						free(tones);
+						ast_free(tones);
 					}
 					/* next item */
 					country = strsep(&c,",");
@@ -326,9 +326,9 @@ out:			v = v->next;
 		if (tones->description[0] || tones->alias[0] || tones->tones) {
 			if (ast_register_indication_country(tones)) {
 				ast_log(LOG_WARNING, "Unable to register indication at line %d.\n",v->lineno);
-				free(tones);
+				ast_free(tones);
 			}
-		} else free(tones);
+		} else ast_free(tones);
 
 		cxt = ast_category_browse(cfg, cxt);
 	}
diff --git a/res/res_jabber.c b/res/res_jabber.c
index 5b88bf7417ecab72b1abab245cdcbc6e46be00e4..e2ecf659a091f3f7983da6af2685100157cadc33 100644
--- a/res/res_jabber.c
+++ b/res/res_jabber.c
@@ -184,12 +184,12 @@ static void aji_client_destroy(struct aji_client *obj)
 	AST_LIST_LOCK(&obj->messages);
 	while ((tmp = AST_LIST_REMOVE_HEAD(&obj->messages, list))) {
 		if (tmp->from)
-			free(tmp->from);
+			ast_free(tmp->from);
 		if (tmp->message)
-			free(tmp->message);
+			ast_free(tmp->message);
 	}
 	AST_LIST_HEAD_DESTROY(&obj->messages);
-	free(obj);
+	ast_free(obj);
 }
 
 /*!
@@ -203,11 +203,11 @@ static void aji_buddy_destroy(struct aji_buddy *obj)
 
 	while ((tmp = obj->resources)) {
 		obj->resources = obj->resources->next;
-		free(tmp->description);
-		free(tmp);
+		ast_free(tmp->description);
+		ast_free(tmp);
 	}
 
-	free(obj);
+	ast_free(obj);
 }
 
 /*!
@@ -241,7 +241,7 @@ static struct aji_version *aji_find_version(char *node, char *version, ikspak *p
 			/* Specified version not found. Let's add it to 
 			   this node in our capabilities list */
 			if(!res) {
-				res = (struct aji_version *)malloc(sizeof(struct aji_version));
+				res = ast_malloc(sizeof(*res));
 				if(!res) {
 					ast_log(LOG_ERROR, "Out of memory!\n");
 					return NULL;
@@ -258,12 +258,12 @@ static struct aji_version *aji_find_version(char *node, char *version, ikspak *p
 	}
 	/* Specified node not found. Let's add it our capabilities list */
 	if(!list) {
-		list = (struct aji_capabilities *)malloc(sizeof(struct aji_capabilities));
+		list = ast_malloc(sizeof(*list));
 		if(!list) {
 			ast_log(LOG_ERROR, "Out of memory!\n");
 			return NULL;
 		}
-		res = (struct aji_version *)malloc(sizeof(struct aji_version));
+		res = ast_malloc(sizeof(*res));
 		if(!res) {
 			ast_log(LOG_ERROR, "Out of memory!\n");
 			return NULL;
@@ -571,9 +571,9 @@ static int aji_act_hook(void *data, int type, iks *node)
 										iks_send(client->p, x);
 										iks_delete(x);
 										if (base64)
-											free(base64);
+											ast_free(base64);
 										if (s)
-											free(s);
+											ast_free(s);
 									} else {
 										ast_log(LOG_ERROR, "Out of memory.\n");
 									}
@@ -612,7 +612,7 @@ static int aji_act_hook(void *data, int type, iks *node)
 				asprintf(&handshake, "<handshake>%s</handshake>", shasum);
 				if (handshake) {
 					iks_send_raw(client->p, handshake);
-					free(handshake);
+					ast_free(handshake);
 					handshake = NULL;
 				}
 				client->state = AJI_CONNECTING;
@@ -1113,7 +1113,7 @@ static void aji_handle_message(struct aji_client *client, ikspak *pak)
 	struct aji_message *insert, *tmp;
 	int flag = 0;
 	
-	if (!(insert = ast_calloc(1, sizeof(struct aji_message))))
+	if (!(insert = ast_calloc(1, sizeof(*insert))))
 		return;
 	time(&insert->arrived);
 	if (iks_find_cdata(pak->x, "body"))
@@ -1127,16 +1127,16 @@ static void aji_handle_message(struct aji_client *client, ikspak *pak)
 		if (flag) {
 			AST_LIST_REMOVE_CURRENT(&client->messages, list);
 			if (tmp->from)
-				free(tmp->from);
+				ast_free(tmp->from);
 			if (tmp->message)
-				free(tmp->message);
+				ast_free(tmp->message);
 		} else if (difftime(time(NULL), tmp->arrived) >= client->message_timeout) {
 			flag = 1;
 			AST_LIST_REMOVE_CURRENT(&client->messages, list);
 			if (tmp->from)
-				free(tmp->from);
+				ast_free(tmp->from);
 			if (tmp->message)
-				free(tmp->message);
+				ast_free(tmp->message);
 		}
 	}
 	AST_LIST_TRAVERSE_SAFE_END;
@@ -1173,7 +1173,7 @@ static void aji_handle_presence(struct aji_client *client, ikspak *pak)
 	while (tmp) {
 		if (!strcasecmp(tmp->resource, pak->from->resource)) {
 			tmp->status = status;
-			if (tmp->description) free(tmp->description);
+			if (tmp->description) ast_free(tmp->description);
 			tmp->description = descrip;
 			found = tmp;
 			if (status == 6) {	/* Sign off Destroy resource */
@@ -1190,7 +1190,7 @@ static void aji_handle_presence(struct aji_client *client, ikspak *pak)
 					else
 						buddy->resources = NULL;
 				}
-				free(found);
+				ast_free(found);
 				found = NULL;
 				break;
 			}
@@ -1230,8 +1230,7 @@ static void aji_handle_presence(struct aji_client *client, ikspak *pak)
 	}
 
 	if (!found && status != 6) {
-		found = (struct aji_resource *) malloc(sizeof(struct aji_resource));
-		memset(found, 0, sizeof(struct aji_resource));
+		found = ast_calloc(1, sizeof(*found));
 
 		if (!found) {
 			ast_log(LOG_ERROR, "Out of memory!\n");
@@ -1736,12 +1735,11 @@ static int aji_filter_roster(void *data, ikspak *pak)
 			});
 
 			if (!flag) {
-				buddy = (struct aji_buddy *) malloc(sizeof(struct aji_buddy));
+				buddy = ast_calloc(1, sizeof(*buddy));
 				if (!buddy) {
 					ast_log(LOG_WARNING, "Out of memory\n");
 					return 0;
 				}
-				memset(buddy, 0, sizeof(struct aji_buddy));
 				ASTOBJ_INIT(buddy);
 				ASTOBJ_WRLOCK(buddy);
 				ast_copy_string(buddy->name, iks_find_attrib(x, "jid"), sizeof(buddy->name));
@@ -2064,12 +2062,11 @@ static int aji_create_client(char *label, struct ast_variable *var, int debug)
 	client = ASTOBJ_CONTAINER_FIND(&clients,label);
 	if (!client) {
 		flag = 1;
-		client = (struct aji_client *) malloc(sizeof(struct aji_client));
+		client = ast_calloc(1, sizeof(*client));
 		if (!client) {
 			ast_log(LOG_ERROR, "Out of memory!\n");
 			return 0;
 		}
-		memset(client, 0, sizeof(struct aji_client));
 		ASTOBJ_INIT(client);
 		ASTOBJ_WRLOCK(client);
 		ASTOBJ_CONTAINER_INIT(&client->buddies);
@@ -2161,7 +2158,7 @@ static int aji_create_client(char *label, struct ast_variable *var, int debug)
 		asprintf(&resource, "%s/asterisk", client->user);
 		if (resource) {
 			client->jid = iks_id_new(client->stack, resource);
-			free(resource);
+			ast_free(resource);
 		}
 	} else
 		client->jid = iks_id_new(client->stack, client->user);
@@ -2178,7 +2175,7 @@ static int aji_create_client(char *label, struct ast_variable *var, int debug)
 		asprintf(&resource, "%s/asterisk", client->user);
 		if (resource) {
 			client->jid = iks_id_new(client->stack, resource);
-			free(resource);
+			ast_free(resource);
 		}
 	} else
 		client->jid = iks_id_new(client->stack, client->user);
@@ -2202,12 +2199,11 @@ static int aji_create_transport(char *label, struct aji_client *client)
 
 	buddy = ASTOBJ_CONTAINER_FIND(&client->buddies,label);
 	if (!buddy) {
-		buddy = malloc(sizeof(struct aji_buddy));
+		buddy = ast_calloc(1, sizeof(*buddy));
 		if(!buddy) {
 			ast_log(LOG_WARNING, "Out of memory\n");
 			return 0;
 		}
-		memset(buddy, 0, sizeof(struct aji_buddy));
 		ASTOBJ_INIT(buddy);
 	}
 	ASTOBJ_WRLOCK(buddy);
@@ -2252,12 +2248,11 @@ static int aji_create_buddy(char *label, struct aji_client *client)
 	buddy = ASTOBJ_CONTAINER_FIND(&client->buddies,label);
 	if (!buddy) {
 		flag = 1;
-		buddy = malloc(sizeof(struct aji_buddy));
+		buddy = ast_calloc(1, sizeof(*buddy));
 		if(!buddy) {
 			ast_log(LOG_WARNING, "Out of memory\n");
 			return 0;
 		}
-		memset(buddy, 0, sizeof(struct aji_buddy));
 		ASTOBJ_INIT(buddy);
 	}
 	ASTOBJ_WRLOCK(buddy);
diff --git a/res/res_monitor.c b/res/res_monitor.c
index 7b69b604343566f5448473201e12a03083c014a2..5bff1b1ff985d7e5859bc430f7f18782b0f24412 100644
--- a/res/res_monitor.c
+++ b/res/res_monitor.c
@@ -156,7 +156,7 @@ int ast_monitor_start(	struct ast_channel *chan, const char *format_spec,
 			if (directory) {
 				char *name = strdup(fname_base);
 				snprintf(tmp, sizeof(tmp), "mkdir -p \"%s\"",dirname(name));
-				free(name);
+				ast_free(name);
 				ast_safe_system(tmp);
 			}
 			snprintf(monitor->read_filename, FILENAME_MAX, "%s/%s-in",
@@ -200,7 +200,7 @@ int ast_monitor_start(	struct ast_channel *chan, const char *format_spec,
 						O_CREAT|O_TRUNC|O_WRONLY, 0, AST_FILE_MODE))) {
 			ast_log(LOG_WARNING, "Could not create file %s\n",
 						monitor->read_filename);
-			free(monitor);
+			ast_free(monitor);
 			UNLOCK_IF_NEEDED(chan, need_lock);
 			return -1;
 		}
@@ -213,7 +213,7 @@ int ast_monitor_start(	struct ast_channel *chan, const char *format_spec,
 			ast_log(LOG_WARNING, "Could not create file %s\n",
 						monitor->write_filename);
 			ast_closestream(monitor->read_stream);
-			free(monitor);
+			ast_free(monitor);
 			UNLOCK_IF_NEEDED(chan, need_lock);
 			return -1;
 		}
@@ -321,8 +321,8 @@ int ast_monitor_stop(struct ast_channel *chan, int need_lock)
 				ast_log(LOG_WARNING, "Execute of %s failed.\n",tmp);
 		}
 		
-		free(chan->monitor->format);
-		free(chan->monitor);
+		ast_free(chan->monitor->format);
+		ast_free(chan->monitor);
 		chan->monitor = NULL;
 	}
 
@@ -371,7 +371,7 @@ int ast_monitor_change_fname(struct ast_channel *chan, const char *fname_base, i
 		if (directory) {
 			char *name = strdup(fname_base);
 			snprintf(tmp, sizeof(tmp), "mkdir -p %s",dirname(name));
-			free(name);
+			ast_free(name);
 			ast_safe_system(tmp);
 		}
 
diff --git a/res/res_musiconhold.c b/res/res_musiconhold.c
index ec049482c5a645bbf9903d95373fe8b3962e3a8f..22e44302f7a3b3b555a8ffa78a25a107b8683d11 100644
--- a/res/res_musiconhold.c
+++ b/res/res_musiconhold.c
@@ -175,7 +175,7 @@ static void ast_moh_free_class(struct mohclass **mohclass)
 	int i;
 	
 	while ((member = AST_LIST_REMOVE_HEAD(&class->members, list)))
-		free(member);
+		ast_free(member);
 	
 	if (class->thread) {
 		pthread_cancel(class->thread);
@@ -184,11 +184,11 @@ static void ast_moh_free_class(struct mohclass **mohclass)
 
 	if (class->filearray) {
 		for (i = 0; i < class->total_files; i++)
-			free(class->filearray[i]);
-		free(class->filearray);
+			ast_free(class->filearray[i]);
+		ast_free(class->filearray);
 	}
 
-	free(class);
+	ast_free(class);
 	*mohclass = NULL;
 }
 
@@ -680,7 +680,7 @@ static struct mohdata *mohalloc(struct mohclass *cl)
 	
 	if (pipe(moh->pipe)) {
 		ast_log(LOG_WARNING, "Failed to create pipe: %s\n", strerror(errno));
-		free(moh);
+		ast_free(moh);
 		return NULL;
 	}
 
@@ -712,7 +712,7 @@ static void moh_release(struct ast_channel *chan, void *data)
 	close(moh->pipe[0]);
 	close(moh->pipe[1]);
 	oldwfmt = moh->origwfmt;
-	free(moh);
+	ast_free(moh);
 	if (chan) {
 		if (oldwfmt && ast_set_write_format(chan, oldwfmt)) 
 			ast_log(LOG_WARNING, "Unable to restore channel '%s' to format %s\n", chan->name, ast_getformatname(oldwfmt));
@@ -819,7 +819,7 @@ static int moh_scan_files(struct mohclass *class) {
 	}
 
 	for (i = 0; i < class->total_files; i++)
-		free(class->filearray[i]);
+		ast_free(class->filearray[i]);
 
 	class->total_files = 0;
 	dirnamelen = strlen(class->dir) + 2;
@@ -880,7 +880,7 @@ static int moh_register(struct mohclass *moh, int reload)
 		} else {
 			ast_log(LOG_WARNING, "Music on Hold class '%s' already exists\n", moh->name);
 		}
-		free(moh);	
+		ast_free(moh);	
 		AST_RWLIST_UNLOCK(&mohclasses);
 		return -1;
 	}
@@ -944,7 +944,7 @@ static int moh_register(struct mohclass *moh, int reload)
 static void local_ast_moh_cleanup(struct ast_channel *chan)
 {
 	if (chan->music_state) {
-		free(chan->music_state);
+		ast_free(chan->music_state);
 		chan->music_state = NULL;
 	}
 }
@@ -1061,18 +1061,18 @@ static int load_moh_classes(int reload)
 					strcpy(class->dir, "nodir");
 				} else {
 					ast_log(LOG_WARNING, "A directory must be specified for class '%s'!\n", class->name);
-					free(class);
+					ast_free(class);
 					continue;
 				}
 			}
 			if (ast_strlen_zero(class->mode)) {
 				ast_log(LOG_WARNING, "A mode must be specified for class '%s'!\n", class->name);
-				free(class);
+				ast_free(class);
 				continue;
 			}
 			if (ast_strlen_zero(class->args) && !strcasecmp(class->mode, "custom")) {
 				ast_log(LOG_WARNING, "An application must be specified for class '%s'!\n", class->name);
-				free(class);
+				ast_free(class);
 				continue;
 			}
 
diff --git a/res/res_odbc.c b/res/res_odbc.c
index 735bc98a75e5ce322dfeb763c06df47668166e0e..36b5d116d5dd4b0727f7885f54fed8d3bd63f371 100644
--- a/res/res_odbc.c
+++ b/res/res_odbc.c
@@ -437,7 +437,7 @@ struct odbc_obj *ast_odbc_request_obj(const char *name, int check)
 			if (odbc_obj_connect(obj) == ODBC_FAIL) {
 				ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
 				ast_mutex_destroy(&obj->lock);
-				free(obj);
+				ast_free(obj);
 				obj = NULL;
 			} else {
 				AST_LIST_INSERT_HEAD(&class->odbc_obj, obj, list);
@@ -657,12 +657,12 @@ static int reload(void)
 				AST_LIST_REMOVE_CURRENT(&(class->odbc_obj), list);
 				odbc_obj_disconnect(current);
 				ast_mutex_destroy(&current->lock);
-				free(current);
+				ast_free(current);
 			}
 			AST_LIST_TRAVERSE_SAFE_END;
 
 			AST_LIST_REMOVE_CURRENT(&odbc_list, list);
-			free(class);
+			ast_free(class);
 		}
 	}
 	AST_LIST_TRAVERSE_SAFE_END;
diff --git a/res/res_smdi.c b/res/res_smdi.c
index d84239713f9a9fd3fdaf1da37c3964435cf426a8..f3d695408be490f79cff62c059921a886a8427cc 100644
--- a/res/res_smdi.c
+++ b/res/res_smdi.c
@@ -476,13 +476,13 @@ static void *smdi_read(void *iface_p)
 /*! \brief ast_smdi_md_message destructor. */
 void ast_smdi_md_message_destroy(struct ast_smdi_md_message *msg)
 {
-	free(msg);
+	ast_free(msg);
 }
 
 /*! \brief ast_smdi_mwi_message destructor. */
 void ast_smdi_mwi_message_destroy(struct ast_smdi_mwi_message *msg)
 {
-	free(msg);
+	ast_free(msg);
 }
 
 /*! \brief ast_smdi_interface destructor. */
@@ -502,7 +502,7 @@ void ast_smdi_interface_destroy(struct ast_smdi_interface *iface)
 	ASTOBJ_CONTAINER_DESTROYALL(&iface->mwi_q, ast_smdi_mwi_message_destroy);
 	ASTOBJ_CONTAINER_DESTROY(&iface->md_q);
 	ASTOBJ_CONTAINER_DESTROY(&iface->mwi_q);
-	free(iface);
+	ast_free(iface);
 
 	ast_module_unref(ast_module_info->self);
 }
diff --git a/res/res_speech.c b/res/res_speech.c
index 960c7f42ce38bd194310471b51b164b54b6a54d3..67dce81cfd07ef38e5c3da02d0dc17e88b4c5966 100644
--- a/res/res_speech.c
+++ b/res/res_speech.c
@@ -105,16 +105,16 @@ int ast_speech_results_free(struct ast_speech_result *result)
 		prev_result = current_result;
 		/* Deallocate what we can */
 		if (current_result->text != NULL) {
-			free(current_result->text);
+			ast_free(current_result->text);
 			current_result->text = NULL;
 		}
 		if (current_result->grammar != NULL) {
-			free(current_result->grammar);
+			ast_free(current_result->grammar);
 			current_result->grammar = NULL;
 		}
 		/* Move on and then free ourselves */
 		current_result = current_result->next;
-		free(prev_result);
+		ast_free(prev_result);
 		prev_result = NULL;
 	}
 
@@ -187,7 +187,7 @@ struct ast_speech *ast_speech_new(char *engine_name, int format)
 	/* Pass ourselves to the engine so they can set us up some more and if they error out then do not create a structure */
 	if (engine->create(new_speech)) {
 		ast_mutex_destroy(&new_speech->lock);
-		free(new_speech);
+		ast_free(new_speech);
 		new_speech = NULL;
 	}
 
@@ -211,10 +211,10 @@ int ast_speech_destroy(struct ast_speech *speech)
 
 	/* If a processing sound is set - free the memory used by it */
 	if (speech->processing_sound)
-		free(speech->processing_sound);
+		ast_free(speech->processing_sound);
 
 	/* Aloha we are done */
-	free(speech);
+	ast_free(speech);
 
 	return res;
 }