%**************************************************************************
%This function calculates which shims must be replaced in order to
%set the gap.  Shims have a fixed adjustment range.
%If the required adjustment is outside the range, the shim must be replaced.  
%
%Input:
%shim_param, structure containing program parameters
%setgap_shim_dgap, required gap change of the undulator (m) 
%
%Output:
%setgap_shim_replace, shim thickness change required from the replacement (m)
%setgap_shim_dgap_after_replace, requied gap change after the shims are replaced (m)
%
%Zachary Wolf, 11/26/07

function [setgap_shim_replace, setgap_shim_dgap_after_replace] = setgap_calc_shim_replace(shim_param, setgap_shim_dgap)

%Each shim does half the gap change
%Upper and lower shims change in the same way
%Increasing the gap requires thinner shims
setgap_shim_change = -setgap_shim_dgap / 2;

%Shim replacements
setgap_shim_change_abs = abs(setgap_shim_change);
index_array = find(setgap_shim_change_abs > shim_param.setgap_shim_range / 2);
num_size_change = round(setgap_shim_change_abs(index_array) / shim_param.setgap_shim_bin_size);
setgap_shim_replace = zeros(1, length(setgap_shim_change));
setgap_shim_replace(index_array) = sign(setgap_shim_change(index_array)) .* num_size_change * shim_param.setgap_shim_bin_size;

%Calculate the required gap change after the replacement
setgap_shim_dgap_after_replace = setgap_shim_dgap - (-2 * setgap_shim_replace);
    
%Done
