nstates = 2;
nsyms = 2;

a = abs(randn(nstates));
b = abs(randn(nstates, nsyms));
pi = abs(randn(1, nstates));

aahist = [];
abhist = [];
%achist = [];

for i = 1:nstates
	a(i,:) = a(i,:)./sum(a(i,:));
	b(i,:) = b(i,:)./sum(b(i,:));
	pi = pi./sum(pi);
end

%a = [ .7 .3; .3 .7];
%b = [ .6 .4; .4 .6];
%pi = [.5 .5];

a
b
pi
for x = 1:1000
	aahist = [aahist a(1,1)];
	abhist = [abhist a(2,2)];
%	achist = [achist a(3,3)];
	o1 = [];
	state = 2;
	if(round(rand(1)) == 0)
		state = 1;
	end
	for tick = 1:400
		if(state == 1)
			if(rand(1) > .8)
				o1 = [o1 2];
			else
				o1 = [o1 1];
			end
		else
			if(rand(1) < .9)
				o1 = [o1 2];
			else
				o1 = [o1 1];
			end
		end
		if(state == 1)
			if( rand(1) < .1)
				state = 2;
			end
		else
			if( rand(1) < .4)
				state = 1;
			end
		end	
	end

[P alpha] = hmmforward(a, pi, b, o1);
beta = hmmbackward(a,pi,b,o1);
%gp = viterbi(a,pi,b,o1);
[na npi nb] = hmmlearn(a, pi, b, o1, alpha, beta);
f = 10/(x);
if(f < .1)
	f = .1;
end
[f x]
a = (a+f*na)/(1+f);
b = (b+f*nb)/(1+f);
pi = (pi+f*npi)/(1+f);
%a = na;
%b = nb;
%pi = npi;
%o1
%gp
a
b
hold off,plot(aahist, 'red-'),hold on, plot(abhist, 'blue-')
disp('[press any key]');
pause
disp('...proceeding...');
%pi

end
%[P alpha] = hmmforward(a, pi, b, o2);
%beta = hmmbackward(a,pi,b,o2);
%[a pi b] = hmmlearn(a, pi, b, o2, alpha, beta);
[P alpha] = hmmforward(a, pi, b, o3);
beta = hmmbackward(a,pi,b,o3);
[a pi b] = hmmlearn(a, pi, b, o3, alpha, beta);
