% David O. Lignell
% Routine returns the Coefficient matrix for the pressure equation
%    As well as the rhs vector Bp
% e.g. Ap * P = Bp,  or P = Ap/Bp
% Ap should not change, so we only have to do this once
% Note for diag -1, the last element of the diagonal is trimmed, while for
% diag 1 the first element is trimmed (if the diagonals are the size of the mat)
% Note we fix a value of P=0 at about the middle cell.  This can be commented out
%   but be sure to uncomment the P shift for the soln in ns.m (e.g. the shift around the average).

nxv = nx-2;                              % number of p cells x-dir
nyv = ny-2;
nvars = nxv*nyv;             
Bp = zeros(nx,ny);   % not nxv, nyv

if Ap_init == 1
    
    ds = repmat(dt*dx/rho/dy, nvars,1);              % south neighbor diagonal
    dn = ds;
    de = repmat(dt*dy/rho/dx, nvars,1);
    dw = de;
    dp = repmat(-2*dt/rho*(dx/dy+dy/dx),nvars,1);

    de([1:nxv:nvars])  = 0.0;     % correct right wall
    dw([nxv:nxv:nvars]) = 0.0;    % correct left wall
    % correct top and bottom
    dp([1:nxv nvars-nxv+1:nvars]) = dp([1:nxv nvars-nxv+1:nvars]) + dt/rho*dx/dy;
    % correct left wall
    dp(1:nxv:nvars) = dp(1:nxv:nvars) + dt/rho*dy/dx;
    % correct right wall
    dp(nxv:nxv:nvars) = dp(nxv:nxv:nvars) + dt/rho*dy/dx;
    
    Ap = spdiags([ds dw dp de dn], [-nxv -1 0 1 nxv], nvars, nvars);

    Ap(floor(nvars/2+nxv/2),:) = 0;                    % specify pressure at one point
    Ap(floor(nvars/2+nxv/2),floor(nvars/2+nxv/2)) = 1.0;
    
    % get the right hand side here
    Ap_init = 0;
end
   
for i=2:nx-1
    for j=2:ny-1
        Bp(i,j) = dy*(u_hat(i+1,j)-u_hat(i,j)) + dx*(v_hat(i,j+1)-v_hat(i,j));
    end
end
Bp(:,2)    = Bp(:,2) - dx*v_vel(:,2);              % fix bottom
Bp(:,ny-1) = Bp(:,ny-1) + dx*v_vel(:,ny);          % fix top
Bp(2,:)    = Bp(2,:) - dy*u_vel(2,:);              % fix left
Bp(nx-1,:) = Bp(nx-1,:) + dy*u_vel(nx,:);          % fix right

Bp = reshape(Bp(2:nx-1,2:ny-1),nvars,1);
Bp(floor(nvars/2+nxv/2),1) = 0.0;                     % specifying pressure at one point
