close all
clear all
clc
savedirname=cd;

navg=7;
nkickers = 1;
kick=0.75;
itreshold = -0.1; %we read positions only if there is less then this current


%cd g:\users\c\ctfop\Public\ctf3emit
%!cd c:\Docume~1\desklpi\peter\ctf3emit


%navg=input('Number of measurements for average?');

%%%%%%%%%%%%%%%%
%%% Open file %%
%%%%%%%%%%%%%%%%
timestepf = now*10000;
filnam=['c:\temp\bpx' sprintf('%10.0f',timestepf) '.dat'];
dhfsetname=['c:\temp\dhf' sprintf('%10.0f',timestepf) '.dat'];
dvfsetname=['c:\temp\dvf' sprintf('%10.0f',timestepf) '.dat'];


fpo=fopen(filnam,'w');
dhf=fopen(dhfsetname,'w');
dvf=fopen(dvfsetname,'w');

readprop='AQN2'; 

turntiming= [6450, 6720, 7000];


         %'CR.DHF0145-S'; 
         
kickers=['CR.DHF0145-S';
         'CR.DHF0200  ';
         'CR.DHF0242  ';
         'CR.DHF0252  ';
         'CR.DHF0292  ';
         'CR.DHF0345  ';
         'CR.DHF0408  ';
         'CR.DHF0452  ';
         'CR.DHF0492  ';
         'CR.DHF0542  ';
         'CR.DHF0582  ';
         'CR.DHF0630  ';
         'CR.DHF0655  ';
         'CR.DHF0700  ';
         'CR.DHF0742  ';
         'CR.DHF0792  ';
         'CR.DHF0845  ';
         'CR.DHF0855  ';
         'CR.DHF0908  ';
         'CR.DHF0948  ';
         'CR.DHF0958  ';
         'CR.DHF1000  ';
         'CR.DHF1055  ' ];      

   
     

quadnames=['CR.IQFG0120';
           'CR.IQDG0140';
           'CR.IQDF0160';
           'CR.IQFF0190';
           'CR.IQFJ0215';
           'CR.IQDJ0230';
           'CR.IQFJ0245';
           'CR.IQFJ0320';
           'CR.IQDH0340';
           'CR.IQFF0510';
           'CR.IQDF0540';
           'CR.IQDG0560';
           'CR.IQFG0580';
           'CR.IQFJ0715';
           'CR.IQDJ0730';
           'CR.IQFJ0745';
           'CR.IQFJ0820';
           'CR.IQDH0840';];

quadconames=['CR.QFG0120-S';
             'CR.QDG0140-S';
             'CR.QDF0160-S';									
             'CR.QFF0190-S';									
             'CR.QFJ0215-S';									
             'CR.QDJ0230-S';									
             'CR.QFJ0245-S';									
             'CR.QFJ0320-S';									
             'CR.QDH0340-S';									
             'CR.QFF0510-S';									
             'CR.QDF0540-S';
             'CR.QDG0560-S';									
             'CR.QFG0580-S';									
             'CR.QFJ0715-S';									
             'CR.QDJ0730-S';									
             'CR.QFJ0745-S';									
             'CR.QFJ0820-S';									
             'CR.QDH0840-S'];
       
bendname= 'CR.IBENDS';
bendconame='CR.BHF0205-S';

wiglename=['IWHA350A';
           'IWHA350B'];
           
wigleconame=['CR.WHA0350-A';
             'CR.WHA0350-B']

cd ('crorbit');
  HCorrectors;
  HMonitors;
  nbpms = length(Monitor);
  if (nkickers > length(Corrector))
      nkickers = length(Corrector);
  end
  fprintf(1,'Number of correctors %d\n', length(Corrector));
  fprintf(1,'Number of Monitors %d\n', nbpms);
cd('g:/users/c/ctfop/Public/ctf3emit');

         
if(1)
  getmadxrespmtx;
  cpcmd=['copy crorbit\currents c:\temp\currents' sprintf('%10.0f',timestepf) '.dat'];
  system(cpcmd);
  fprintf(1,'Exited getmadxrespmtx\n');
end  


