refactor to use more RAII and have better locality of reference when dealing with menu items. Also minor cleanup