A General Derivation of the Formula for the Diffraction by a Perfect Grating