Optimization of Perfectly Conducting Gratings a General Method