function T=TMM_Grating_Matrix(wavelength, Period, NG, n1, n2, loss)
% Calculate the total transfer matrix of the gratings
l=Period/2;
T_hw1=TMM_HomoWG_Matrix(wavelength,l,n1,loss);
T_is12=TMM_IndexStep_Matrix(n1,n2);
T_hw2=TMM_HomoWG_Matrix(wavelength,l,n2,loss);
T_is21=TMM_IndexStep_Matrix(n2,n1);
q=length(wavelength);
Tp=zeros(2,2,q); T=Tp;
for i=1:length(wavelength)
  Tp(:,:,i)=T_hw2(:,:,i)*T_is21(:,:,i)*T_hw1(:,:,i)*T_is12(:,:,i);
  T(:,:,i)=Tp(:,:,i)^NG; % 1st order uniform Bragg grating
  % for an FP cavity, 1st order cavity, insert a high index region, n2.
  T(:,:,i)=Tp(:,:,i)^NG * (T_hw2(:,:,i))^1 * Tp(:,:,i)^NG * T_hw2(:,:,i);
end