% Nernst

% Determine the grid size and generate the diffusion.
  N = input('Enter Time:');
  nRedMolecules=4;  %Number of Red Particles
  permRed=.1;  %permeability of red ions
  nBlueMolecules=4;
  permBlue=.5; %
  membrane=2; %Membrane at x=2
  [a b]=DiffusionMem(N,membrane,permRed);
  xRed=[a];
  xRedLength=length(xRed);
  yRed=[b];
  for red=2:nRedMolecules
      [c d] = DiffusionMem(N,membrane,permRed);
      xRed=[xRed;c];
      yRed=[yRed;d];
      red= red + 1;
  end
  [e f]=DiffusionMem(N,membrane,permBlue); %Initial array for blue particles
  xBlue=[e]; %Initial X matrix for Blue Particles
  xBlueLength=length(xBlue);
  yBlue=[f]; %Initial y Martix for Blue particles
  for blue=2:nBlueMolecules
      [g h] = DiffusionMem(N,membrane,permBlue);
      xBlue=[xBlue;g]; %Concatinate each x row
      yBlue=[yBlue;h]; %Concatinate each y row
      blue = blue + 1; %Update Index
  end
    
% Create the figure window
  close all
  figure
  set(gcf,'position',[150 50 600 600])
  hold on
 
  
% Draw the boundary and highlight the origin...
  M = N+.5;
  plot([-M M M -M -M],[-M -M M M -M],'k')
 
  
% Set the axes
  axis([-M M -M M])
  axis equal square manual
% Label in and out
  yText=M-1;
  xTextMin=-M+.5;
  xTextMax=M-3.5;
  text(xTextMin,yText,'Inside Cell')
  text(xTextMax,yText,'Outside Cell')
% Set membrane
  xMem=membrane;
  yMin=-M;
  yMax=M;
  blueConOut=0; %Conc of blue ions outside the cell
% Animates the walk...
  for col=2:xRedLength %By column
      plot([xMem xMem],[yMin yMax],'-c')
      for row=1:nRedMolecules %By Row
          plot(xRed(row,col-1),yRed(row,col-1),'.w','Markersize',20)
          plot(xRed(row,col),yRed(row,col),'.r','Markersize',20)
          plot(xBlue(row,col-1),yBlue(row,col-1),'.w','Markersize',20)
          plot(xBlue(row,col),yBlue(row,col),'.b','Markersize',20)
          if xBlue(row,col)>2
              blueConOut=blueConOut +1;
          end
      end
      if blueConOut==4
          ENA=58*log(blueConOut);          
      elseif blueConOut==0
          ENA=58;
      else
          ENA=58*log(blueConOut/(nBlueMolecules-blueConOut));
      end
      xlabel(['Volt=',num2str(ENA,'%4.4f'),' mv'])
      pause(.1)
      blueConOut=0;
  end
  
  