function VectorWalker(varargin)
%   Dr. A. I. Hanna (2005) CMP, UEA, 2006.
error(nargchk(0,inf,nargin));

if mod(length(varargin),2) ~= 0
    % input args have not com in pairs, woe is me
    error('Arguments to VectorWalker must come param/value in pairs.')
end
ad.data.pdm = [];
ad.data.xlim = [];
ad.data.zlim = [];
ad.data.edges = [];
ad.data.ylim = [];
ad.data.direction = 1;
ad.data.units = 'var';
ad.data.selectedShapePC =[];
ad.data.sfam = [];
ad.data.shapeorappearance = 'Shape';

% Begin change by js, 071217
% Begin new code

ad.data.dim = 2;

% End new code
% End change by js, 071217

for i=1:2:length(varargin)
    switch lower(varargin{i})
        case 'pdm'
            ad.data.pdm = varargin{i+1};
        case 'shapes'
            ad.data.B = varargin{i+1};
        case 'ploth'
            ad.data.ph = varargin{i+1};
        case 'pcs'
            ad.data.selectedShapePC = varargin{i+1};
        case 'edges'
            ad.data.edges = varargin{i+1};
        case 'units'
            ad.data.units = varargin{i+1};
        case 'facets'
            ad.data.facets = varargin{i+1};
        case 'shapespaceaxishandle'
            ad.data.shapespaceaxishandle = varargin{i+1};
            % Begin change by js, 071217, 080130
            % Begin new code
        case 'dim'
            ad.data.dim = varargin{i+1};
        case 'surfacedata'
            ad.surfaceData = varargin{i+1};
        case 'sfam'
            ad.data.sfam = varargin{i+1};
        case 'shapeorappearance'
            ad.data.shapeorappearance = varargin{i+1};
            % End new code
            % End change by js, 071217, 080130
        otherwise
            error(['Unknown parameter name passed to VectorWalker.  Name was ' varargin{i}])
    end
end

% Open, move, and get the handles from the figure file.
fig = openfig(mfilename, 'reuse'); % JAB
% Move the gui and then show it, rather than have it jump all over the
% place.
movegui(fig, 'center');
set(fig, 'visible', 'on');

handles = guihandles(fig);
if ~isfield(ad.data,'facets')
    set(handles.Facets,'value',0,'enable','off');
else
    set(handles.Facets,'value',1,'enable','on');
end
set(handles.shapeslider, 'Value', 1, 'Min', 1, 'Max', size(ad.data.B,2), 'SliderStep', [.01 .1]);
set(handles.shapeslider, 'callback', {@doMoveShape});
set(handles.startbtn, 'callback', {@doStartStop});
set(handles.MakeMovie, 'callback', {@doMakeMovie});
mb = ad.data.B(:, 1);
if strcmp(ad.data.shapeorappearance,'Shape')
    shape = ad.data.pdm.Xm + ad.data.pdm.pca.P*mb;
else
    shape = ad.data.pdm.Xm;
