Planar Diffraction Analysis of Homogeneous and Longitudinally Inhomogeneous Gratings Based on Legendre Expansion of Electromagnetic Fields