%for i=1:nbpms,
%   
%    asigname = strcat(Monitor(i).name,'S-C');
%    fprintf(1,'%d %s 1St Turn Delay is %f\n',i,asigname,turntiming(1));
%    tmpx= Jgetcontrolval(asigname,'STRT');
%    Jsetcontrolval(asigname,'STRT',turntiming(1));
%    return;
%    
%    asigname = strcat(Monitor(i).name,'H-C');
%    Jsetcontrolval(asigname,'CURSOR',turntiming(1));
%    asigname = strcat(Monitor(i).name,'V-C');
%    Jsetcontrolval(asigname,'CURSOR',turntiming(1));
%end
%return;



referenceH=zeros(nbpms,navg);
referenceV=zeros(nbpms,navg);
current=zeros(nbpms,1);

orbitH=zeros(nbpms,navg);
orbitV=zeros(nbpms,navg);

%Write configuration line NoMonitors NoKickers ### MonName1 MonName2 
%Obly not faulty are listed and present in the output file
fprintf(fpo,'%d\t%d\t###\t',nbpms, nkickers);
for i=1:nbpms,
  if(Monitor(i).faulty)
     fprintf(1,'\nSkipping faulty monitor no %d\n',i);
     continue;
  end
  fprintf(fpo,'%s\t',Monitor(i).name);
end
fprintf(fpo,'\n');




diffH=zeros(nbpms,nkickers);
diffV=zeros(nbpms,nkickers);

kicker=1;
nkicked = 1;
while (nkicked <= nkickers )

   if(Corrector(kicker).faulty)
       fprintf(1,'\nSkipping faulty kicker no %d\n',kicker);
       kicker = kicker + 1;
       continue;
   end
    

   akicker = strtrim(Corrector(kicker).name);
   inikick = Jgetcontrolvalfesa(akicker,'Setting');
   fprintf(1,'\nCurrent kick of %s is %f\n',akicker, inikick);
   
  
   for j=1:navg,
     for i=1:nbpms,
 
       if(Monitor(i).faulty)
          fprintf(1,'\nSkipping faulty monitor no %d\n',i);
          continue;
       end

       asigname = strcat(Monitor(i).name,'S-C');
       current(i,1) = 0;
       fprintf(1,'%d %s Current is %f\n',i,asigname,current(i,1));
    
       while (current(i,1) > itreshold),
          current(i,1) = Jgetcontrolval(asigname,readprop);    
          fprintf(1,'%d %s Current is %f\n',i,asigname,current(i,1));
          if (current(i,1) > itreshold)
              fprintf(1,'%d %s Current is TOO LOW %f waiting\n',i,asigname,current(i,1));
              pause(1.2);
          end
       end


       asigname = strcat(Monitor(i).name,'H-C');
       referenceH(i,j) = nan;
       while (isnan(referenceH(i,j))),
         referenceH(i,j) = Jgetcontrolval(asigname,readprop);
         fprintf(1,'%d %s Xpos %f\n',i,asigname,referenceH(i,j));
       end  

       fprintf(dhf,'%f ',referenceH(i,j));
       
       asigname = strcat(Monitor(i).name,'V-C');
    
       referenceV(i,j) = nan;
       while (isnan(referenceV(i,j))),
          referenceV(i,j) = Jgetcontrolval(asigname,readprop);
          fprintf(1,'%d %s Xpos %f\n',i,asigname,referenceV(i,j));
       end 
       fprintf(dvf,'%f ',referenceV(i,j));
       
     end
     fprintf(dhf,'\n');
     fprintf(dvf,'\n');
     pause(1.2);
   end

   referenceHmean = mean(referenceH,2);
   referenceVmean = mean(referenceV,2);

   
   fprintf(fpo,'%d %s %f REF',kicker,akicker,inikick);
   for i=1:nbpms,
     fprintf(fpo,' %f ',referenceHmean(i));
   end
   fprintf(fpo,'\n');

   for i=1:nbpms,
     fprintf(1,'%d mean=%f of ',i,referenceHmean(i));
     for j=1:navg,
       fprintf(1,' %f',referenceH(i,j));
     end
     fprintf(1,'\n');
   end

  

   %SET THE KICKER
   
   
   Jsetcontrolvalfesa(akicker,'Setting',inikick+kick);

   pause(3);

   currentkick = Jgetcontrolvalfesa(akicker,'Setting');
   fprintf(1,'\nNew kick of %s is %f\n',akicker, currentkick);



   for j=1:navg,
     for i=1:nbpms,
       
       if(Monitor(i).faulty)
         fprintf(1,'\nSkipping faulty monitor no %d\n',i);
         continue;
       end

       asigname = strcat(Monitor(i).name,'S-C');

       current(i,1) = 0;
       while (current(i,1) > itreshold),
         current(i,1) = Jgetcontrolval(asigname,readprop);    
         fprintf(1,'%d %s Current is %f\n',i,asigname,current(i,1));
       end

       asigname = strcat(Monitor(i).name,'H-C');
       orbitH(i,j) = Jgetcontrolval(asigname,readprop);
       fprintf(1,'%d %s Xpos %f\n',i,asigname,orbitH(i,j));

       asigname = strcat(Monitor(i).name,'V-C');
       orbitV(i,j) = Jgetcontrolval(asigname,readprop);
       fprintf(1,'%d %s Xpos %f\n',i,asigname,orbitV(i,j));
     end
     pause(1.2);
   end



   orbitHmean = mean(orbitH,2);
   orbitVmean = mean(orbitV,2);

   for i=1:nbpms,
     fprintf(1,'%d orbit mean=%f of ',i,orbitHmean(i));
     for j=1:navg,
       fprintf(1,' %f',orbitH(i,j));
     end
     fprintf(1,'\n');
   end

   for i=1:nbpms,
     diffH(i,kicker) = orbitHmean(i) - referenceHmean(i);
     fprintf(1,'diff=%f orbit=%f reference=%f\n',diffH(i,kicker),orbitHmean(i),referenceHmean(i));
   end

   fprintf(fpo,'%d %s %f DIF',kicker,akicker,kick);
   for i=1:nbpms,
     fprintf(fpo,' %f ',diffH(i,kicker));
   end
   fprintf(fpo,'\n');



  Jsetcontrolvalfesa(akicker,'Setting',inikick);
  currentkick = Jgetcontrolvalfesa(akicker,'Setting');

  fprintf(1,'\nBring back old kick of %s is %f\n',akicker, currentkick);
  
  pause(3);
  
  kicker = kicker + 1;
  nkicked = nkicked + 1;

