function [x,xproj,y,yproj,ts,p,maxpix]=Jgetimagesave(deviceName,plotflag,init)
%function [p,imageArray,imagePositionSet1,imagePositionsSet2]=Jgetimage(deviceName)
% Initialise RDA
persistent pbg merkbg;
javaMethod('setProperty', 'java.lang.System', 'cmw.names', 'abcmw.cern.ch:5020');
rda = cern.cmw.rda.client.RDAService.init();

cycle = 'SCT:USER:SETUP';

device = rda.getDeviceHandle(deviceName);

if init==1
    % background measurement
    image = device.get('Image', cycle);
    imageArray = image.extractShortArray('imageSet');
    x = image.extractDoubleArray('imagePositionSet1');
    y = image.extractDoubleArray('imagePositionSet2');
    ts = char(image.extractString('acqTime'));
    nx=length(x);
    ny=length(y);
    pbg=zeros(nx,ny);
    for i=1:ny,
        pbg(:,i)=imageArray((i-1)*nx+1:i*nx);
    end
    merkbg=1;
    p=[];x=[];xproj=[];y=[];yproj=[];maxpix=[];
    return
elseif init==2
    % Set camera acquisition on
    ExpertSettingProp='ExpertSetting';
    ExpertSettingFields=device.get(ExpertSettingProp,cycle);
    xmin=ExpertSettingFields.extractShort('windowOriginX_min')
    xmax=ExpertSettingFields.extractShort('windowSizeX_max')
    xact=ExpertSettingFields.extractShort('windowSizeX')
    ymin=ExpertSettingFields.extractShort('windowOriginY_min')
    ymax=ExpertSettingFields.extractShort('windowSizeY_max')
    yact=ExpertSettingFields.extractShort('windowSizeY')
    ExpertSettingFields.insert('windowOriginX',int16(xmin+7));
    ExpertSettingFields.insert('windowSizeX',int16(xmax-7));
    ExpertSettingFields.insert('windowOriginY',int16(ymin+11));
    ExpertSettingFields.insert('windowSizeY',int16(ymax-11));
%    ExpertSettingFields.insert('cameraSwitch',int32(3));
    ExpertSettingFields.insert('alwaysAcquire',logical(1));
    ExpertSettingFields.insert('startAcquisition',logical(1));

    device.set(ExpertSettingProp,cycle,ExpertSettingFields);
elseif init==3
    % Set camera acquisition off
    ExpertSettingProp='ExpertSetting';
    ExpertSettingFields=device.get(ExpertSettingProp,cycle);
%    ExpertSettingFields.insert('screenSelect',int32(0));
%    ExpertSettingFields.insert('cameraSwitch',int32(2));
    ExpertSettingFields.insert('alwaysAcquire',logical(0));
    ExpertSettingFields.insert('startAcquisition',logical(0));
    device.set(ExpertSettingProp,cycle,ExpertSettingFields);
    p=[];x=[];xproj=[];y=[];yproj=[]; ts='';maxpix=[];;
    return
elseif init==4
    merkbg=0;
    p=[];x=[];xproj=[];y=[];yproj=[];ts='';maxpix=[];;
    return
end

image = device.get('Image', cycle);
imageArray = image.extractShortArray('imageSet');
x = image.extractDoubleArray('imagePositionSet1');
y = image.extractDoubleArray('imagePositionSet2');
ts = char(image.extractString('acqTime'));
nx=length(x);
ny=length(y);
p=zeros(nx,ny);
Imag=Jgetcontrolval('CL.BHB1040','CCV');

for i=1:ny,
    p(:,i)=imageArray((i-1)*nx+1:i*nx);
end
ph=( p(1:nx-2,1:ny-2)+p(1:nx-2,2:ny-1)+p(1:nx-2,3:ny)...
    +p(2:nx-1,1:ny-2)+p(2:nx-1,2:ny-1)+p(2:nx-1,3:ny)...
    +p(3:nx  ,1:ny-2)+p(3:nx  ,2:ny-1)+p(3:nx  ,3:ny))/9;
maxpix=max(max(ph));
if merkbg
    p=p-pbg;
end
if min(x)==max(x)
    x=1:length(x);
    nocalibxflag=1;
else
    nocalibxflag=0;
end
if min(y)==max(y)
    y=1:length(y);
    nocalibyflag=1;
else
    nocalibyflag=0;
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Save entire image matrix to file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

savefile=['c:\temp\' deviceName '_' sprintf('%2.2f',Imag) '.dat']
save(savefile,'p','-ascii', '-double', '-tabs')

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Calculate Projections and save
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

xproj=sum(p')';
savefile=['c:\temp\xproj_' deviceName '_' sprintf('%2.2f',Imag) '.dat']
save(savefile,'xproj','-ascii', '-double', '-tabs')

yproj=sum(p)';
savefile=['c:\temp\yproj_' deviceName '_' sprintf('%2.2f',Imag) '.dat']
save(savefile,'yproj','-ascii', '-double', '-tabs')

%xproj=sum(p(:,y>0 & y<30)')';
clf
if plotflag==1
    surf(y,x,p,'FaceColor','interp',...
        'EdgeColor','none',...
        'FaceLighting','phong')
    % daspect([5 5 1])
    axis tight
    view(-50,30)
    camlight left
    xlabel('X (mm)')
    ylabel('Y (mm)')
    title([deviceName '     ' ts(1:(length(ts)-7))])
elseif plotflag==2
    clf
    %[dummy,hc]=contourf(x,y,p',20);
    %set(hc,'linestyle','none');
    surface(x,y,p','linestyle','none');
%    surf(x,y,p','linestyle','none');
    if nocalibxflag
        xlabel('X (pixel)')
    else
        xlabel('X (mm)')
    end
    if nocalibyflag
        ylabel('Y (pixel)')
    else
        ylabel('Y (mm)')
    end
    title([deviceName '     ' ts(1:(length(ts)-7))])
    axis tight;
    caxis([0 sqrt(max(max(p))/(2^10-1))*(2^10-1)]);
    a=axis;
    hold on
    sxproj=0.5*(xproj-min(xproj))/(max(xproj)-min(xproj))*(a(4)-a(3))+a(3);
    syproj=0.5*(yproj-min(yproj))/(max(yproj)-min(yproj))*(a(2)-a(1))+a(1);
    hx=plot3(x,sxproj,ones(size(x))*max(max(p)),'y-');
    hy=plot3(syproj,y,ones(size(y))*max(max(p)),'y-');
    hold off
end
