%**************************************************************************
%This function fits the trajectory in the undulator with a line.  The slope
%and intercept are returned.  The fitted line is extended through the entire
%trajectory and the residuals are calculated and returned.
%
%Input:
%z_start, z position of the start of the fit (m)
%z_end, z position of the end of the fit (m)
%z, z position array for the trajectory (m)
%x, x or y position of the trajectory at each z (m)
%
%Output:
%slope, slope of the linear fit (dimensionless)
%intercept, intercept of the linear fit (m)
%resid, residuals to the extended fit for all z (m)
%
%Zachary Wolf, 1/8/06

function [slope, intercept, resid] = traj_fit_traj(z_start, z_end, z, x)

%Fit a line to the trajectory in the undulator
index_array = find((z >= z_start) & (z <= z_end));
z_fit = z(index_array);
x_fit = x(index_array);
p = polyfit(z_fit, x_fit, 1);
slope = p(1);
intercept = p(2);

%Find the residuals to the linear fit
resid = x - (slope * z + intercept);

%Done