function trajectories3d_animations_v3(Lon,Lat,Depth,Times,lonlim,latlim,depthlim,SaveDir,pfunc,varargin)

% function trajectories_animationtrajectories_animation(Lon,Lat,Times,lonlim,latlim,frameDir,pfunc,varargin)

%------------------------------------------------------------------------------------
%trajectories_animation will animate trajectories
%
%function trajectories_animation(Lon,Lat,Times,SaveDir,varargin)
%	for future revisions this function should support a host of varibale inputs that
%	control the finer points of the plotting and animation (color, time-delay, etc.
%	as well as making the "SaveDir" variable a varargin argument)
%
% $Id: trajectories_animation.m  2014-11-24 17:54:29Z efredj $
%
%------------------------------------------------------------------------------------


if ~exist( 'pfunc', 'var' )
    pfunc = 'm_plot';
end

switch pfunc
    case 'm_plot'
        plotFunct = 'm_plot';
        scatterFunct = 'm_scatter';
    case 'plot'
        plotFunct = 'plot';
        scatterFunct = 'scatter';
    otherwise
        error( 'Only valid inputs are ''m_plot'' or ''plot''' );
end

% default options
if ~exist('add2Title','var')
    add2Title = '';
end

if ~exist('initSize','var')
    initSize = 6;
end

if ~exist('headSize','var')
    headSize = 6;
end
if ~exist('trajColor','var')
    trajColor = 'k';
end
if ~exist('initColor','var')
    initColor = 'b';
end
if ~exist('headColor','var')
    headColor = [0.7,0.7,0.7];
end
if ~exist('tailLen','var')
    tailLen = 6;
end
if ~exist('saveToFile','var')
    saveToFile = 'screen';
end
if ~exist('headMarker','var')
    headMarker = '+';
end
if ~exist('initMarker','var')
    initMarker = 'o';
end
if ~exist('tailLineStyle','var')
    tailLineStyle = '-';
end
if ~exist('initLineStyle','var')
    initLineStyle = 'none';
end

% look at any remaining options
k=1;
while k<length(varargin),
    optn=lower(varargin{k});
    switch optn,
        case 'add2title',
            add2Title = varargin{k+1};
        case 'initsize'
            initSize = varargin{k+1};
        case 'headsize'
            headSize = varargin{k+1};
        case 'trajcolor'
            trajColor = varargin{k+1};
        case 'initcolor'
            initColor = varargin{k+1};
        case 'headcolor'
            headColor = varargin{k+1};
        case 'taillen'
            tailLen = varargin{k+1};
        case 'savetofile'
            saveToFile = varargin{k+1};
        case 'headmarker'
            headMarker = varargin{k+1};
        case 'initmarker'
            initMarker = varargin{k+1};
        case 'taillinestyle'
            tailLineStyle = varargin{k+1};
        case 'initlinestyle'
            initLineStyle = varargin{k+1};
    end;
    k=k+2;
end

% Try to make the frame size smaller
orient portrait
hold on;

% Initialize plot handles to avoid annoying error messages
h1 = [];  % Handle to active tail
h2 = [];  % Handle to Head
h3 = [];  % Handle to past tail (from start to end of active tail)
h4 = [];  % Handle to Initial
h5 = [];  % Handle to Path (from start to now)
h6 = [];  % Handle to Depth colorbar

numFrames = size(Times(:),1);
numTracers = size(Lon,2);

