function mesh = addrandomfield( mesh, amount, whichMgen, smoothness, add )
%mesh = addrandomfield( mesh, amount, whichMgen, smoothness, add )
%   Add a random amount of growth factor to every point.

    if nargin < 4, add = 1; end
    
    extraGrowth = rand(size(mesh.morphogens,1),1) - 0.5;
    extraGrowth = smoothMorphogen( mesh.edgeends, extraGrowth, 2 );
    extraGrowth = extraGrowth - min(extraGrowth);
    maxgrowth = max( extraGrowth );
    if maxgrowth > 0
        extraGrowth = extraGrowth * (amount/maxgrowth);
    end
    if add
        mesh.morphogens(:,whichMgen) = extraGrowth + mesh.morphogens(:,whichMgen);
    else
        mesh.morphogens(:,whichMgen) = extraGrowth;
    end
    mesh.saved = 0;
end

function g = smoothMorphogen( edges, g, n )
    for r=1:n
        gr = zeros( size(g) );
        nbs = zeros( size(g) );
        for i=1:size(edges,1)
            ends = edges(i,:);
            gr(ends) = gr(ends) + g(ends([2,1]));
            nbs(ends) = nbs(ends) + 1;
        end
        g = gr ./ nbs;
      % gtr = g'
      % nbstr = nbs'
    end
    g = gr;
end