end
if isProject3D(pwd)
    ad.data.dimensions=3;

    % Begin change by js, 080815
    % Set to default figure colour and make resizable (must have resize
    % behaviour set to "proportional" using GUIDE. Also set renderer to
    % "OpenGL"
%         figcol = [0.8314, 0.8157, 0.7843];
%         set(fig, 'Color', figcol);
        set(fig, 'Resize', 'on');
        set(fig, 'Renderer', 'OpenGL');

        % Add the custom toolbar
        set(fig, 'toolbar', 'figure');
        set(fig, 'menubar', 'figure');
        changeFigureToolbarToSimple(fig);
%         cameratoolbar(gcf);

        % Plot template isosurface TODO

        %     tPoints = ad.surfaceData.templatePoints;
        %     tSurface = ad.surfaceData.templateSurface;
        %     mPoints = pts;
        %
        %     % Now warp this surface using AIH general motion coherence code.
        %     % Align template points and surface with model points to get a better warp
        %
        %     % Define colours for visualisation of alignment and warping if desired
        %     sourceColours = ['b'; 'g'];
        %     targetColours = ['y'; 'r'];
        %     alignedColours = ['g'; 'b'];
        %     axesHandle = -1;
        %     verbose = 0;
        %
        %     [tPoints, tSurface] =  alignWithTargetPoints('targetPoints', mPoints, ...
        %         'sourcePoints', tPoints, 'sourceSurface', tSurface, 'method', 'svd', ...
        %         'verbose', verbose, 'axesHandle', axesHandle, 'targetColours', targetColours, ...
        %         'sourceColours', sourceColours, 'alignedColours', alignedColours, ...
        %         'targetLabel', 'Target Point Set', 'sourceLabel', 'Source Point Set', ...
        %         'alignedLabel', 'Aligned Point Set');
        %
        %     ad.surfaceData.currentModelSurface =  warpSurface('targetPoints', mPoints, ...
        %         'sourcePoints', tPoints, 'sourceSurface', tSurface, 'method', 'closed', ...
        %         'sigma', 1, 'lambda', 0.01, 'verbose', verbose, 'axesHandle', axesHandle, ...
        %         'targetColours', targetColours, 'sourceColours', alignedColours, ...
        %         'targetLabel', 'Target Point Set', 'sourceLabel', 'Aligned Point Set');
        %
        %     % Render warped surface
        %     ad.surfaceData.handle = patch('Faces', ad.surfaceData.currentModelSurface.faces, ...
        %         'Vertices', ad.surfaceData.currentModelSurface.vertices, ...
        %         'EdgeColor', 'none', 'FaceColor', ad.surfaceData.colour, 'FaceLighting', 'gouraud',...
        %         'Parent', ad.handles.mainAxes);
        %
        %     % Setup light
        %     lightPos = [1 0 1];
        %     ad.surfaceData.lightHandles(1) = light('Position', lightPos, 'Parent', ad.handles.mainAxes);
        %     ad.surfaceData.lightHandles(2) = light('Position', -lightPos, 'Parent', ad.handles.mainAxes);
        %
        % Setup 3D viewing of the axes
        
        % The follwing commands ensure the axis fits into the figure
        view(3);
        axis tight;
        axis equal;
        axis vis3d;
        box on;
else
    ad.data.dimensions=2;
end
if isfield(ad.data,'facets')
    pts = reshape(shape, ad.data.dimensions, length(shape)/ad.data.dimensions)';
    %ad.data.shapehandle = plotPointModel('pts', pts, 'parent', handles.mainAxes, 'edges', ad.data.edges);
    %ad = plotSurface(ad,ad.handles.mainAxes,ad.Facets.facs);

    % Begin change by js, 081212
    % Begin original code
    
    % js Make things pretty for thesis
    %     colour=[0.9,0.4,0.4];
    %     ad.data.shapehandle.pts_h  = trisurf(ad.data.facets.facs,pts(:,1),pts(:,2),pts(:,3),...
    %         'FaceColor',colour,'Parent',handles.mainAxes,'EdgeColor',colour/1.3);
    %     shading(handles.mainAxes,'faceted')
    
    %     axis(handles.mainAxes, 'image', 'xy');
    %     cameratoolbar(gcf);
    
    % End original code
    % Begin replacement code
    
    % Resizing programmatically does not work properly with this figure
%     set(fig, 'Position', [0, 0, 1000, 1000]);

    colour = [0, 1, 0];
    cdata = repmat(colour, size(ad.data.facets.facs, 1), 1);
    ad.data.shape_surf_h =trisurf(ad.data.facets.facs,pts(:,1),pts(:,2),pts(:,3),...
        'FaceVertexCData', cdata,'Parent',handles.mainAxes ,'EdgeColor', [0, 0, 0])%, ...
%         'FaceLighting', 'flat');
    
    axis ij;
    grid off;
    view(3); % az = -37.5, el = 30