end %end of loop over kickers


for kicker=1:nkickers,
  for i=1:nbpms,
      fprintf(1,'BPI no %d Kicker %d diff=%f \n',i, kicker, diffH(i,kicker));
  end
end

fclose(fpo);
fclose(dhf);
fclose(dvf);

return;


cd ('crorbit');


Orbit_correction(referenceHmean);

cd('g:/users/c/ctfop/Public/ctf3emit');


return;
































































reference(i,2) = Jgetcontrolval('CR.SVBPM0155H-C','CCV');
reference(i,3) = Jgetcontrolval('CR.SVBPM0195H-C','CCV');
reference(i,4) = Jgetcontrolval('CR.SVBPI0208H-C','CCV');
reference(i,5) = Jgetcontrolval('CR.SVBPI0248H-C','CCV');
reference(i,6) = Jgetcontrolval('CR.SVBPI0275H-C','CCV');
reference(i,7) = Jgetcontrolval('CR.SVBPI0305H-C','CCV');
reference(i,8) = Jgetcontrolval('CR.SVBPI0395H-C','CCV');
reference(i,1) = Jgetcontrolval('CR.SVBPI0425H-C','CCV');
reference(i,1) = Jgetcontrolval('CR.SVBPI0475H-C','CCV');
reference(i,1) = Jgetcontrolval('CR.SVBPI0570H-C','CCV');
reference(i,1) = Jgetcontrolval('CR.SVBPM0650H-C','CCV');
reference(i,1) = Jgetcontrolval('CR.SVBPM0695H-C','CCV');
reference(i,1) = Jgetcontrolval('CR.SVBPI0708H-C','CCV');
reference(i,1) = Jgetcontrolval('CR.SVBPI0775H-C','CCV');
reference(i,1) = Jgetcontrolval('CR.SVBPI0895H-C','CCV');
reference(i,1) = Jgetcontrolval('CR.SVBPI0925H-C','CCV');
reference(i,1) = Jgetcontrolval('CR.SVBPM1025H-C','CCV');
reference(i,1) = Jgetcontrolval('CR.SVBPI1070H-C','CCV');