for i = 1:numFrames
    fprintf('%s: Processing frame%02d\n',mfilename,i);
    % Get rid of the time(i-1) worms.
    delete(h1);
    delete(h2);
    delete(h3);
    delete(h4);
    delete(h5);
    delete(h6);
    
    % Length of data traversed so far is less then tail
    if i == 1
        % Do nothing, just make the head, no tail
    elseif i > 1  &&  i <= tailLen
        % Make tail from start of data to now.
        h1 = feval( plotFunct,Lon(1:i,:),Lat(1:i,:), ...
            'lineStyle',tailLineStyle,'linewidth',2,'color',trajColor);
    else
        % Make the past tail.  Add 1 to prevent the situation where X(1:1,:) &
        % Y(1:1,:), and all starting positions are connected.  Just draw
        % first, and the last
        h3 = feval( plotFunct,Lon(1:i-tailLen+1,:),Lat(1:i-tailLen+1,:), ...
            'lineStyle',tailLineStyle,'linewidth',2,'color',headColor);
        % Make the tail from now to tailLen dt's ago.
        h1 = feval( plotFunct,Lon(i-tailLen:i,:),Lat(i-tailLen:i,:), ...
            'lineStyle',tailLineStyle,'linewidth',2,'color',trajColor);
    end
    
    % Add the Initial Location
    h4 = feval( plotFunct,Lon(1,:),Lat(1,:),'lineStyle',initLineStyle,'Color',initColor, ...
        'marker',initMarker,'markerSize',initSize);
    
    % Make the head
    h2 = feval( plotFunct,Lon(i,:),Lat(i,:),'lineStyle',initLineStyle,'Color',headColor, ...
        'marker',headMarker,'markerSize',headSize);
    
%     for ntracer=1:numTracers;
        h5 = feval( scatterFunct,Lon(i,:),Lat(i,:),50,Depth(i,:) );
        h6 = colorbar('v');
        set(get(h6,'title'),'string','Depth (m)')
        hold on
%     end
    % Title in all its splendor.
    title( {sprintf('%s Particle Trajectories From',add2Title), ...
        sprintf('Currents at %s GMT', ...
        datestr(Times(i),'dd-mmm-yyyy HH:MM')) }, ...
        'FontSize',14,'FontWeight','bold');
    
    if ~strcmpi(saveToFile,'screen')
        print('-djpeg',fullfile(SaveDir,sprintf('frame%02d',i)));
    end
    
    drawnow;
end

if ~strcmpi(saveToFile,'screen')
    % Add code repeat the ending frame a set number of times.
    % Determine last actual frame number and add to it.
    cnt = i;
    numRepeatLastFrame = 8;
    for j = 1:numRepeatLastFrame
        cnt = cnt + 1;
        print('-djpeg',fullfile(SaveDir,sprintf('frame%02d',cnt)));
    end
end
hold off;

return;
end

function CLim = newclim(BeginSlot,EndSlot,CDmin,CDmax,CmLength)
%                Convert slot number and range
%                to percent of colormap
PBeginSlot    = (BeginSlot - 1) / (CmLength - 1);
PEndSlot      = (EndSlot - 1) / (CmLength - 1);
PCmRange      = PEndSlot - PBeginSlot;
%                Determine range and min and max 
%                of new CLim values
DataRange     = CDmax - CDmin;
ClimRange     = DataRange / PCmRange;
NewCmin       = CDmin - (PBeginSlot * ClimRange);
NewCmax       = CDmax + (1 - PEndSlot) * ClimRange;
CLim          = [NewCmin,NewCmax];
return;
end

function CData = newcolor(CData, CLim)
%                Determine the color for a specific CData
t = (CData-CLim(1))/diff(CLim);
CData = (1-t)*CLim(1)+t*CLim(2);
return;
end

function fixcolorbar(colpos,colaxis,vname,fsize)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% function fixcolorbar(colpos,colaxis,vname,fsize)
%
% put a colorbar at a fixed position
%
% input:
%
%  colpos   position of the colorbar [left, bottom, width, height]
%  colaxis  = [cmin cmax]: values assigned to the first and 
%           last colors in the current colormap 
%           (default: fit the min and max values of the variable)  
%  vname    name of the variable (string)
%           (default: 'temp')
%  fsize    font size  
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
dc=(colaxis(2)-colaxis(1))/64;
% subplot('position',colpos)
x=[0:1];
y=[colaxis(1):dc:colaxis(2)];
[X,Y]=meshgrid(x,y);
pcolor(Y,X,Y)
shading flat
set(gca,'YTick',y,'YTickLabel',[' '])
return;
end