function [membraneImg,u,output]=membrane(img,tf,dtime,I)
%
% A modified version of CNN falling membrane template: in this
% project used for contrast enhancement.
% 
% Usage: [membrane, u, output]=membrane(imageFile, tf, dtime,I);
%
% <Output parameters>
% membrane:  the output membrane image
% u:         the original image scaled to CNN's range of [-1,1]
% output:    the direct output of CNN
%
% u and output are useful for later, further CNN image processing.
%
% <Input parameters>
% img:       image, usually read in through imread(...)
% tf:        final time to run to
% dtime:     display time, i.e. the time between successive displays
%            of the CNN simulation progress: defaulted to 1, which
%            is good for detailed viewing purposes.  To save
%            some Matlab computation time, one can make it larger.
% I :        gravity parameter for the falling membrane, defaulted to -1.0
%

% Concept courtesy of Kenneth R. Crounse, crounse@fred.EECS.Berkeley.EDU; 
% Implementation modified by Philip L. Tsai, tsailipu@cs.stanford.edu.


% either go [I=-1.0, center of A = -4] or [I=-0.05, center of A = -3] as
% the default
if nargin < 4, I = -1.0; end %I = -0.05; end
if nargin < 3, dtime = 1; end
if nargin < 2, tf = 10; end

A = template_form([-4.0 0.5 0.5]);
B = template_form([-4.0 0.5 0.5]);
%A = [0 1 0; 1 -3 1; 0 1 0]
%B = [0 1 0;1 -4 1;0 1 0]

u = im2double(img);
uu = max(max(u));
ul = min(min(u));
[uy,ux] = size(u);
u = (u-ul)/(uu-ul)*2-1;
%x0 = 1*ones(uy,ux);

% uses -u so that the output, the difference, will start out showing
% more features and gradually lose them over time as it converges to
% equilibrium (in other words, the membrane (output+u+1) start out in
% the smoother side of the equilibrium) -- this can help if we would
% like to brighten the dark regions more by shortening tf.  If one
% uses x0=1 (so membrane is now at the other side of the equilibrium),
% then the ouput will start out showing little features and gradually 
% converge to the equilibrium -- this way we can't take advantage of
% short tf to brighten the dark regions while not lose features.

x0=-u;
 
output=viewcnn(A,B,I,x0,u,tf,dtime);
output=pwlsig(output);
membraneImg=output+u+1;




