edifunction [tm,numstate]=tm_2x2(data)
% data in trials x n
% data is assumed to have 2 possible states, inputs are 1 and 0 only

tm=zeros(2,2,size(data,2)); % transition matrix for each n
ntrials=size(data,1); % number of trials 
n=size(data,2); % n
numstate=zeros(2,2,n);
% 4 possible transitions for 2 states

aa=[0 0]; % state 1 stays in state 1 (awake to awake)
ab=[0 1]; % state 1 goes to state 2  (awake to asleep)
ba=[1 0]; % state 2 goes to state 1  (asleep to awake)
bb=[1 1]; % state 2 stays in state 2  (asleep to asleep)


for i=1:n;
    temp=data(:,i); % for each n
    counts=zeros(2,2); % counts for each transition
    for k=1:ntrials-1; %for each transition between trials
        trans=[temp(k) temp(k+1)];
      
        if trans==aa;
            counts(1,1)=counts(1,1)+1;
        elseif trans==ab;
            counts(1,2)=counts(1,2)+1;
        elseif trans==ba;
            counts(2,1)=counts(2,1)+1;
        elseif trans==bb;
            counts(2,2)=counts(2,2)+1;
        else
            warning(['Transition ' num2str(k) ' for Mouse ' num2str(i) ' does not match 4 possible states']);
        end
        
    end
    numstate(:,:,i)=counts;
        if sum(sum(counts))~=ntrials-1;
            error('# of Transitions inputted was not found');
        else
            temp=repmat(sum(counts,2),1,2);
            tm(:,:,i)=counts./temp;
        end        
end

