%Init tempspecs

%Use lsqnonlin or fsolve to initialize for the optimization using fmincon, so fmincon
%always gets a feasible starting point.

disp('Trying to initialize to feasible starting point')

T0 = x0(4:8) ;
x0_init = [x0(1:3) ; x0(9:11)] ;

tolcon = options.TolCon ; 

fsolve_options = optimset('Display','off','MaxIter',100,'TolFun',1e-7,'TolX',1e-7,'Algorithm','trust-region-reflective') ; % ,'Algorithm','levenberg-marquardt' 'trust-region-reflective'
parameters.solver = 'fsolve' ;
[T,fval,exitflag] = fsolve(@MCHE_UA_RES,T0,fsolve_options,x0_init,d,parameters) ;

% lsqnonlin_options = optimset('Display','off','MaxIter',100,'TolFun',0.1*(tolcon)^2,'Algorithm','levenberg-marquardt') ;
% parameters.solver = 'lsqnonlin' ;
% [T,resnorm,residual,exitflag] = lsqnonlin(@MCHE_UA_RES,T0,[],[],lsqnonlin_options,x0_init,d,parameters) ;

%If successful, replace temperatures in original x0 with new ones
if exitflag > 0
    disp('Initialization successful')
    x0 = [x0_init(1:3) ; T ; x0_init(4:6)]; 
else
    disp('Initialization failed miserably')
end