%**************************************************************************
%traj_anal_traj
%This function performs an alalysis of the beam trajectory.
%
%Input:
%param, parameter structure
%dat_file, output data file name
%plt_file, output plot file name
%field, field structure
%
%Output:
%traj, structure containing trajectory information
%   z                   %Translated Z, with z=0 at undulator center (m)
%   x                   %Trajectory x position (m)
%   y                   %Trajectory y position (m)
%   x_p                 %First derivative dx/dz
%   y_p                 %First derivative dy/dz
%   vx                  %Velocity in the x direction (m/s)
%   vy                  %Velocity in the y direction (m/s)
%   vz                  %Velocity in the z direction (m/s)
%
%Zachary Wolf
%7/25/11

function [traj] = traj_anal_traj(param, dat_file, plt_file, field)

%Extract required information
gamma = param.gamma;
z = field.z;
bx = field.bx;
by = field.by;
bz = field.bz;
int_bx_dz = field.int_bx_dz;
int_int_bx_dz_dz = field.int_int_bx_dz_dz;
int_by_dz = field.int_by_dz;
int_int_by_dz_dz = field.int_int_by_dz_dz;

%Calculate the velocities
%Use first order, see LCLS-TN-15-3
[vx, vy, vz] = traj_calc_vel(gamma, int_bx_dz, int_by_dz);

%Calculate the trajectories
%Use first order, see LCLS-TN-15-3
[x, x_p, x_pp] = traj_calc_x_traj(gamma, by, int_by_dz, int_int_by_dz_dz);
[y, y_p, y_pp] = traj_calc_y_traj(gamma, bx, int_bx_dz, int_int_bx_dz_dz);

%Plot the trajectories
traj_plot_x_vs_z(plt_file, z, x);
traj_plot_y_vs_z(plt_file, z, y);
%traj_plot_y_vs_x(plt_file, x, y);

%Write the trajectory exit information to the data file
traj_dat_traj_exit(dat_file, x(end), x_p(end), y(end), y_p(end));

%Plot the velocities
% traj_plot_vx_vs_z(plt_file, z, vx);
% traj_plot_vy_vs_z(plt_file, z, vy);
% traj_plot_vz_vs_z(plt_file, z, vz);

%Save the results
traj.z = z;
traj.x = x;
traj.y = y;
traj.x_p = x_p;
traj.y_p = y_p;
traj.vx = vx;
traj.vy = vy;
traj.vz = vz;

%Done
