function s = log(s0)
%SAXS/LOG Take natural logarithm of SAXS image data.
%   LOG(S) returns a SAXS image object where the pixel intensities
%   are the natural logarithm of pixel intensities in SAXS image S.
%   Other SAXS attributes are copied from S.
%
%   Before taking the logarithm, any zero- or negative-valued pixels in S
%   are changed to a value half of the lowest positive intensity value in
%   S. In other words, if there are pixels valued 0 and 1 and up in S, the
%   0 values are changed to 0.5.
%
%   Likewise, any NaN values in S are changed to one half the value that
%   zeroes and negatives are changed to.  In the above example, any NaN
%   values would be changed to 0.25 before computing logarithms.

if ~ isa(s0, 'saxs')
    error('I need a SAXS image argument.')
end

if isempty(s0.log)  % log not yet taken
    s = s0;
    
    intensitymin = min(s.pixels(find(s.pixels > 0)));  % least positive value
    
    s.pixels(s.pixels <= 0) = intensitymin / 2;
    s.pixels(isnan(s.pixels)) = intensitymin / 4;
    s.pixels = log(s.pixels);
    s.log = 'log';
    s.history = strvcat(s.history, 'natural logarithm');
else  % log already taken; don't do it again
    s = s0;
    warning('I can only take the logarithm of an image once.')
end