function S = laserCrunch(filename, N, L, dx, a, d, x_offset,amp)
% L = 8.19m;
% a = 40 um
% d = 125 um
% N = 5;  % number of slits.
if nargin < 8
    amp = 1;
end
if nargin < 7
    x_offset = 0;
end
if nargin < 6
	d = 125;
end
if nargin < 5
    a = 40;
end
a  =  a*1e-6; % convert from um to m.
d  =  d*1e-6; % convert from um to m.
dx = dx*1e-2; % convert from cm to m.

lambda = 532e-9;  % in m.

S = csvread(filename,1,0);
t = S(:,1); % time of sample.
theta = S(:,3); % angular position of rotary motion sensor.
P = S(:,2);  % power of light detected.
Nt = size(P,1);
% find the region at the beginning and end where the position is constant
% and then use the know change in position and measure change in angle to
% calibrate the angular position to give linear position.
    N_mean = sum(t<2);
    n_begin   =           1:N_mean;
    n_end     = (Nt-N_mean):Nt;
    theta_0   = mean(theta(n_begin));
    theta_end = mean(theta(n_end  ));
    [P_max,ind] = max(P);           % find the sample that has the highest power.
    theta_center = theta(ind);      % find the angular position of this highest power
    rate = dx/(theta_end-theta_0);  % the rate at which the position changes with angle
    x = rate*(theta-theta_center)-x_offset;  % the linear position.
    figure(1)
    plot(t,theta,t(n_begin),theta(n_begin),'r',t(n_end),theta(n_end),'r');

% Now compute the theoretical result.
st  = sin(atan((x/L))) ;
xi  = (d/lambda)*st;
xi2 = (a/lambda)*st    ;
P_envelope = sinc(xi2).^2;
P_theory   = amp*(sin(N*pi*xi)./(N*sin(pi*xi))).^2 ;

% remove the power due to background light level, and normalize the power.

ind = find(abs(xi)<4);
P_min = min(P(ind));
P = (P-P_min)/(P_max-P_min);  

% make graphs
figure(2)
plot(xi,P_theory.*P_envelope,xi,P,'.')
texText('$d\sin\theta/\lambda$','x')
end