function err = fitBS(start, nm, R, muaoxy, muadeoxy, muawater, muabili);
% updated April 18, 2008 by SLJ
global cnt

cnt = cnt + 1;
GRAPH = 1; % 1 = ON, 0 = OFF

B     = start(1);
S     = start(2);
a     = start(3);
P     = start(4);
Pwidth = start(5);
Pnm   = start(6);
GG    = start(7);

W = 0.65; % water content
%b = 1.0;  % scattering coefficient, musp = a*nm.^-b

%%%%
% bili
%%%
muaP = exp(-(abs(nm - Pnm)/Pwidth).^2);

Mie = 4.59e3*nm.^-0.913;
Ray = 1.74e12*nm.^-4;
musp = a*(Mie + Ray);

r = 0.2;
n = 1.37;
mua = B*(S*muaoxy + (1-S)*muadeoxy) + W*muawater + P*muaP;
pR = GG*getRr(mua, musp, r, n);
%
mua = B*(S*muaoxy + (1-S)*muadeoxy) + W*muawater;
pRB = GG*getRr(mua, musp, r, n);
%
mua = W*muawater;
pRW = GG*getRr(mua, musp, r, n);

err = sum( (pR - R).^2 );

if S>1; err = err*10; end
if S<0.0; err = err*10; end
if Pnm<0; err = err*10; end

if cnt<500
	FLAG = (mod(cnt,10)==0);
else
	FLAG = (mod(cnt,100)==0);
end

if ( GRAPH & FLAG )
figure(2)
set(figure(2),'position',[645    40   577   757],'color','w')
sz = 18;
subplot(2,1,1); hold off
ymax = 1;
plot(nm, R, 'm-')
hold on
plot(nm, pRW, 'k--','linewidth',2)
plot(nm, pR, 'b-','linewidth',2)
plot(nm, pRB, 'r-','linewidth',2)

set(gca,'fontsize',sz)
xlabel('wavelength [nm]')
ylabel('M = R/Rstd')
axis([400 900 0 1])
text(450, ymax*0.9, sprintf('B = %0.4f', B),'fontsize',sz)
text(450, ymax*0.8, sprintf('S = %0.3f', S),'fontsize',sz)
text(450, ymax*0.7, sprintf('a = %0.3f', a),'fontsize',sz)
text(450, ymax*0.6, sprintf('P = %0.3f', P),'fontsize',sz)
text(450, ymax*0.5, sprintf('widthP = %0.1f', Pwidth),'fontsize',14)
text(450, ymax*0.4, sprintf('nmP = %0.1f', Pnm),'fontsize',14)
text(450, ymax*0.3, sprintf('GG = %0.2f', GG),'fontsize',sz)
drawnow

end


