clear all
close all
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% fastP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
cut1=3770;cut2=11250;
xMAX=8135;
xf=(cut1-xMAX:1:cut2-xMAX);
xcmfp=0;
xcmfm=0;
ymeanP=xf*0;
ymeanM=xf*0;
%%%%%%%%% legge i file con eterodina positiva fast %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
limBKGD=7800;
filecommon='sio2_maggio10_1736';
figure(50)
fi=dir([filecommon '*']);
index1=[];
index2=[];

for kk=[1:7];
	index1=[index1,kk];
    kk
	file=[filecommon '_' num2str(kk)];
	str=['load ' file '.dat'];eval(str);
	str=['x=' file '(:,1);'];eval(str);
	str=['y=' file '(:,2);'];eval(str);                
	str=['N=' file '(:,3);'];eval(str);
      
    nn=find(x>cut1 & x<cut2);x=x(nn);y=y(nn);
    nn=find(x<limBKGD);y=y-mean(y(nn)); %y=y/max(y);
      
    [A,B]=butter(20,0.2,'low');
    yf=filter(A,B,y);
    nn=find(yf>0.85*max(yf));xcm=sum(x(nn).*yf(nn))/sum(yf(nn));x=x-xcm;  
    y=interp1(x,yf,xf,'linear',NaN);
    
    figure(333);
    plot(xf,y);ylim([-0.02 0.02])

    ymeanP=ymeanP+y;
    xcmfp=xcmfp+xcm;
    str=['clear ' file ];eval(str);
    figure(50);
    hold on;plot(xf,y,'g');
end


hold on
plot(xf,(ymeanM+ymeanP)/(length(index1)+length(index2)),'r');
hold off


YY=(ymeanM+ymeanP)/(length(index1)+length(index2));
jj=find(isnan(YY)==0); xfnew=xf(jj); Ynew=YY(jj);

jj=find(isnan(YY)==0);
figure(101)
xx=xf(jj)*0.52733333; yy=YY(jj)/max(YY(jj));
plot(xx,yy)

  
nn1=find(xx<-500); nn2=find(xx>500); nn=[nn1 nn2];  P=polyfit(xx(nn),yy(nn),1);
Ybkg=polyval(P,xx);

figure(11)
subplot(2,1,1); semilogy(xx,yy-Ybkg,xx,yy)
subplot(2,1,2); plot(xx,yy,xx,Ybkg)

if 0, 
    AA=[xx' (yy-Ybkg)']; str=['save ' filecommon '.dat AA -ascii;'];eval(str);
end;
 