%**************************************************************************
%This function calculates the K value from the undulator field.
%
%Input:
%z, z-positions of the field (m)
%by, By(z) on the midplane (T)
%
%Output:
%k, K value
%
%Zachary Wolf, 11/11/09

function [k] = field_calc_calc_k(z, by)

%Constants
q = -1.60217733e-19;    %Electron charge (C)
m = 9.1093897e-31;      %Electron mass (kg)
c = 2.99792458e8;       %Speed of light (m/s)
gamma = 1;  %Drops out of K calculation

%Calculate K
x_prime = (- q / (gamma * m * c)) * cumtrapz(z, by);
x_prime = x_prime - mean(x_prime);
slip = trapz(z, (1 / (2 * gamma^2)) + (1 / 2) * x_prime.^2);
dsdz = slip / (z(end) - z(1));
k = sqrt(2 * (2 * gamma^2 * dsdz - 1));

%Done
