Optimal Control of Spin Dynamics in Magnetic Resonance