%assumes Phi's in log space

function[] = JTChain3(cur,n,fwd_only)

global DST;

global TINY;

%number of potential functions + 1
T=DST(cur).T(n);

%number of states
S = DST(cur).S; 

%potentials
Psi = DST(cur).vPhi(:,:,2:T);

%assign first potential
for i=1:S

    Psi(:,i,1) = DST(cur).vphi(i) + Psi(:,i,1);
end

% s1_1 = normlog3(DST(cur).vphi,1e-25)

%forward messages
for t=1:T-2
    
    psi(:,t) = sumlog(Psi(:,:,t),2);
    
    for i=1:S

        Psi(:,i,t+1) = psi(i,t) + Psi(:,i,t+1);
    end
    
end

%backward messages
if(~fwd_only)
	for t=T-2:-1:1
        
        oldpsi = psi(:,t);
        psi(:,t) = sumlog(Psi(:,:,t+1),1)';
        
        for i=1:S    

            Psi(i,:,t) = psi(i,t) - oldpsi(i) + Psi(i,:,t);
        end   
	end
end

const = 1e-25;

DST(cur).xi{n}(:,:,1) = normlog3(Psi(:,:,1),const);

for t=2:T-1


    DST(cur).s{n}(:,t) = normlog3(psi(:,t-1),const);
    
    DST(cur).xi{n}(:,:,t) = normlog3(Psi(:,:,t),const);
    
%     test=DST(cur).s{n}(:,t) - sum(DST(cur).xi{n}(:,:,t))'
    
end


DST(cur).s{n}(:,1) = ((sum(DST(cur).xi{n}(:,:,1))') + const) / (1+S*const);

% s1_2 = DST(cur).s{n}(:,1)
% 
% s1_1 - s1_2

DST(cur).s{n}(:,T) = ((sum(DST(cur).xi{n}(:,:,T-1),2)) + const) / (1+S*const);

    
