function data = tune_measurement(settings)

setup_utilities()

if nargin < 1
    
    dips = {'MS1DIP02','MS1DIP03','MS1DIP04','MS1DIP05','MS1DIP06','MS1DIP07'};
    %dips={'MS1CRV01','MS1CRV02','MS1CRV03','MS1CRV04'};
    
    coeffs = [0.2411, -0.1351, -0.2436, 0.1588, -0.0235, -0.1386]; % Default horizontal coefficients for 42 Mev
    %coeffs = [0,0,0,0];

    scales = [1]; %linspace(-2,2,5);
    bpms = {'IFABPM01','IFABPM02','IFABPM03','IFABPM04'};

    set_magnets = true;
    min_magnet_pause = 1.0;
    n_avg = 1;
    readout_delay = 0.2;
    vmp = 'vm1@erp122:';
    
    % Get full pv names with virtual machine prefix if wanted
    dips = strcat(vmp,dips);
    bpms = strcat(vmp,bpms);
    
else
    
    set_magnets = settings.set_magnets;
    min_magnet_pause = settings.min_magnet_pause;
    n_avg = settings.n_avg;
    readout_delay = settings.readout_delay;
    vmp = settings.vmp;
    
    dips = settings.dips;
    coeffs = settings.coeffs; % Default horizontal coefficients for 42 Mev
    scales = settings.scales; %linspace(-2,2,5);
    bpms = settings.bpms;
    
end

if(length(dips) ~= length(coeffs))
    error('Number of magnet and strength coefficients must bet he same.')
end

initial_dip_data = get_data_from_prefix(dips);
initial_bpm_data = get_data_from_prefix(bpms);

data.Is0 = initial_dip_data.cmd;
data.x0 = initial_bpm_data.x;
data.y0 = initial_bpm_data.y;
data.x0err = initial_bpm_data.x_err;
data.y0err = initial_bpm_data.y_err;

xs = nan(length(scales),length(bpms));
ys = nan(length(scales),length(bpms));
xerrs = nan(length(scales),length(bpms));
yerrs = nan(length(scales),length(bpms));

mstates = {};
mstates{end+1}=get_machine_state();

set_ref = true;
%if(strcmp(vmp,''))
%    set_ref = false;
%end

for ii=1:length(scales)

    dIs = scales(ii)*coeffs';
    if(set_magnets)
        set_pvs(dips,data.Is0+dIs,set_ref);
    end
    
    pause(min_magnet_pause)
    
    mstates{end+1}=get_machine_state();
    
    tdat = get_data_from_prefix(bpms, n_avg, readout_delay);
    xs(ii,:) = tdat.x; 
    ys(ii,:) = tdat.y;
        
    xerrs(ii,:) = tdat.x_err;
    yerrs(ii,:) = tdat.y_err;
    
end

if(set_magnets)
    set_pvs(dips,data.Is0,set_ref);
end

data.mstates = mstates;
data.xs = xs;
data.ys = ys;
data.xerrs = xerrs;
data.yerrs = yerrs;
data.dips = dips;
data.bpms = bpms;
data.scales = scales;
data.coeffs = coeffs;
data.set_ref = set_ref;

end

function set_pvs(pvs,vals,set_ref)

for ii=1:length(pvs)-1
    %p = get_pvs_from_prefix(pvs{ii});
    %lcaPut(p.cmd.name, vals(ii));
    lcaPut([pvs{ii} '_cmd'],vals(ii));
    display(['Setting cmd: ' pvs{ii}])
    if(set_ref)
        display(['Setting save: ' pvs{ii}])
        lcaPut([pvs{ii} '_save'],vals(ii));
    end
end

set_cmd_from_prefix(pvs{end},[vals(end) vals(end)],false,10);

end


function setup_utilities()

mfile_dir = fileparts(mfilename('fullpath'));
addpath(genpath(fullfile(mfile_dir, '..', '..', 'utilities')));

end