function aam=read_in_pointmodels(aam,is3D, scaleptsflag)
% function aam=read_in_pointmodels(aam, is3D)
%
%
% Dr. A. I. Hanna (2007)
dim = 2;
if is3D
    dim = 3;
end
template = aam.PointModelTemplate;
template_pts = get(template, 'pts');
num_template_pts = length(template_pts(:));
[a, templatename] = fileparts(get(template, 'name'));
dirname=[pwd, filesep, 'PointModels', filesep, templatename];
d=dir([dirname, filesep,'*_pm*']);
%now go through the list of files that we need, taking them from the dir
dnames={d.name};
pmt=get(aam, 'PointModelTemplate');
completed=[];
els = {};
wh = waitbar(0, 'Loading point models...');
for i=1:length(aam.am_imagenames)
    waitbar(i/length(aam.am_imagenames), wh);
    imagename=aam.am_imagenames{i};
    [pathname, fname, ext] = fileparts(imagename);
    filename = [dirname, filesep, fname, '_pm.mat'];
    if exist(filename, 'file')
        temp=load(filename);
        if isfield(temp, 'pts')
            [r,c]=size(temp.pts');
            if num_template_pts==length(temp.pts)
                pts=reshape(temp.pts,dim,round(c/dim));
                if isfield(temp, 'scale') && scaleptsflag
                    fprintf(' - this point model has scale value: %f\n', temp.scale);
                    pts = scalePts(pts, temp.scale);
                end
                els{end+1}=AAM_Element;%#ok<AGROW> % aam.elements{i};
                loops=get(pmt,'loops');
                if length(loops)>0
                    els{end}=set(els{end},'loops',loops{1});
                end
                els{end}=set(els{end},'closedloops',get(pmt,'closedloops'));
                els{end}=set(els{end},'imagefilename',imagename);
                els{end}=set(els{end},'alignedPts',[]);
                els{end}=set(els{end},'pts',pts);
                completed=[completed,i]; %#ok<AGROW>
            else
                str = sprintf('WARNING: pointmodel %s has incorrect number of points - ignoring',fname);
                fprintf('%s\n', str);
            end
        end
    else
        str = sprintf('WARNING: non-existent pointmodel %s - ignoring',fname);
        fprintf('%s\n', str);
    end
end
close(wh);
aam=set(aam,'elements',els);
aam=set(aam,'completeElements',completed);
return;
%%%
%
%%%
function pts = scalePts(pts, scale)
    mu = mean(pts,2);
    pts = pts - mu*ones(1, size(pts,2));
    pts = pts*scale;
    pts = pts + mu*ones(1, size(pts,2));
return
