function [distance_val, model_momm, average_failure_rate, ...
    average_gdp_loss, mean_negative_equity_at_default]=...
    distance_function_constraints_spreads(distance_param,data_momm,wtmat,...
    M00_,M10_,M01_,M11_,oo00_,...
    options00_,constraint1, constraint2,...
    constraint_relax1, constraint_relax2)


global overwrite overwrite_param_names

overwrite = distance_param;

%global M_ oo_

char('sigma_eps_a','sigma_eps_isp','sigma_eps_tau',...
    'rhop_a','rho_isp','rho_taup','phip_i','kappap','xip','taup');

sigma_eps_a = distance_param(1);
sigma_eps_isp = distance_param(2);
sigma_eps_tau = distance_param(3);
rho_a = distance_param(4);
rho_isp = distance_param(5);
rho_taup = distance_param(6);
phip_i = distance_param(7);
kappap = distance_param(8);
xip = distance_param(9);
taup = distance_param(10);



if rho_isp<0.99 && rho_isp>0 && ...
        rho_a<.99 && rho_a >0 && rho_taup<.99 && rho_taup>0 &&...
        phip_i >0 && kappap>0 && kappap<.95 &&...
        sigma_eps_isp > 0.0001 &&  sigma_eps_a>0.0001 && sigma_eps_tau>0.0001 &&...
        xip>0 && taup>0


    %try
    nperiods = 25;
    nperiods_shocks = 5000;
    maxiter = 20;
    irf_shock = char('eps_a','eps_isp','eps_tau');
    randn('seed',1);
    nshocks = size(irf_shock,1);
    shockssequence = randn(nperiods_shocks,nshocks);

    [zdatapiecewise_, zdatass_, oo00_,  M00_, violvecbool_last_shock, check] = ...
        solve_two_constraints_add_violvecbool_no_parse_short(M00_,M10_,M01_,M11_,oo00_,...
        options00_,constraint1, constraint2,...
        constraint_relax1, constraint_relax2,...
        shockssequence,irf_shock,nperiods,0,maxiter);

    if check==0

        
        [model_momm,...
          mean_negative_equity_at_default,...
          average_failure_rate,...
          average_gdp_loss]=make_moments(M00_,zdatapiecewise_,zdatass_);  
            
        distance_val = (model_momm-data_momm)'*wtmat*(model_momm-data_momm)/(sum(sum(wtmat)));
        distance_val = distance_val +...
            (1 - average_failure_rate/0.003799874586704)^2 +...
            (1-(average_gdp_loss/(-0.331394920309664)))^2;
        % (1 - mean_negative_equity_at_default/0.01927)^2;           

    else
        model_momm = nan;
        average_failure_rate = nan;
        average_gdp_loss = nan;
        mean_negative_equity_at_default = nan;
        distance_val = 10000000;
    end

else
    model_momm = nan;
    average_failure_rate = nan;
    average_gdp_loss = nan;
    mean_negative_equity_at_default= nan;
    distance_val = 10000000;
end
 


