%% This is an open source software

function matchedpatterninfo = match_ptm_20161109_toexternalDB( mypatterninfo, patterndb)
%   Here we will compare each individual series patterns to overall pattern
%   database and will add the missing patterns
  
%   Input paremeters
%   mypatterninfo --- patterninfo from all series (multi_ptm_20161107)
%   patterndb     --- allobserved patterns database
%   Output paremeter
%   matchedpatterninfo --- every series will haev same patterns ever
%   observed

%   Akbilgic 20161107

% first, find the patterns not existing in DB and exclude them

%nmissing=length(patternextra);

matchedpatterninfo = cell(size(mypatterninfo,1),1);


%mypool=parpool(feature('numCores'));
for i=1:size(mypatterninfo,1)
    [~,externalpatterns]=setdiff(mypatterninfo{i,1}(:,1),patterndb(:,1)); % keep hte patterns exist in ref DB
    patternsINdb=setdiff(1:size(mypatterninfo{i,1},1),externalpatterns);
    
    matchedpatterninfo{i,1}=mypatterninfo{i,1}(patternsINdb,:);

	[~,missingind]=setdiff(patterndb(:,1),matchedpatterninfo{i,1}(:,1)); % find missing patterns
	nmissing=length(missingind);
	matchedpatterninfo{i,1}=[matchedpatterninfo{i,1};[patterndb(missingind,:) zeros(nmissing,size(matchedpatterninfo{1,1},2)-2)]];
    
	matchedpatterninfo{i,1}= sortrows(matchedpatterninfo{i,1},[2,1]); 

end

%matchedpatterninfo=matchedpatterninfo;

%mypool=parpool(feature('numCores'));
%parfor i=1:size(mypatterninfo,1) % for each series
%   [~,missingind]=setdiff(patterndb(:,1),patterninfo{i,1}(:,1)); % find missing patterns
%   nmissing=length(missingind);
%   matchedpatterninfo{i,1}=[matchedpatterninfo{i,1};[patterndb(missingind,:) zeros(nmissing,size(patterninfo{1,1},2)-2)]];
    
%   matchedpatterninfo{i,1}= sortrows(matchedpatterninfo{i,1},[2,1]); 
%end
%delete(mypool)       

end

%%



%
% Copyright J. Andrew Howe & Oguz Akbilgic 2015
% this code may be freely used, modified, and distributed (at no charge)
% as long as this footer remains unaltered
% updated by akbilgic 20170223

%% Akbilgic 20161108