function [rgb] = z2rgb_kawski(z,a,g)
% function [rgb] = z2rgb_kawski(z {,a {,g}})
%
% converts complex numbers into values in unit RGB cube.
% for gridded version: a is axes highlighting width (a=0 gives no axes)
% g is grid spacing (g=0 gives no grid). Added 6/15/07
% Debugged for falling outside unit cube, changed to double-cone 11/25/07
%
% Alex Barnett 11/11/05, influenced by Matthias Kawski

m = abs(z) + 1e-15;

if nargin>2 & g>0
  m = m.*(0.8 + 2*xor(mod(real(z),g)>g/2,mod(imag(z),g)>g/2));   % 0.45
end
if nargin>1 & a~=0
  s = 1 - (1-(max(0,1-abs(real(z))/a)+max(0,1-abs(imag(z))/a))).*(m/2 + 1).^-1;
else
  s = 1 - 1.*(m/2 + 1).^-1;     % bit more dyn range for large & small values
  %s = (1+tanh(log(m)))/2;        % original 2005 version
end
x = real(z)./m;           % x,y is point on unit circle
y = imag(z)./m;
w = 1.22*(0.5-abs(s-0.5));        % prefactor found empirically via test_z2rgb
%w = 2*s.*(1-s); % radius of cone as func of saturation, adjust prefactor (3)?
rgb(:,:,1) = s + w.*(-y/sqrt(6) + x/sqrt(2));
rgb(:,:,2) = s + w.*(-y/sqrt(6) - x/sqrt(2));
rgb(:,:,3) = s + w.*y*sqrt(2/3);
%end