c1i=Jgetcontrolval('CL.QFA0460','CCV');
c2i=Jgetcontrolval('CL.QDA0465','CCV');

pbeam=input('Beam momentum on girder 5 (MeV)=');


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Acquire an image for background substraction %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

JsetcontrolvalInt('CX.SGUN','ENABLE',0);
pause(0.5);


%%%%%%%%%%%%%%
%%% Gun on %%%
%%%%%%%%%%%%%%
JsetcontrolvalInt('CX.SGUN','ENABLE',1);
gti=JgetcontrolvalInt('CX.TGUN','CCV')


for i=1:ncur,
        Jsetcontrolval('CL.QFA0460','CCV',ctab(i,1));
        Jsetcontrolval('CL.QDA0465','CCV',ctab(i,2));

        Jsetcontrolvalfesa('CR.QDF0160-S','Setting',ctab(i,1));
        Jsetcontrolvalfesa('CR.QFF0190-S','Setting',ctab(i,2));
end
        
fprintf(1,'Count %d  si %f siref %f  (abs(si-siref)/siref)  %6.3f  rmsi %f',count, si, siref, (si-siref)/siref, rmsi );

return

    figure(1)
    subplot(211)
    plot(xp,sx,'b',xp,sxfit,'r-')
    a=axis;
    hold on
    plot([posx(i) posx(i)],[a(3) a(4)],'k',[posx(i)-rmsx(i) posx(i)-rmsx(i)],[a(3) a(4)],'r',...
        [posx(i)+rmsx(i) posx(i)+rmsx(i)],[a(3) a(4)],'r');
    axis tight
    hold off
    subplot(212)
    plot(yp,sy,'b',yp,syfit,'r-')
    hold on
    a=axis;
    plot([posy(i) posy(i)],[a(3) a(4)],'k',[posy(i)-rmsy(i) posy(i)-rmsy(i)],[a(3) a(4)],'r',...
        [posy(i)+rmsy(i) posy(i)+rmsy(i)],[a(3) a(4)],'r');
    axis tight
    hold off

fclose(fpo);


%
% Set the quadrupole to the initial value
%

if NGirder==5
    Jsetcontrolval('CL.QFA0460','CCV',c1i);
    Jsetcontrolval('CL.QDA0465','CCV',c2i);
elseif NGirder==10
    Jsetcontrolval('CL.QDB1005','CCV',c1i);
    Jsetcontrolval('CL.QFC1010','CCV',c2i);
    Jsetcontrolval('CL.QDB1015','CCV',c3i);
elseif NGirder==15
    Jsetcontrolval('CT.QDF0410','CCV',c1i);
    Jsetcontrolval('CT.QFF0420','CCV',c2i);
elseif NGirder==20
    Jsetcontrolval('CT.QDD0520','CCV',c1i);
    Jsetcontrolval('CT.QFD0530','CCV',c2i);
elseif NGirder==25
    Jsetcontrolvalfesa('CR.QDF0160-S','Setting',c1i);
    Jsetcontrolvalfesa('CR.QFF0190-S','Setting',c2i);
end

JsetcontrolvalInt('CX.TGUN','CCV',gti);
[xp,sx0,yp,sy0,dat0,pdummy,maxpix]=Jgetimage(nameMTV,0,3);
dates=date;
timvec=clock;
%analyseemimeasnew
figure(2)
n=length(six);
subplot(211)
plot(1:n,six,1:n,siy)
a=axis;
axis([a(1) a(2) 0 a(4)])
ylabel('integrated intensity')
title('Quality control panel')
legend('horizontal profile','vertical profile')
subplot(212)
plot(maxpixa);
ylabel('maximum pixel reading')
a=axis;
axis([a(1) a(2) 0 2^12])

analyseemimeas
cd(savedirname);
