%% This file is open source entry
function mypatterninfo = ptm_20161109( data,oz) % pattern transition matrix

%   Creates patterns list and correspondign pattern transition 
%   probabilities for a given symbolic series
  
%   Input paremeters
%   data     --- symbolic series
%   mem      --- max pattern length to consider
%   nsymbols --- alphabet size

%   Output paremeter
%   mypatterns --- list of observed patterns
%   oz         --- model parameters

%   Akbilgic 20150801

%% set parameters and initialize
ndata=length(data);
nsymbols=length(oz.list_symbol);
expectedmax=floor(ndata*oz.maxmem/10);
mypatterninfo=zeros(expectedmax,nsymbols+3);%[mypatterns length myprob myfreq]

% mypatterninfo=[];%[mypatterns length myprob myfreq]
%mypatterns=0;
%mypatternlength=0;
%myprobs=zeros(1,nsymbols);
%ndb=size(patterndb,1);
%% create patterns list and calculate pattern transition probabilites
sayacmy=0;
for j=6:7 % up to max PTP number 
    for i=1:ndata-j    
        %mysize=size(myprobs,1);
        %j,i
        mychar=hex2num(data(i:i+j-1));% patterns at hand
        %data(i+j)
        mynextchar=hex2num(data(i+j));% following symbol       
        mycol=sum((1:nsymbols).*(mynextchar==oz.col));% column number
 
        [~,myrow]=ismember(mychar,mypatterninfo(:,1))     ;   
        if myrow<1% if not exist in mydb
            sayacmy=sayacmy+1;% this is the row to add new entries
            mypatterninfo(sayacmy,1:2)=[mychar j];
%            mypatterninfo(sayacmy,2)=mychar;
%            mypatternlength=[mypatternlength;j];
%            myprobs=[myprobs; zeros(1,nsymbols)];
            mypatterninfo(sayacmy,mycol+2)=1;
        else   
            mypatterninfo(myrow,mycol+2)=mypatterninfo(myrow,mycol+2)+1;            
        end
    end
end

mypatterninfo=mypatterninfo(1:sayacmy,:);


mypatterninfo(:,end)=sum(mypatterninfo(:,3:end-1),2);% sum up frequencies

if strcmp(oz.PTPtype,'w')% sum of aall elements in PTP=1
    mypatterninfo(:,3:end-1)=mypatterninfo(:,3:end-1)/sum(mypatterninfo(:,end));
else
    mypatterninfo(:,3:end-1)=mypatterninfo(:,3:end-1)./repmat(mypatterninfo(:,end),1,nsymbols);% nonw sum of all rows = 1
end

%mypatterninfo=[mypatterns(2:end,1) mypatternlength(2:end,1) myprobs(2:end,:) myfreqs(2:end,1)];





%newpatterndb={allpatterns,allpatternlength};
% 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




