function final_event_qual= Rsquared_MOD(data,level_pts,Fit_It)

number_of_levels=length(level_pts)-1;
event_qual=zeros(number_of_levels,1);

for i=1:number_of_levels
    
    I_array=data(level_pts(i):level_pts(i+1));
    Fit_I=Fit_It(level_pts(i):level_pts(i+1),2);
    sub_event_size=length(I_array);
    ipt=findchangepts(I_array,'MaxNumChanges',2);

    if isempty(ipt)==0
        ipt=sort(unique([1;ipt(1);ipt(end)-1;sub_event_size]));
        true_levels=length(ipt)-1;
        lvl_length=zeros(true_levels,1);
            for j=1:true_levels
                lvl_length(j)=ipt(j+1)-ipt(j);
            end

        [~,I]=max(lvl_length);
        lvl_data=I_array(ipt(I):ipt(I+1));
        st=ipt(I);
        et=ipt(I+1);
    else
        lvl_data=I_array;
    end
    
    fit_I_data=median(Fit_I);
    event_mean=mean(lvl_data);
    SS_tot=sum((lvl_data-event_mean).^2);  %total sum of squares
    SS_res=sum((lvl_data-fit_I_data).^2);% residual sum of squares
    event_qual(i)=min([(SS_res/SS_tot);(SS_tot/SS_res)]);
end
final_event_qual=mean(event_qual);
end

