function PermK = Darcy_SmplnPerm_QuadriMesh(fxnK,QuadriMesh,GAUSSQUAD)
%% Darcy on quadri.mesh: Sampling permeability using a Gaussian quadrature
% PermK: elementwise constant 2x2 SPD matrix (as averages on elements) 
% James Liu, Zhuoran Wang, ColoState; 2012/07--2018/12 

%% Mesh info 
NumEms = QuadriMesh.NumEms;
k1 = QuadriMesh.elem(:,1);  k2 = QuadriMesh.elem(:,2);  
k3 = QuadriMesh.elem(:,3);  k4 = QuadriMesh.elem(:,4);
x1 = QuadriMesh.node(k1,1);  y1 = QuadriMesh.node(k1,2);
x2 = QuadriMesh.node(k2,1);  y2 = QuadriMesh.node(k2,2);
x3 = QuadriMesh.node(k3,1);  y3 = QuadriMesh.node(k3,2);
x4 = QuadriMesh.node(k4,1);  y4 = QuadriMesh.node(k4,2);
area = 0.5*( (x2-x1).*(y3-y1) - (x3-x1).*(y2-y1)...
           + (x3-x1).*(y4-y1) - (x4-x1).*(y3-y1));

%% Coefficients of bilinear mapping 
CofA = zeros(NumEms,4);
CofA(:,1) = x1;
CofA(:,2) = x2-x1;
CofA(:,3) = x4-x1;
CofA(:,4) = (x3+x1)-(x2+x4);
CofB = zeros(NumEms,4);
CofB(:,1) = y1;
CofB(:,2) = y2-y1;
CofB(:,3) = y4-y1;
CofB(:,4) = (y3+y1)-(y2+y4);

%% NOTE: Permability is a 2x2 SPD matrix (pointwise) 
PermK = zeros(NumEms,2,2);
NumQuadPts = size(GAUSSQUAD.RECT,1);
GAUSSQUADRECT1 = ones(NumQuadPts,2) - GAUSSQUAD.RECT(:,1:2);
for k=1:NumQuadPts
  xhat = GAUSSQUADRECT1(k,1);
  yhat = GAUSSQUADRECT1(k,2);
  qp = [CofA(:,1) + CofA(:,2)*xhat + CofA(:,3)*yhat + CofA(:,4)*xhat*yhat,...
        CofB(:,1) + CofB(:,2)*xhat + CofB(:,3)*yhat + CofB(:,4)*xhat*yhat];
  jac = (CofB(:,3)+CofB(:,4)*xhat) .* (CofA(:,2)+CofA(:,4)*yhat)...
      - (CofA(:,3)+CofA(:,4)*xhat) .* (CofB(:,2)+CofB(:,4)*yhat);
  MatK = fxnK(qp);
  for i=1:2
    for j=1:2
      PermK(:,i,j) = PermK(:,i,j) + GAUSSQUAD.RECT(k,3)*(jac.*MatK(:,i,j));
    end
  end
end
for i=1:2
  for j=1:2
    PermK(:,i,j) = PermK(:,i,j)./area;
  end
end

%% JL20160517: ALT.: Splitting ea.quadri. into 2 triangles for integration 

return;