%     view(217.5, 30); % Sample points the wron way, hence rotate 180 degrees
    axis tight;
    axis equal;
    axis vis3d;
    box on;
    

    % Add camera head light manually,
    % VERY FUNNY MATLAB! - The screen rendering indicates that either the
    % light source is in the wrong place or the normals are wrong, hard to
    % tell. HOWEVER when the figure is saved as a png, all is rendered as
    % expected. HAHA, VERY FUNNY. And I thought I was slowly going nuts -
    % no it is MATLAB that's nuts in this case. The axis ij command has it
    % all confused when it comes to lighting.
    lightPos  = get(handles.mainAxes, 'CameraPosition');

    % Swap xy to compensate for axis ij
%     t = lightPos(1);
%     lightPos(1) = lightPos(2);
%     lightPos(2) = t;
    light('Position', lightPos, 'Parent', handles.mainAxes);
%     camlight('headlight');

    set(ad.data.shape_surf_h, 'FaceLighting', 'flat');

    
    % Add a menu and item to the figure to set pre-defined view points
    % Ad menu items to set a default viewpoints

    handles.figuresMenu = uimenu(fig, 'Tag', 'figuresMenu', 'Label', 'Figures');

    % Ad menu items to set a default viewpoints
    handles.lateralViewpointMenuItem = uimenu(handles.figuresMenu, ...
        'Tag', 'lateralViewpointMenuItem', 'Label', 'Lateral angle Viewpoint');
    set(handles.lateralViewpointMenuItem, 'Callback', {@lateralViewpointCallback});

    handles.adaxialViewpointMenuItem = uimenu(handles.figuresMenu, ...
        'Tag', 'adaxialViewpointMenuItem', 'Label', 'Adaxial angle Viewpoint');
    set(handles.adaxialViewpointMenuItem, 'Callback', {@adaxialViewpointCallback});

    handles.view3ViewpointMenuItem = uimenu(handles.figuresMenu, ...
        'Tag', 'view3ViewpointMenuItem', 'Label', 'view(3) Viewpoint');
    set(handles.view3ViewpointMenuItem, 'Callback', {@view3ViewpointCallback});

    pts = reshape(shape, ad.data.dimensions, length(shape)/ad.data.dimensions)';
    ad.data.shapehandle = plotPointModel('pts', pts, 'parent', handles.mainAxes, 'edges', ad.data.edges);


    % End replacement code
    % End change by js, 081212

else
    pts = reshape(shape, ad.data.dimensions, length(shape)/ad.data.dimensions)';
    ad.data.shapehandle = plotPointModel('pts', pts, 'parent', handles.mainAxes, 'edges', ad.data.edges);
    %axis(handles.mainAxes, 'image', 'xy');
    axis(handles.mainAxes, 'image', 'ij');
end
%ad.data.shapehandle = plot(handles.mainAxes, shape(1:2:end),  shape(2:2:end), 'o', 'MarkerFaceColor', 'y', 'MarkerEdgeColor', 'r');

% Begin change by js, 081212
% Begin original code

% figcol = [0 0 0];
% figcol = [1 1 1];
% gridcol = [1 1 1];
% set(fig, 'Color', figcol);
% set(handles.mainAxes, 'Color', figcol, 'XColor', gridcol, 'YColor', gridcol,'ZColor', gridcol);

% End original code
% Begin replacement code

% Turn grid off and make background white
figcol = [1 1 1];
set(fig, 'Color', figcol);

% End replacement code
% End change by js, 081212

ad.handles = handles;
setappdata(0,'VectorWalkerData',ad);
try
    uiwait(fig);
catch
    if ishandle(fig)
        delete(fig)
    end
end
delete(ad.data.ph);
return;


% Begin change by js, 081212
% Begin original code
 
% No replacement in this case 
 
% End original code
% Begin replacement code

% Set default viewpoints
function lateralViewpointCallback(cbo, event)

display('VectorWalker::lateralViewpointCallback: start executing.');

view(264, 10); % Prevents vertical stacking of z axis labels
% view(86, 10);

function adaxialViewpointCallback(cbo, event)

display('VectorWalker::adaxialViewpointCallback: start executing.');

view(-6, 10);
% view(174, 10);

function view3ViewpointCallback(cbo, event)

display('VectorWalker::view3ViewpointCallback: start executing.');

view(3);
% view(217.5, 30);


