Further modification of function modefit_mg.R