function [calcabs calcconc resids]=altlsq(guess_calcconc,guess_calcabs,obsdata,ncomp,method)
% 15 May 2011
% module description:
%	altlsq carries out constrained (non-negative) leastsquares
%
% variables
%	input:
%	temp:
%	output:
% tokens: or, sqrt, mean, rows, abs, break, lsqnoneg
%
%
% refactoring
% T1 -guess_calcconc ??
% T2 - guess_calcabs ??
% X - obsdata
% ncomp -
% what - method
% x - calcabs
% z - calcconc


	disp('altlsq')
	calcabs=guess_calcabs;
	calcconc=guess_calcconc';

	tmp_calcabs=size(calcabs'); %another matlab hack
	tmp_calcconc=size(calcconc'); %another matlab hack

%	if (or( (method=='efa'),(method=='rtl') ) )
%		cfirst=true;
%	else
%		cfirst=false;
%	end
	convergence=1e-6;maxiter=300;
	rms=ones(1,maxiter+1).*nan;
	resids=obsdata-(calcconc'*calcabs);
	tempstor=sqrt(mean((resids.^2))); % tempstor holds the mean of all the residuals and is a one-number measure of goodness-of-fit
	rms(1)=mean(tempstor);
	cfirst=true;

	if (cfirst)
%tic
		for n=1:maxiter
		%	constrain spectra

%	tic
			for i=1:tmp_calcabs(1)
%	       			calcabs(:,i)=lsqnonneg(calcconc',obsdata(:,i),calcabs(:,i)); %octave version
					calcabs(:,i)=lsqnonneg(calcconc',obsdata(:,i)); %matlab version
			end
%	toc
%	tic
		% 	constrain concentrations
			for i=1:tmp_calcconc(1)
%				calcconc(:,i)=lsqnonneg(calcabs',obsdata(i,:)',calcconc(:,i)); %octave version
				calcconc(:,i)=lsqnonneg(calcabs',obsdata(i,:)'); %matlab version
			end
%	toc
			resids=obsdata-calcconc'*calcabs;
			tempstor=sqrt(mean(resids.^2));
			rms(n+1)=mean(tempstor);
			residual_mean_square=abs(rms(n)-rms(n+1))
			if (abs(rms(n)-rms(n+1))< convergence)
				break
			end
%disp('cfirst, iter, resid'),n,abs(rms(n))
%toc
		end
%cfirst=false => very very very slow optimisation in the first iteration. Don't know why
	else
%tic
		for n=1:maxiter
		% 	constrain concentrations
%	tic
			for i=1:tmp_calcconc(1)
%				calcconc(:,i)=lsqnonneg(calcabs',obsdata(i,:)',calcconc(:,i)); %octave version
				calcconc(:,i)=lsqnonneg(calcabs',obsdata(i,:)'); %matlab version
			end
%	toc
		%	constrain spectra
%	tic
			for i=1:tmp_calcabs(1)
	        		calcabs(:,i)=lsqnonneg(calcconc',obsdata(:,i),calcabs(:,i));
			end
%	toc

			resids=obsdata-calcconc'*calcabs;
			tempstor=sqrt(mean(resids.^2));
			rms(n+1)=mean(tempstor);
			residual_mean_square=abs(rms(n)-rms(n+1))
			if (abs(rms(n)-rms(n+1))< convergence)
				break
			end
disp('not cfirst')
%toc
		end
	end
	find(calcabs<0)
	noit=n
	finalrms=abs(rms(n+1)-rms(n))
	resids=obsdata-calcconc'*calcabs;
	calcconc=calcconc';

end
