function fieldnameIndex = compileFieldnameIndex(matFiles)
% Traverse the extracts of all matfiles, compiling a list of all fields and
% indexing from fieldnames to the matfile num.
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
% 
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
% 
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
% 
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
% 
% CERR is distributed under the terms of the Lesser GNU Public License. 
% 
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
% 
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.


disp('planDB>> Compiling fieldname Index...');
fieldnameIndex = struct('fieldname', {},'planIndices',{});
for i=1:length(matFiles)
    if matFiles(i).isPlanC
        newfieldnames = listAllFieldNames(matFiles(i).extract);
        oldfieldnames = [fieldnameIndex.fieldname]';
        [C, INew, IOld] = intersect(newfieldnames, oldfieldnames);
        
        for j=1:length(IOld)
            fieldnameIndex(IOld(j)).planIndices(end+1) = i;
        end

        if isempty(oldfieldnames)
            oldfieldnames={};
        end
        
        [C, INew] = setdiff(newfieldnames, oldfieldnames);

        for j=1:length(INew)
            fieldnameIndex(end+1).fieldname = newfieldnames(INew(j));
            fieldnameIndex(end).planIndices = i;
        end        
        
    end
end

for i=1:length(fieldnameIndex)
    fieldnameIndex(i).fieldname = fieldnameIndex(i).fieldname{:};
end

disp('planDB>> Fieldname Index Complete.');