function y = fernifs(x,p1,p2,p3,p4)
% FERNIFS is a map of IFS Fern map for a single step.
% y = fernifs(x,p1,p2,p3,p4)
% p1, p2, p3 and p4 are probabilities for selecting
% corresponding maps W1, W2, W3 and W4.
%
% defaults: p1=0.4, p2=0.2, p3=0.2, p4=0.2

% Copyright(C) 2004 Tohru Ikeguchi, All Rights Reserved

if nargin<1, x = randn(2,1); end

if nargin<2 | isempty(p1), p1= 0.4; end
if nargin<3 | isempty(p2), p2= 0.2; end
if nargin<4 | isempty(p3), p3= 0.2; end
if nargin<5 | isempty(p4), p4= 0.2; end

if p1+p2+p3+p4 ~= 1, 
   p1+p2+p3+p4
   error('sum of p is larger than 1');
end

if size(x,1) == 1 & size(x',1) == 1
  x(2) = randn;
end

if size(x,1) > 2 & size(x,2) >2
  size(x)
  error('Should not happen');
  return
end


pb = rand;

if pb<=p1
   y(1) =  0.836.*x(1)+0.044.*x(2);
   y(2) = -0.044.*x(1)+0.836.*x(2)+0.169;
elseif pb<=(p1+p2)
   y(1) = -0.141.*x(1)+0.302.*x(2);
   y(2) =  0.302.*x(1)+0.141.*x(2)+0.127;
elseif pb<=(p1+p2+p3)
   y(1) =  0.141.*x(1)-0.302.*x(2);
   y(2) =  0.302.*x(1)+0.141.*x(2)+0.169;
else
   y(1) =  0;
   y(2) =  0.175337.*x(2);
end

return
