%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This function is responsible for "best fitting" the surface scan    %
% data with an ideal surface described in a separate report.          %
%                                                                     %
% Author: Mihai Cara, mcara@purdue.edu                                %
% Last Updated by Mihai Cara on 06/25/2004                            %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [v, bk] = optim(v0, MaxIter, N, M, X, Y, data, e, Weighted)

% the function optim outputs a vector which contains varibles used
% by the functions ideal_surface and kisum to calculate
% the best nonlinear fit for our data

bk = (sum(data(:,1))+sum(data(:,M))+sum(data(1,2:(M-1)))+...
      sum(data(N,2:(M-1))))/(2*N+2*(M-2));
d=data-bk;

e = abs(e);

for i=1:N
    for j=1:M
        if (e(i,j) < 1e-10)
            e(i, j) = 1e-10;
        end
    end
end

% w = (e/max(max(e))).^2;
w = e/max(max(e));

v = fminsearch(@kisum, v0, optimset('TolFun',1e-8, 'MaxIter', MaxIter,...
    'LevenbergMarquardt', 'on'),...
    N, M, X, Y, d, w, Weighted);

%the function kisum uses the least squares method to calculate the best approximation 
%(best nonlinear fit) for our data using the function ideal_surface.
%the input arguments of the function kisum are:
%%-vector v(containing the mean of the data experimentally collected,the slope, 
% the X and Y coordinates of the center of the circle and the efficient radius
%-N & M: M = number of columns = size(X) & N = number of rows = size(Y)
%-X and Y represent the X-coordinates and the Y-coordinates
%-w: is related to the errors of the measurement

function s = kisum(v, N, M, X, Y, data, w, Weighted)
if (Weighted == 1)
  s = sum(sum(((data-ideal_surface(X,Y,v))./w).^2));
else
  s = sum(sum((data-ideal_surface(X,Y,v)).^2));
end

%the function ideal_surface uses a nonlinear equation to approximate the surface 
%of the fotomultiplier and has the following input arguments:
%-vector v(containing the mean of the data experimentally collected,the slope, 
%the X and Y coordinates of the center of the circle and the efficient radius
%-X and Y represent the X-coordinates and the Y-coordinates
% 
function is = ideal_surface(x,y,v)
[x1,y1]=meshgrid((x-v(4)).^2, (y-v(5)).^2);
is = (0.5*v(1)).*(1-tanh(v(2).*(sqrt(x1+y1)-v(3))));