% End replacement code
% End change by js, 081212

%%%
%
%%%
function doMoveShape(sliderh, evd)
ad = getappdata(0,'VectorWalkerData');

%P = ad.data.pdm.pca.P;
if strcmp(ad.data.shapeorappearance,'Shape')
    b = ad.data.pdm.pca.b;
else
    b = ad.data.sfam.b;
end
if strcmpi(ad.data.units, 'std')
    bscale = sqrt(b);
else
    bscale = ones(size(b));
end

pcs = ad.data.selectedShapePC;
Xm = ad.data.pdm.Xm;
B = ad.data.B;
mb = B(:, round(get(sliderh, 'value')));

if strcmp(ad.data.shapeorappearance,'Shape')
    shape = Xm + ad.data.pdm.pca.P*(mb.*bscale);
else
    shape = Xm;
end
shape = reshape(shape, ad.data.dimensions, length(shape)/ad.data.dimensions);

% Added J Newman 20/06/2011
if isfield(ad.data,'sfam')
    if ~isempty(ad.data.sfam)
        sz = ad.data.sfam.siz;
        Am = ad.data.sfam.Am;
        ompts = ad.data.sfam.ompts;
        if strcmp(ad.data.shapeorappearance,'Shape')
            A = Am;
        else
            A = Am + ad.data.sfam.P*(mb.*bscale);
        end
        I = reshape(A, [sz(2) sz(1) sz(3)]);
        minVal = min(min(min(shape)));
        if minVal < 0
            shape = shape + abs(minVal) + 1;
        end
        ad.currentImage = uint8(triwarp(I,ompts,shape'));
        if isempty(findobj('type','figure','name','appWarped'))
            appFig = figure('name','appWarped');
        end
        appFig = findobj('type','figure','name','appWarped');
        figure(appFig);
        imagesc(ad.currentImage);
        axis off;
        axis equal
    end
end

[segmentPoint, offsets] = isAugmentedProject;
if ~isempty(segmentPoint)
    shape = splitPoints(shape', segmentPoint, offsets)';
end
if isfield(ad.data,'facets')
    set(ad.data.shape_surf_h, 'Vertices', shape'); %...
    
    % Begin change js 20081212
    % Begin new code
    
    % Let's plot the edges and points as well
    edges = ad.data.edges{1};
    set(ad.data.shapehandle.pts_h, 'XData', shape(1,:), 'YData', shape(2,:), 'ZData', shape(3,:));

    for i=1:length(ad.data.shapehandle.edge_h)
        set(ad.data.shapehandle.edge_h(i), 'XData', [shape(1, edges(i,1)), shape(1, edges(i,2))], ...
            'YData', [shape(2, edges(i,1)), shape(2, edges(i,2))], ...
            'ZData', [shape(3, edges(i,1)), shape(3, edges(i,2))]);
    end


    % End new code
    % End change js 20081212
else
    edges = ad.data.edges{1};
    if ad.data.dimensions==2
        set(ad.data.shapehandle.pts_h, ...
            'XData', shape(1,:), ...
            'YData', shape(2,:));
        for i=1:length(ad.data.shapehandle.edge_h)
            set(ad.data.shapehandle.edge_h(i), ...
                'XData', [shape(1, edges(i,1)), shape(1, edges(i,2))],...
                'YData', [shape(2, edges(i,1)), shape(2, edges(i,2))]);
        end
    else % set(ad.data.surface_pts_handle,'Vertices',pts);
        set(ad.data.shapehandle.pts_h, 'XData', shape(1,:), 'YData', shape(2,:), 'ZData', shape(3,:));

        for i=1:length(ad.data.shapehandle.edge_h)
            set(ad.data.shapehandle.edge_h(i), 'XData', [shape(1, edges(i,1)), shape(1, edges(i,2))], ...
                'YData', [shape(2, edges(i,1)), shape(2, edges(i,2))], ...
                'ZData', [shape(3, edges(i,1)), shape(3, edges(i,2))]);
        end

        %delete(ad.data.shapehandle.pts_h);
        %delete(ad.data.shapehandle.edge_h);
        %ad.data.shapehandle = plotPointModel('pts', shape', 'parent', ad.handles.mainAxes, 'edges', ad.data.edges);

        %        switch length(pcs)
        %            case 2
        %                set(ad.data.ph, 'XData', mb(1), 'YData', mb(2));
        %            case 3
        %                set(ad.data.ph, 'XData', mb(1), 'YData', mb(2), 'ZData', mb(3));
        %        end

        %        axis(ad.handles.mainAxes, 'image', 'xy');
        %         curr_xlim = [min(shape(1,:)), max(shape(1,:))];
        %         curr_ylim = [min(shape(2,:)), max(shape(2,:))];
        %         curr_zlim = [min(shape(3,:)), max(shape(3,:))];

        %
        % Update surface plot

        %         tPoints = ad.surfaceData.templatePoints;
        %         tSurface = ad.surfaceData.templateSurface;
        %         mPoints = shape';
        %
        %         % Now warp this surface using AIH general motion coherence code.
        %         % Align template points and surface with model points to get a better warp
        %
        %         % Define colours for visualisation of alignment and warping if desired
        %         sourceColours = ['b'; 'g'];
        %         targetColours = ['y'; 'r'];
        %         alignedColours = ['g'; 'b'];
        %         axesHandle = -1;
        %         verbose = 0;
        %
        %         [tPoints, tSurface] =  alignWithTargetPoints('targetPoints', mPoints, ...
        %             'sourcePoints', tPoints, 'sourceSurface', tSurface, 'method', 'svd', ...
        %             'verbose', verbose, 'axesHandle', axesHandle, 'targetColours', targetColours, ...
        %             'sourceColours', sourceColours, 'alignedColours', alignedColours, ...
        %             'targetLabel', 'Target Point Set', 'sourceLabel', 'Aligned Point Set', ...
        %             'alignedLabel', 'Aligned Point Set');
        %
        %         ad.surfaceData.currentModelSurface =  warpSurface('targetPoints', mPoints, ...
        %             'sourcePoints', tPoints, 'sourceSurface', tSurface, 'method', 'closed', ...
        %             'sigma', 1, 'lambda', 0.01, 'verbose', verbose, 'axesHandle', axesHandle, ...
        %             'targetColours', targetColours, 'sourceColours', alignedColours, ...
        %             'targetLabel', 'Target Point Set', 'sourceLabel', 'Aligned Point Set');
        %
        %         % Update surface plot
        %         set(ad.surfaceData.handle, 'Faces', ad.surfaceData.currentModelSurface.faces, ...
        %             'Vertices', ad.surfaceData.currentModelSurface.vertices);
        %
        %         % Update axis limits based on shape
        %         curr_xlim = [min(shape(1,:)), max(shape(1,:))];
        %         curr_ylim = [min(shape(2,:)), max(shape(2,:))];
        %         curr_zlim = [min(shape(3,:)), max(shape(3,:))];

        %         curr_xlim = get(ad.handles.mainAxes, 'XLim');
        %         curr_ylim = get(ad.handles.mainAxes, 'YLim');
        %         curr_zlim = get(ad.handles.mainAxes, 'Zlim');
        %
        %         if isempty(ad.data.xlim)
        %             ad.data.xlim = curr_xlim;
        %             ad.data.ylim = curr_ylim;
        %             ad.data.zlim = curr_zlim;
        %         else
        %             if curr_xlim(1)<ad.data.xlim(1); ad.data.xlim(1) = curr_xlim(1); end;
        %             if curr_xlim(2)>ad.data.xlim(2); ad.data.xlim(2) = curr_xlim(2); end;
        %             if curr_ylim(1)<ad.data.ylim(1); ad.data.ylim(1) = curr_ylim(1); end;
        %             if curr_ylim(2)>ad.data.ylim(2); ad.data.ylim(2) = curr_ylim(2); end;
        %             if curr_zlim(1)<ad.data.zlim(1); ad.data.zlim(1) = curr_zlim(1); end;
        %             if curr_zlim(2)>ad.data.zlim(2); ad.data.zlim(2) = curr_zlim(2); end;
        %         end
        %
        %          set(ad.handles.mainAxes, 'XLim', ad.data.xlim, 'YLim', ad.data.ylim, 'ZLim', ad.data.zlim);
        %
        % Updata axis limits based on surface
        %          ad = updateAxisLimitsFromSurface(ad,
        %          ad.surfaceData.currentModelSurface);
    end
    %axis(ad.handles.mainAxes, 'image', 'xy');
end
switch length(pcs)
    case 2
        % Add line here to make trajectory move correctly.
        set(ad.data.ph, 'XData', mb(1), 'YData', mb(2));
    case 3
        set(ad.data.ph, 'XData', mb(1), 'YData', mb(2), 'ZData', mb(3));
end
% axis(ad.handles.mainAxes, 'image', 'xy');
curr_xlim = [min(shape(1,:)), max(shape(1,:))];
curr_ylim = [min(shape(2,:)), max(shape(2,:))];
if ad.data.dimensions == 3
    curr_zlim = [min(shape(3,:)), max(shape(3,:))];
end

if isempty(ad.data.xlim)
    ad.data.xlim = curr_xlim;
    ad.data.ylim = curr_ylim;

    if ad.data.dimensions==3
        ad.data.zlim = curr_zlim;
    end
else
    if curr_xlim(1)<ad.data.xlim(1); ad.data.xlim(1) = curr_xlim(1); end;
    if curr_xlim(2)>ad.data.xlim(2); ad.data.xlim(2) = curr_xlim(2); end;
    if curr_ylim(1)<ad.data.ylim(1); ad.data.ylim(1) = curr_ylim(1); end;
    if curr_ylim(2)>ad.data.ylim(2); ad.data.ylim(2) = curr_ylim(2); end;

    if ad.data.dimensions==3
        if curr_zlim(1)<ad.data.zlim(1); ad.data.zlim(1) = curr_zlim(1); end;
        if curr_zlim(2)>ad.data.zlim(2); ad.data.zlim(2) = curr_zlim(2); end;
    end
end

set(ad.handles.mainAxes, 'XLim', ad.data.xlim, 'YLim', ad.data.ylim);

if ad.data.dimensions==3
    set(ad.handles.mainAxes, 'ZLim', ad.data.zlim);
end

setappdata(0,'VectorWalkerData', ad);
%%%
%
%%%
function doStartStop(startbtn, evd)
ad = getappdata(0,'VectorWalkerData');
speed = get(ad.handles.speedpopup, 'string');
speed = str2num(speed{get(ad.handles.speedpopup, 'value')});
if get(startbtn, 'value')==1
    set(startbtn, 'String', 'Stop');
else
    set(startbtn, 'String', 'Start');
end
while get(startbtn, 'value')==1
    ad = getappdata(0,'VectorWalkerData');
    sliderh = ad.handles.shapeslider;
    currval = get(sliderh, 'value');
    slidermax = get(sliderh, 'Max');
    slidermin = get(sliderh, 'Min');
    if (currval+ad.data.direction)>slidermax
        ad.data.direction = ad.data.direction*-1;
    end
    if (currval+ad.data.direction)<slidermin
        ad.data.direction = ad.data.direction*-1;
    end
    set(sliderh, 'value', currval+ad.data.direction);
    setappdata(0,'VectorWalkerData', ad);
    pause(speed);
    doMoveShape(ad.handles.shapeslider);
end
%%%
%
%%%
function doMakeMovie(moviebtn, evd)
ad = getappdata(0,'VectorWalkerData');
if isempty(which('avifile'))
    path(path,genpath('C:\Program Files\MATLAB\R2010a\toolbox\matlab\audiovideo'));
end
speed = get(ad.handles.speedpopup, 'string');
speed = str2num(speed{get(ad.handles.speedpopup, 'value')});
datetime=strrep(datestr(now),' ','-');
datetime=strrep(datetime,':','-');
name=sprintf('ShapeVectorWalkShowShape-%s',datetime);
shapemoviename = fullfile(pwd,'movies',[name,'.avi']);
shapemoviefilehandle=avifile(shapemoviename,'fps',10);
fprintf(1,'starting to produce %s\n',shapemoviename);
if isfield(ad.data,'sfam')
    if ~isempty(ad.data.sfam)
        appearance_name=sprintf('ShapeVectorWalkShowApp-%s',datetime);
        appmoviename = fullfile(pwd,[appearance_name,'.avi']);
        appmoviefilehandle=avifile(appmoviename,'fps',10);
        fprintf(1,'starting to produce %s\n',appmoviename);
    end
end
set(ad.handles.startbtn, 'String', 'Stop','Enable','off');
sliderh=ad.handles.shapeslider;
slidermax = get(sliderh, 'Max');
slidermin = get(sliderh, 'Min');
ds=(slidermax - slidermin)/200; %20; % temporary
shapeparent=get(ad.handles.mainAxes,'parent');
if isfield(ad.data,'sfam')
    if ~isempty(ad.data.sfam)
        if isempty(findobj('type','figure','name','appWarped'))
            apparent = figure('name','appWarped');
        else
            apparent = findobj('type','figure','name','appWarped');
        end
    else
        apparent = 0;
    end
else
    apparent = 0;
end
for i=slidermin:ds:slidermax
     ad = getappdata(0,'VectorWalkerData');
     sliderh = ad.handles.shapeslider;
     disp(sprintf('%f',i))
     set(sliderh, 'value', i);
     setappdata(0,'VectorWalkerData', ad);
     pause(speed);
     doMoveShape(ad.handles.shapeslider);
     shapeimg = getframe(shapeparent);
     shapemoviefilehandle=addframe(shapemoviefilehandle,shapeimg.cdata);
     if apparent > 0
         appimg = getframe(apparent);
         appmoviefilehandle=addframe(appmoviefilehandle,appimg.cdata);
     end
     fprintf(1,'%d\n',slidermax-i*ds)
end
% for i=slidermax:-ds:slidermin
%      ad = getappdata(0,'VectorWalkerData');
%      sliderh = ad.handles.shapeslider;
%      set(sliderh, 'value', i);
%      setappdata(0,'VectorWalkerData', ad);
%      pause(speed);
%      doMoveShape(ad.handles.shapeslider);
%      shapeimg = getframe(shapeparent);
%      shapemoviefilehandle=addframe(shapemoviefilehandle,shapeimg.cdata);
%      if apparent > 0
%          appimg = getframe(apparent);
%          appmoviefilehandle=addframe(appmoviefilehandle,appimg.cdata);
%      end
% end
shapemoviefilehandle=close(shapemoviefilehandle)
MakeVideosAndFLV( 400, 2, fullfile(pwd,'movies'),[name,'.avi'],[name,'.flv'] );
disp(sprintf('Finished writing %s\n',shapemoviename));
if isfield(ad.data,'sfam')
    if ~isempty(ad.data.sfam)
        appmoviefilehandle=close(appmoviefilehandle)
        MakeVideosAndFLV( 400, 2, fullfile(pwd,'movies'),[appearance_name,'.avi'],[appearance_name,'.flv'] );
        disp(sprintf('Finished writing %s\n',appmoviename));
    end
end
set(ad.handles.startbtn, 'String', 'Start','Enable','on');
set(moviebtn,'Value',0);

%ad.moviefilehandle=avifile(ad.moviename);
% speed = get(ad.handles.speedpopup, 'string');
% speed = str2num(speed{get(ad.handles.speedpopup, 'value')});
% set(ad.handles.startbtn, 'String', 'Stop','Enable','off');
% sliderh=ad.handles.shapeslider;
% slidermax = get(sliderh, 'Max');
% slidermin = get(sliderh, 'Min');
% ds=(slidermax - slidermin)/20;
% MP=get(0,'ScreenSize');
% set(ad.handles.figure1,'color','w');
% set(ad.handles.mainAxes,'color','w');
% % set(ad.handles.figure1,'position',[0    5  100   30]);
% % set(get(ad.data.shapespaceaxishandle,'parent'),'position',[30    5  100   30]);
% parent=get(ad.handles.mainAxes,'parent');
% %parent2 = get(ad.handles.figure1,'axes');
% %parent2 = get(ad.data.shapespaceaxishandle, 'Parent');
% set(parent2, 'Color', 'w');
% figure(parent); % Make figure current and raise it above others
% F1 = getframe(parent);
% % F2 = getframe(ad.data.shapespaceaxishandle);
% figure(parent); % Make figure current and raise it above others
% F2 = getframe(parent2);
% s1=size(F1.cdata);
% s2=size(F2.cdata);
% leftwidth=2;
% composite=uint8(zeros(s1(1),leftwidth*s1(2),3));
% composite(1:s1(1), 1:(leftwidth-1)*s1(2), 1:3)=imresize(F2.cdata,[s1(1),(leftwidth-1)*s1(2)]);
% composite(1:s1(1), (leftwidth-1)*s1(2)+1:leftwidth*s1(2),1:3)=imresize(F1.cdata,[s1(1),s1(2)]);
% fig=figure(6)
% iptsetpref('ImshowBorder','tight');
% imshow(composite);
% k=1;
% figure(fig); % Make figure current and raise it above others
% movegui(fig, 'northeast'); %Tidy it away to make room for the shape plot
% F3(k) =getframe(fig);
% for i=slidermin:ds:slidermax %while get(startbtn, 'value')==1
%     ad = getappdata(0,'VectorWalkerData');
%     sliderh = ad.handles.shapeslider;
%     set(sliderh, 'value', i);
%     setappdata(0,'VectorWalkerData', ad);
%     pause(speed);
%     doMoveShape(ad.handles.shapeslider);
%     figure(parent);
%     F1 = getframe(parent);%ad.handles.mainAxes);
%     %     F2 = getframe(ad.data.shapespaceaxishandle);
%     figure(parent2);
%     F2 = getframe(parent2);
%     composite(1:s1(1), 1:(leftwidth-1)*s1(2), 1:3)=imresize(F2.cdata,[s1(1),(leftwidth-1)*s1(2)]);
%     composite(1:s1(1), (leftwidth-1)*s1(2)+1:leftwidth*s1(2),1:3)=imresize(F1.cdata,[s1(1),s1(2)]);
%     figure(fig);
%     imshow(composite);
%     k=k+1;
%     figure(fig);
%     F3(k) =getframe(fig);
% end
% for i=slidermax:-ds:slidermin %while get(startbtn, 'value')==1
%     ad = getappdata(0,'VectorWalkerData');
%     sliderh = ad.handles.shapeslider;
%     set(sliderh, 'value', i);
%     setappdata(0,'VectorWalkerData', ad);
%     pause(speed);
%     doMoveShape(ad.handles.shapeslider);
%     figure(parent);
%     F1 = getframe(parent);%(ad.handles.mainAxes);
%     %     F2 = getframe(ad.data.shapespaceaxishandle);
%     figure(parent2);
%     F2 = getframe(parent2);
%     composite(1:s1(1), 1:(leftwidth-1)*s1(2), 1:3)=imresize(F2.cdata,[s1(1),(leftwidth-1)*s1(2)]);
%     composite(1:s1(1), (leftwidth-1)*s1(2)+1:leftwidth*s1(2),1:3)=imresize(F1.cdata,[s1(1),s1(2)]);
%     figure(fig);
%     imshow(composite);
%     k=k+1;
%     figure(fig);
%     F3(k) =getframe(fig);
% end
% moviename=['VectorWalk-',datestr(now),'.avi'];
% ind=findstr(moviename,' ');
% moviename(ind)='T';
% ind=findstr(moviename,':');
% moviename(ind)='-';
% moviename=fullfile(pwd,moviename);
% disp(sprintf('\nPlease wait as writing %s will take some time',moviename));
% movie2avi(F3,moviename,'fps',5,'Quality',90,'compression','Cinepak');
% disp(sprintf('Finished writing %s\n',moviename));
% set(ad.handles.startbtn, 'String', 'Start','Enable','on');
% set(moviebtn,'Value',0);
% close(fig);

