
% ------------------------------------------------------------------------
% Function: fitgamma (Ux, SFE)
% ------------------------------------------------------------------------
% Aim:
% To determine the restrofing force by deriving the GSFE
% ------------------------------------------------------------------------

function [ Uxdata, RestoringForce ] = fitgamma( Ux, SFE )

    global BurVect;
    global filepath;
    global gammafitresult;
    global SFEfit;

    % % To fit the gamma surface
    
    [gammafunc, gof]=gammaFit1d(Ux,SFE);
    
    fprintf('\n');
    if gof.rsquare >= 0.9800
        fprintf('        >> The rsquare of fitting gamma surface is %10.4f \n', gof.rsquare);
    else
        fprintf('        >> WARNING!!!  The rsquare of fitting gamma surface is < 0.9800 \n');
    end
    
    % % To output the fit values SFEfit
    
    SFEfit=gammafunc(Ux);
    
    % % To save the figure

    figurefile=strcat(filepath,'/fitgamma.fig');
    saveas(1,figurefile);
    close(figure(1));

    fprintf('        >> The figure of SFE vs displacement is ploted and saved as "fitgamma.fig" \n');
    
    % % The gamma fitting function, which has high efficiency

        temp_AA=coeffnames(gammafunc);
        temp_BB=coeffvalues(gammafunc);

        temp_gfit=formula(gammafunc);
        for ii=1:numcoeffs(gammafunc)
            temp_gfit=subs(temp_gfit,temp_AA{ii},temp_BB(ii));
        end
        temp_gfit=vpa(temp_gfit,4);

        % % % To define the function 'gammafitresult'
        eval(strcat('gammafitresult=@(Ux)',char(temp_gfit),';'));
    
    %% (GPa)
    
    dsfe=diff(gammafitresult(0:0.0001:1))/0.0001;
    RestoringForce=-dsfe(600:50:9500)'*10/BurVect;
    
    xxx=[(0.0001/2):0.0001:(1-0.0001/2)]';
    Uxdata=xxx(600:50:9500)*BurVect;

    plot(Uxdata,RestoringForce);
    
    title('Restoring force vs. displacement u');
    xlabel('Disregistry vector u/b');
    ylabel('Restoring force (GPa)');
    
    % % To save the figure

    figurefile=strcat(filepath,'/restoring_force.fig');
    saveas(1,figurefile);
    close(figure(1));

    fprintf('        >> The figure of restoring force vs. disregistry vector u is ploted and saved as "restoring_force.fig" \n');
    fprintf('\n');

end

