function [J_P,J_Q,err_P,err_Q] = form_J_inj_polar(VV,connect_m,YBUS,m_Pinj,m_Qinj)
% Syntax:  [J_P,J_Q,err_P,err_Q] = form_J_inj_polar(VV,connect_m,YBUS...
%                                  m_Pinj,m_Qinj)
% 
% Purpose:   To form the measurement jacobian as well as error corresponding
%            to conventional real and reactive power injection measurement 
%            w.r.t. voltage angle and magnitude in order
%            
% Input:    VV        - Voltage vector in complex form
%           connect_m - Connectivity matrix
%           YBUS      - bus admittance matrix
%           m_Pinj    - Pinjection measurement information matrix
%           m_Qinj    - Qinjection measurement information matrix
%           
% Output:   J_P    - Jacobian corresponding to conventional real power 
%                    injection measurement
%           J_Q    - Jacobian corresponding to conventional reactive power 
%                    injection measurement
%           err_P  - error corresponding to conventional real power 
%           err_Q  - error corresponding to conventional reactive power
%
% Calls:     
% Called by SE_WLS
%
nob=length(VV(:,1));
G=real(YBUS);B=imag(YBUS);
Pindex=m_Pinj(:,1);%Real power injection measurement index vector
Qindex=m_Qinj(:,1);%Reactive power injection measurement index vector
S_calc=VV.*conj(YBUS*VV);%complex power injection vector (calculated)

VM=abs(VV);VA=angle(VV);
err_P=[];
J11=zeros(length(Pindex),nob);
J12=zeros(length(Pindex),nob);

if isempty(Pindex)==0
    for i=1:length(Pindex)
        k=Pindex(i);
        temp1=real(S_calc(k));temp2=imag(S_calc(k));
        for j=1:nob
            if k==j
                J11(i,j)=-temp2-VM(k)*VM(k)*B(k,k);
                J12(i,j)=(temp1+VM(k)*VM(k)*G(k,k))/VM(k);
            else
                if connect_m(k,j)==1
                    J11(i,j)=VM(k)*VM(j)*(G(k,j)*sin(VA(k)-VA(j))-B(k,j)*cos(VA(k)-VA(j)));
                    J12(i,j)=VM(k)*(G(k,j)*cos(VA(k)-VA(j))+B(k,j)*sin(VA(k)-VA(j)));
                end
            end
        end        
        [err_P]=[err_P;m_Pinj(i,2)-temp1];
    end
end
J_P=[J11 J12];

err_Q=[];
J31=zeros(length(Qindex),nob);
J32=zeros(length(Qindex),nob);
if isempty(Qindex)==0        
    for i=1:length(Qindex)
        k=Qindex(i);
        temp1=real(S_calc(k));temp2=imag(S_calc(k));     
        for j=1:nob
            if k==j                    
                J31(i,j)=temp1-VM(k)*VM(k)*G(k,k);
                J32(i,j)=(temp2-VM(k)*VM(k)*B(k,k))/VM(k);
            else
                if connect_m(k,j)==1
                    J31(i,j)=-VM(k)*VM(j)*(G(k,j)*cos(VA(k)-VA(j))+B(k,j)*sin(VA(k)-VA(j)));
                    J32(i,j)=VM(k)*(G(k,j)*sin(VA(k)-VA(j))-B(k,j)*cos(VA(k)-VA(j)));
                end
            end
        end                
        [err_Q]=[err_Q;m_Qinj(i,2)-temp2];
    end
end
J_Q=[J31 J32];