%
% function [] = AAMElementConverter(class_template_file, structure_template_file)
%
% A tool to convert the class template file to structures used by toolbox2
%
% Dr. A. I. Hanna (14-07-2005)
function [] = AAMElementConverter(AAM_file, directoryname)
if nargin ~= 2
    [filename, pathname] = uigetfile('*.model_dat', 'Pick Class Template File', pwd);
    if isequal(filename,0) | isequal(pathname,0)
        disp('User pressed cancel')
        return;
    else
        disp(['User selected ', fullfile(pathname, filename)]);
    end
    AAM_file = fullfile(pathname, filename);
    directoryname = uigetdir(pathname, 'Select Directory to Store PM');
    if isequal(directoryname,0)
        disp('User pressed cancel')
        return;
    else
        disp(['User selected ', directoryname])
    end
end


if isempty(AAM_file) | isempty(directoryname)
    error('One or both of the filenames are empty. You must provide two valid filenames.');
    return;
end


AAM = load(AAM_file, '-mat');

AAM = AAM.AAM;
PMTemplate = get(AAM, 'PointModelTemplate')
if strcmp(class(PMTemplate), 'struct')
    template_pts = PMTemplate.pts;
else
    template_pts = get(PMTemplate, 'pts');
end

elements = get(AAM, 'elements');
for e =1:length(elements)
    AAM_Element = elements{e};
    pts = get(AAM_Element, 'pts');
    % We only want to take the elements that have the correct number of
    % landmarks. Those with too few will not be included in the PM_
    % directory
    if (size(template_pts,2) == size(pts, 2))
        pts = pts(:);
        filename = get(AAM_Element, 'imagefilename');
        filename = filename(1:length(filename)-4);
        %save([directoryname, filesep, filename, '_pm.mat'], 'pts')
    end
end
return;
% Check to see if the loaded file is consistant with the current definition
% of PointModelTemplate Class. If not then it will be a structure.
if strcmp(class(PMTemplate), 'struct')
    model.pts = PMTemplate.pts';
    model.pri = PMTemplate.primaries;
else
    model.pts = get(PMTemplate, 'pts')';
    model.pri = get(PMTemplate, 'primaries');
end
model.norm = [];
model.loop = 0;
model.subject = '';
save(structure_template_file, 'model');