function [handles] = SaveTemplate(handles)
old_template_name = get(handles.PointModelTemplate, 'name');
[path, old_template_name, ext, vers] = fileparts(old_template_name);
[filename, pathname] = uiputfile('*.temp_dat', 'Save Template As...', ['Templates', filesep]);
if isequal(filename,0) | isequal(pathname,0)
    disp('User pressed cancel')
else
    [p, n] = fileparts(pathname(1:length(pathname)-1));
    if strcmp(n, 'Templates')
        if (handles.dat.changedPointModels == 1)
            [path, templatename, ext, vers] = fileparts(filename);
            while CheckForPointModels(templatename)
                [filename, pathname] = uiputfile('*.temp_dat', 'Save Template As...', ['Templates', filesep]);
                if isequal(filename,0) | isequal(pathname,0)
                    disp('User pressed cancel')
                    return;
                else
                    [path, templatename, ext, vers] = fileparts(filename);
                end
            end
        end
        handles.PointModelTemplate = set(handles.PointModelTemplate, 'name', filename);
        handles.PointModelTemplate = set(handles.PointModelTemplate, 'direc', n);
        PMTemplate = handles.PointModelTemplate;
        save([pathname, filename], 'PMTemplate');
        handles.dat.toSave = 0;
        disp(['User selected ', fullfile(pathname, filename)]);
        handles.workingDir = pathname;
        set(handles.templateDirTxt, 'String', cut_string(get(handles.PointModelTemplate, 'direc')));
        set(handles.templateNameTxt, 'String', filename);
        if (handles.dat.changedPointModels == 1) & (handles.dat.newTemplate == 0)
            if ~exist(['PointModels', filesep, templatename])
                mkdir(['PointModels', filesep, templatename]);
            end
            if (handles.dat.changedPointModels == 1) & (handles.dat.newTemplate == 0)
                [handles] = UpdatePointModels(handles);
                % force any fixed points (e.g. border points) to their
                % correct place and create a file specifying sets that form
                % edit series (i.e. that can be turned on and off during
                % point placement)
                templatename=get(handles.PointModelTemplate,'name');
                templatename=templatename(1:findstr(templatename,'.temp_dat')-1);
                fixed_points_file=sprintf('%s_place_fixed_points',templatename);
                set(handles.figMain, 'Pointer', 'watch');
                if exist(fixed_points_file)==2
                    eval(fixed_points_file); % edit_sets
                end
                set(handles.figMain, 'Pointer', 'Arrow');
                handles.dat.changedPointModels = 0;
            end
        end
        handles.dat.newTemplate = 0;
    else
        warndlg('Please save the template in the ''Templates'' directory', 'Invalid file selection');
    end
end
disp('Saving');
return;