%resolution_modulation.m
%calculates the results/modulation

function [Results]=resolution_modulation(STARCAL,centerx,centery,segfactor,ds,size_part,segments,h,periods);

p=periods;

nyq=p/pi-(0.25*p/pi);

nyquist=p/pi;
ph=h;

segset=0;
if segments==8
    segments=24;
    size_part=1/24;
    segset=1;
end

dphi = size_part * 2*pi;

for nn=1:segments
    if nn ==1
        phivon = (segments * pi / 2 - dphi) / (segments/4);
    else
        phivon = ((nn-1) * pi / 2 - dphi) / (segments/4);
    end    
    rdct = 1;
   

       for rd=round(nyq:0.5*ds)
        [Results(rdct,nn+1)]=resolution_modulation_fit(STARCAL, centery, centerx, [rd*segfactor(1,nn)], phivon, dphi, p);
        
        if nn==1
            Results(rdct,1)=(p*ph)/(2*rd*pi); 
        end
        rdct =rdct+1;
      end 

end

if segset==0
    Results(1,(segments+2))=(p*ph)/(2*nyquist*pi);  
else
    Results=ressegreduct(Results);
    segments=8;
    Results(1,(segments+2))=(p*ph)/(2*nyquist*pi); 
end

function Resultst=ressegreduct(Results)

off1=-2;
off2=-1;
off3=0;
for n=2:9
    
    if n==2
        Resultst(:,n)=mean([Results(:,2) Results(:,3) Results(:,25)],2);
    else
        
    Resultst(:,n)=mean([Results(:,2*n+off1) Results(:,2*n+off2) Results(:,2*n+off3)],2);
    off1=off1+1;
    off2=off2+1;
    off3=off3+1;
    end
end

Resultst(:,1)=Results(:,1);