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';

#	if (or( (method=="efa"),(method=="rtl") ) )
#		cfirst=true;
#	else
#		cfirst=false;
#	endif
	convergence=1e-6;maxiter=100;
	rms=ones(1,maxiter+1).*NA;
	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:rows(calcabs')
	       			calcabs(:,i)=lsqnonneg(calcconc',obsdata(:,i),calcabs(:,i));
			endfor
	toc
	tic
		# 	constrain concentrations
			for i=1:rows(calcconc')
				calcconc(:,i)=lsqnonneg(calcabs',obsdata(i,:)',calcconc(:,i));
			endfor
	toc
			resids=obsdata-calcconc'*calcabs;
			tempstor=sqrt(mean(resids.^2));
			rms(n+1)=mean(tempstor);
			if (abs(rms(n)-rms(n+1))< convergence)
				break
			endif
disp('cfirst, iter, resid'),n,abs(rms(n))
#toc
		endfor
#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:rows(calcconc')
				calcconc(:,i)=lsqnonneg(calcabs',obsdata(i,:)',calcconc(:,i));
			endfor
	toc
		#	constrain spectra
	tic
			for i=1:rows(calcabs')
	        		calcabs(:,i)=lsqnonneg(calcconc',obsdata(:,i),calcabs(:,i));
			endfor
	toc

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

endfunction
