Refactor dynamic menus handling.

 - Various cosmetics and clean-ups.
 - More error checking in debug mode.
 - Improve the behavior of the dynamic menus when a new file is opened while a menu is opened.