Electromagnetic theory of gratings