// Copyright (C) 1997-2004 Alias Systems Corp.
// 
// The information in this file is provided for the exclusive use of the
// licensees of Alias.  Such users have the right to use, modify,
// and incorporate this code into other products for purposes authorized
// by the Alias license agreement, without fee.
// 
// ALIAS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
// INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
// EVENT SHALL ALIAS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
// CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
// DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

//
//  Description:
//	This contains procedures necessary for
//	the drag-n-drop Marking Menus editor.
//

//
//  HERE ARE THE OPTIONVARS USED IN THIS FILE.
//
//
//  Each Marking Menu has the following information associated with it:
//	-> filename (string)
//	-> annotation (string)
//	-> a flag indicating whether the menu should be displayed as a true Marking Menu or just a Motif menu (boolean)
//	-> a flag indicating whether the menu has been exported to the hotkey editor (boolean)
//  The Marking Menus are arranged in a sequential list, and the
//  following optionVars store arrays of the items listed above
//  for each Marking Menu:
//
//	markingMenuEditorFilenames		// array of strings
//	markingMenuEditorAnnotations		// array of strings
//	markingMenuEditorDisplayAsMMFlags	// array of ints (booleans)
//	markingMenuEditorIsNamedCommandFlags	// array of ints (booleans)
//
//
//
//
//  These optionVars are related to the hotBox.  The hotBox has 5 zones
//  (North, South, East, West, and Center), each of which can have 3
//  Marking Menus (one for each mouse button) - hence 15 menus all together.
//  The annotations of these 15 menus are stored in the 15 optionVars below.
//
//	nameOfHotBoxN1MarkingMenu, nameOfHotBoxN2MarkingMenu, nameOfHotBoxN3MarkingMenu,  // North  1,2,3
//	nameOfHotBoxS1MarkingMenu, nameOfHotBoxS2MarkingMenu, nameOfHotBoxS3MarkingMenu,  // South  1,2,3
//	nameOfHotBoxE1MarkingMenu, nameOfHotBoxE2MarkingMenu, nameOfHotBoxE3MarkingMenu,  // East   1,2,3
//	nameOfHotBoxW1MarkingMenu, nameOfHotBoxW2MarkingMenu, nameOfHotBoxW3MarkingMenu,  // West   1,2,3
//	nameOfHotBoxC1MarkingMenu, nameOfHotBoxC2MarkingMenu, nameOfHotBoxC3MarkingMenu   // Center 1,2,3
//
//




proc int menuEditorGetIndex(string $radialPosition, int $overflowRow)
{
	int $index;

	if ($radialPosition == "None") {
		$index = $overflowRow + 8 - 1;
	}
	else if ($radialPosition == "N") {
		$index = 0;
	}
	else if ($radialPosition == "NE") {
		$index = 1;
	}
	else if ($radialPosition == "E") {
		$index = 2;
	}
	else if ($radialPosition == "SE") {
		$index = 3;
	}
	else if ($radialPosition == "S") {
		$index = 4;
	}
	else if ($radialPosition == "SW") {
		$index = 5;
	} 
	else if ($radialPosition == "W") {
		$index = 6;
	}
	else if ($radialPosition == "NW") {
		$index = 7;
	}

	return $index;
}

global proc menuEditorCreateSubMenu(string $theMenuEditor, string $radialPosition, int $overflowRow)
{
	string $menuTypes[] = `menuEditor -q -mit $theMenuEditor`;
	int $subEditorsOpen[] = `menuEditor -q -subMenuEditorsOpen $theMenuEditor`;
	string $title;
	string $windowName;
	int $index;

	$index = menuEditorGetIndex($radialPosition, $overflowRow);

	if ($subEditorsOpen[$index]) {
		// The sub-menuEditor is already popped up, so don't do it again !
		return;
	}

	if ($menuTypes[$index] != "submenu"){
		menuEditor -e -d $radialPosition $overflowRow $theMenuEditor;
		menuEditor -e -subMenuAt $radialPosition $overflowRow $theMenuEditor;
	}

	if ($radialPosition == "None") {
		$title = "Linear Item " + $overflowRow;
	}
	else {
		$title = $radialPosition + " Item";
	}

	$windowName = `window -resizeToFitChildren true -title ("Submenu Editor For " + $title)`;
		string $pageName = `formLayout`;

			global int $menuEditorCellWidth;
			global int $menuEditorFudgeFactorDueToVerticalScrollBar;
			string $SubEditor = `menuEditor
				-cellWidth $menuEditorCellWidth
				-w (3*$menuEditorCellWidth + $menuEditorFudgeFactorDueToVerticalScrollBar)
				-h 400
				-iconMenuCallback "createMenuEditorCellMenu"`;

			formLayout -e 
				-af $SubEditor top 20
				-af $SubEditor left 20
				-af $SubEditor bottom 20
				-af $SubEditor right 20
				$pageName;

			menuEditor -e -subMenuEditorWindow $windowName -subMenuOf $theMenuEditor $radialPosition $overflowRow $SubEditor;

	showWindow $windowName;
}

global proc menuEditorSaveEditInfo(
	string $window,
	string $theMenuEditor, string $radialPosition, int $overflowRow,

	string $labelField,
	string $iconField,
	string $commandField,
	string $checkOrRadio,
	string $optionBoxCheckBox,
	string $optBoxCmdField,

	int $isSubmenuItem
) {
	string $menuItemLabel = `textFieldGrp -q -tx $labelField`;

	// To create a new menu item, the user must at least
	// enter a valid label.
	//
	if ($menuItemLabel == "") {
		confirmDialog -title "Alert"
			-button "OK"
			-parent "markingMenuEditorWnd"
			-defaultButton "OK"
			-message "       Please enter a label.       ";
		return;
	}

	// Save the label.

	menuEditor -e -l $menuItemLabel $radialPosition $overflowRow $theMenuEditor;

	if (!$isSubmenuItem) {

		string $iconFilename = `textFieldGrp -q -fileName $iconField`;
		string $menuItemCommand = `scrollField -q -tx $commandField`;
		int $selectedRadioButton = `radioButtonGrp -q -select $checkOrRadio`;
		int $isOptionBoxPresent = `checkBox -q -value $optionBoxCheckBox`;
		string $optionBoxCommand = `scrollField -q -text $optBoxCmdField`;

		// Save other parameters.

		menuEditor -e -i $iconFilename $radialPosition $overflowRow $theMenuEditor;
		menuEditor -e -c $menuItemCommand $radialPosition $overflowRow $theMenuEditor;

		switch ($selectedRadioButton) {
			case 1 : // check box
				menuEditor -e -cbp true $radialPosition $overflowRow $theMenuEditor;
				menuEditor -e -cbs 1 $radialPosition $overflowRow $theMenuEditor;
				break;
			case 2 : // radio button
				menuEditor -e -rbp true $radialPosition $overflowRow $theMenuEditor;
				menuEditor -e -rbs 0 $radialPosition $overflowRow $theMenuEditor;
				break;
			default : // nothing
				menuEditor -e -cbp false $radialPosition $overflowRow $theMenuEditor;
				menuEditor -e -rbp false $radialPosition $overflowRow $theMenuEditor;
				break;
		}

		if ($isOptionBoxPresent) {
			menuEditor -e -obp true $radialPosition $overflowRow $theMenuEditor;
			menuEditor -e -obc $optionBoxCommand $radialPosition $overflowRow $theMenuEditor;
		}
		else {
			menuEditor -e -obp false $radialPosition $overflowRow $theMenuEditor;
		}
	}

	deleteUI $window;
}

global proc menuEditorCreateMenuItemEditDialog(string $theMenuEditor, string $radialPosition, int $overflowRow, string $menuTitle)
{
	string $menuTypes[] = `menuEditor -q -mit $theMenuEditor`;
	int $index = menuEditorGetIndex($radialPosition, $overflowRow);
	int $isSubmenuItem = false;

	if ($menuTypes[$index] == "separator") {
		confirmDialog -title "Alert"
			-button "OK"
			-parent "markingMenuEditorWnd"
			-defaultButton "OK"
			-message "       Sorry, separators have no editable attributes.       ";
		return;
	}
	else if ($menuTypes[$index] == "submenu") {
		$isSubmenuItem = true;
	}

	string $windowName;
	string $tempString;

	$windowName = $menuTitle;

	if ($radialPosition == "None") {
		string $buffer[];
		int $j;
		$windowName = "win" + $overflowRow;
		$j = tokenize($menuTitle, $buffer);
		$menuTitle = $buffer[0] + " " + $buffer[1] + " " + $overflowRow;
	}

	$tempString = $windowName;
	$windowName = `substitute " " $windowName "_"`;
	if ($windowName == "") {
		$windowName = $tempString;
	}

	if (`window -exists $windowName`) {
		showWindow $windowName;
		return;
	}

	string $menuItemLabel[] = `menuEditor -q -l $theMenuEditor`;
	string $iconFilename[] = `menuEditor -q -i $theMenuEditor`;
	string $menuItemCommand[] = `menuEditor -q -c $theMenuEditor`;
	int $isCheckBoxPresent[] = `menuEditor -q -cbp $theMenuEditor`;
	int $isRadioButtonPresent[] = `menuEditor -q -rbp $theMenuEditor`;
	int $isOptionBoxPresent[] = `menuEditor -q -obp $theMenuEditor`;
	string $optionBoxCommand[] = `menuEditor -q -obc $theMenuEditor`;
	int $index = menuEditorGetIndex($radialPosition, $overflowRow);

	window -resizeToFitChildren true -t ("Edit " + $menuTitle) $windowName;

	if ($isSubmenuItem) {
		// Submenu items are a special case.
		// Only their label can be edited.
		//
		string $form1 = `formLayout`;
			string $labelField = `textFieldGrp -l "Label"
				-cw 1 95
				-cat 1 right 5
				-cat 2 left 0
				-adjustableColumn 2
				-text $menuItemLabel[$index]`;

			string $saveBtn = `button -l "Save and Close"
				-c ("menuEditorSaveEditInfo(\"" + $windowName + "\",\"" + $theMenuEditor + "\",\"" + $radialPosition + "\"," + $overflowRow
				+ ",\"" + $labelField + "\",\"\",\"\",\"\",\"\",\"\",true);"
				)`;

			string $closeBtn = `button -l "Close" -c ("deleteUI " + $windowName)`;

			int $divisions = `formLayout -query -numberOfDivisions $form1`;

			formLayout -e
				-af $labelField top 10
				-af $labelField left 10
				-af $labelField right 10

				//-ac $saveBtn top 10 $labelField
				-af $saveBtn bottom 10
				-af $saveBtn left 10
				-ap $saveBtn right 5 ($divisions/2)

				//-ac $closeBtn top 10 $labelField
				-af $closeBtn bottom 10
				-ap $closeBtn left 5 ($divisions/2)
				-af $closeBtn right 10
				$form1;
		setParent ..;

		showWindow $windowName;

		return;
	}

	string $form1 = `formLayout`;
		string $labelField = `textFieldGrp -l "Label"
			-cw 1 95
			-cat 1 right 5
			-cat 2 left 0
			-adjustableColumn 2
			-text $menuItemLabel[$index]`;
		string $iconField = `textFieldGrp -l "Icon Filename"
			-cw 1 95
			-cat 1 right 5
			-cat 2 left 0
			-adjustableColumn 2
			-fileName $iconFilename[$index]`;
		string $commandLabel = `text -align right -l "Command(s) :"`;
		string $commandField = `scrollField -wordWrap false -h 125 -text $menuItemCommand[$index]`;

		frameLayout
			-l "Optional Properties"
			-labelAlign "center"
			-labelIndent 10
			-borderStyle "etchedIn"
			propertiesFrame;

			string $form2 = `formLayout`;

				string $checkOrRadio = `radioButtonGrp
					-nrb 3
					// -cw4 130 80 80 80
					-label1 "Check Box"
					-label2 "Radio Button"
					-label3 "Neither"`;
				string $radioGroupText = `text -align left
					-l ("Note: all radio button menu items created here will\n"
					+ "share the same default radio button collection."
					)`;
				separator zeparator;   // (for lack of a better name)
				string $optionBoxCheckBox = `checkBox -l "Option Box"
					-value $isOptionBoxPresent[$index]`;
				string $optBoxCmdLabel = `text -align right -l "Option Box Command(s) :" -enable $isOptionBoxPresent[$index]`;
				string $optBoxCmdField = `scrollField -wordWrap false -h 85 -text $optionBoxCommand[$index] -enable $isOptionBoxPresent[$index]`;

				formLayout -e
					-af $checkOrRadio top 10
					-af $checkOrRadio left 10

					-ac $radioGroupText top 10 $checkOrRadio
					-af $radioGroupText left 10

					-ac zeparator top 10 $radioGroupText
					-af zeparator left 10
					-af zeparator right 10

					-ac $optionBoxCheckBox top 10 zeparator
					-af $optionBoxCheckBox left 10

					-ac $optBoxCmdLabel top 10 $optionBoxCheckBox
					-af $optBoxCmdLabel left 10

					-ac $optBoxCmdField top 10 $optBoxCmdLabel
					-af $optBoxCmdField left 10
					-af $optBoxCmdField right 10
					-af $optBoxCmdField bottom 10
					$form2;

				if ($isCheckBoxPresent[$index])
					radioButtonGrp -e -select 1 $checkOrRadio;
				else if ($isRadioButtonPresent[$index])
					radioButtonGrp -e -select 2 $checkOrRadio;
				else
					radioButtonGrp -e -select 3 $checkOrRadio;

				checkBox -e
					-onc ("text -e -enable true " + $optBoxCmdLabel + "; scrollField -e -enable true " + $optBoxCmdField)
					-ofc ("text -e -enable false " + $optBoxCmdLabel + "; scrollField -e -enable false " + $optBoxCmdField)
					$optionBoxCheckBox;
			setParent ..;
		setParent ..;

		string $saveBtn = `button -l "Save and Close"
			-c ("menuEditorSaveEditInfo(\"" + $windowName + "\",\"" + $theMenuEditor + "\",\"" + $radialPosition + "\"," + $overflowRow
			+ ",\"" + $labelField + "\",\"" + $iconField + "\",\"" + $commandField
			+ "\",\"" + $checkOrRadio + "\",\"" + $optionBoxCheckBox + "\",\"" + $optBoxCmdField
			+ "\",false);"
			)`;

		string $closeBtn = `button -l "Close" -c ("deleteUI " + $windowName)`;

		formLayout -e
			-af $labelField top 10
			-af $labelField left 10
			-af $labelField right 10

			-ac $iconField top 10 $labelField
			-af $iconField left 10
			-af $iconField right 10

			-ac $commandLabel top 10 $iconField
			-af $commandLabel left 10
			$form1;

		int $divisions = `formLayout -query -numberOfDivisions $form1`;

		formLayout -e
			-af $saveBtn bottom 10
			-af $saveBtn left 10
			-ap $saveBtn right 5 ($divisions/2)

			-af $closeBtn bottom 10
			-ap $closeBtn left 5 ($divisions/2)
			-af $closeBtn right 10

			-ac propertiesFrame bottom 10 $saveBtn
			-af propertiesFrame left 10
			-af propertiesFrame right 10
			$form1;

		formLayout -e
			-ac $commandField top 10 $commandLabel
			-ac $commandField bottom 10 propertiesFrame
			-af $commandField left 10
			-af $commandField right 10
			$form1;
	setParent ..;

	showWindow $windowName;
}

//radialPosition -- "None" for no radial position
//overflowRow -- 0 for no overflow
global proc createMenuEditorCellMenu(string $theMenuEditor,string $parentIcon,string $menuTitle,string $radialPosition, 
				     int $overflowRow) 
{
	popupMenu -parent $parentIcon;
		menuItem -l $menuTitle;
		menuItem -d true;
		menuItem -d true;
		string $editItem = `menuItem -ecr false -l "Edit Menu Item..." -c ("menuEditorCreateMenuItemEditDialog (\"" + $theMenuEditor + "\", \"" +  
								      $radialPosition + "\", " +  $overflowRow + ", \"" + $menuTitle +
								      "\")")`;
		if ($radialPosition == "None") {
			menuItem -ecr false -l "Insert Separator" -c("menuEditor -e -sp \"" + $radialPosition  + "\" " + $overflowRow + " " + 
							$theMenuEditor);
		}
		menuItem  -ecr false -l "Delete Menu Item" -c ("evalDeferred \"menuEditor -e -delete \\\"" + $radialPosition + "\\\" " + $overflowRow + " " + $theMenuEditor + "\"" );
		menuItem  -ecr false -l "Popup Submenu..." -c ("evalDeferred \"menuEditorCreateSubMenu (\\\"" + $theMenuEditor + "\\\", \\\"" + $radialPosition + "\\\", " + 
						 $overflowRow + ")\"");
		setParent -m ..;
}

// ===============================================

proc setArrayEntryInMarkingMenuEditorFilenames(int $index, string $value) {

	if (`optionVar -exists markingMenuEditorFilenames`) {
		string $filenameArray[] = `optionVar -q markingMenuEditorFilenames`;
		$filenameArray[$index] = $value;

		// Rebuild the optionVar array.
		//
		optionVar -clearArray markingMenuEditorFilenames;
		int $j;
		for ($j = 0; $j < size($filenameArray); ++$j)
			optionVar -stringValueAppend markingMenuEditorFilenames $filenameArray[$j];
	}
}

proc setArrayEntryInMarkingMenuEditorAnnotations(int $index, string $value) {

	if (`optionVar -exists markingMenuEditorAnnotations`) {
		string $annotationArray[] = `optionVar -q markingMenuEditorAnnotations`;
		$annotationArray[$index] = $value;

		// Rebuild the optionVar array.
		//
		optionVar -clearArray markingMenuEditorAnnotations;
		int $j;
		for ($j = 0; $j < size($annotationArray); ++$j)
			optionVar -stringValueAppend markingMenuEditorAnnotations $annotationArray[$j];
	}
}

proc setArrayEntryInMarkingMenuEditorDisplayAsMMFlags(int $index, int $value) {

	if (`optionVar -exists markingMenuEditorDisplayAsMMFlags`) {
		int $displayAsMMArray[] = `optionVar -q markingMenuEditorDisplayAsMMFlags`;
		$displayAsMMArray[$index] = $value;

		// Rebuild the optionVar array.
		//
		optionVar -clearArray markingMenuEditorDisplayAsMMFlags;
		int $j;
		for ($j = 0; $j < size($displayAsMMArray); ++$j)
			optionVar -intValueAppend markingMenuEditorDisplayAsMMFlags $displayAsMMArray[$j];
	}
}

proc setArrayEntryInMarkingMenuEditorIsNamedCommandFlags(int $index, int $value) {

	if (`optionVar -exists markingMenuEditorIsNamedCommandFlags`) {
		int $isNamedCmdArray[] = `optionVar -q markingMenuEditorIsNamedCommandFlags`;
		$isNamedCmdArray[$index] = $value;

		// Rebuild the optionVar array.
		//
		optionVar -clearArray markingMenuEditorIsNamedCommandFlags;
		int $j;
		for ($j = 0; $j < size($isNamedCmdArray); ++$j)
			optionVar -intValueAppend markingMenuEditorIsNamedCommandFlags $isNamedCmdArray[$j];
	}
}

// Returns an array of 4 strings:
//    [0] == one of "N", "S", "E", "W", "C" if the menu is attached to a hotbox region; "" otherwise.
//    [1] == "true" if the menu is attached to the LMB, "" otherwise.
//    [2] == "true" if the menu is attached to the MMB, "" otherwise.
//    [3] == "true" if the menu is attached to the RMB, "" otherwise.
//
proc string[] markingMenuEditorGenerateHotBoxInfo(string $menuAnnotation) {

	string $nameOfOptionVar;
	string $region[] = { "N", "S", "E", "W", "C" };
	int $r, $button;
	int $isLeft = 0, $isMiddle = 0, $isRight = 0;
	string $returnValue[] = { "", "", "", "" };

	for ($r = 0; $r < size($region); ++$r) {
		for ($button = 1; $button <= 3; ++$button) {
			$nameOfOptionVar = generateNameOfHotBoxOptionVar($region[$r],$button);
			if (`optionVar -exists $nameOfOptionVar`)
				if (`optionVar -q $nameOfOptionVar` == $menuAnnotation) {
					switch ($button) {
						case 1: $isLeft   = 1; break;
						case 2: $isMiddle = 1; break;
						case 3: $isRight  = 1; break;
					}
				}
		}

		if ($isLeft || $isMiddle || $isRight) {
			$returnValue[0] = $region[$r];
			if ($isLeft)
				$returnValue[1] = "true";
			if ($isMiddle)
				$returnValue[2] = "true";
			if ($isRight)
				$returnValue[3] = "true";
			break;
		}
	}

	return $returnValue;
}

proc string generateMarkingMenuEditWindowName(string $markingMenuEditorWindowPrefix, int $index) {

	if (`optionVar -exists markingMenuEditorAnnotations`) {
		string $annotationArray[] = `optionVar -q markingMenuEditorAnnotations`;
		string $windowName = $markingMenuEditorWindowPrefix + $annotationArray[$index];
		return $windowName;
	}
	else return "";
}

proc int areAnyMarkingMenuEditWindowsOpen(string $markingMenuEditorWindowPrefix) {

	if (`optionVar -exists markingMenuEditorAnnotations`) {
		string $annotationArray[] = `optionVar -q markingMenuEditorAnnotations`;
		int $j;
		for ($j = 0; $j < size($annotationArray); ++$j)
			if (`window -exists ($markingMenuEditorWindowPrefix + $annotationArray[$j])`)
				return true;
		return false;
	}
	else
		return false;
}

proc string markingMenuEditorFilemask() {

	return "menu_*.mel";
}

proc string generateMarkingMenuEditorAnnotationFromFilenameAndExtension(string $filenameWithExtension) {

	int $length = `size $filenameWithExtension`;
	return `substring $filenameWithExtension 6 ($length-4)`;  // This removes the "menu_" prefix and the ".mel" extension.
}

proc markingMenuEditorRefreshScrollList(
	string $scroll,
	string $settingsOptionMenu, string $settingsRadio_N, string $settingsRadio_WCE, string $settingsRadio_S, string $settingsCheck, 
	string $settingsTabLayout, int $zeroBasedIndexOfItemToSelect
) {
	// Clear the "Settings"
	//
	int $tabForNoSettings = 3;
	optionMenu -e -select $tabForNoSettings $settingsOptionMenu;
	tabLayout -e -selectTabIndex $tabForNoSettings $settingsTabLayout;
	radioButtonGrp -e -select 0 $settingsRadio_N;
	radioButtonGrp -e -select 0 $settingsRadio_WCE;
	radioButtonGrp -e -select 0 $settingsRadio_S;
	checkBoxGrp -e -v1 false $settingsCheck;
	checkBoxGrp -e -v2 false $settingsCheck;
	checkBoxGrp -e -v3 false $settingsCheck;

	if (!`optionVar -exists markingMenuEditorAnnotations`) {
		// There is no list of Marking Menus.
		textScrollList -e -removeAll $scroll;
		return;
	}

	string $annotationArray[] = `optionVar -q markingMenuEditorAnnotations`;
	int $isNamedCmdArray[] = `optionVar -q markingMenuEditorIsNamedCommandFlags`;

	// Compute the widths of the columns in the scrolled list.
	//
	int $maxWidthCol1 = 0;
	int $j;
	for ($j = 0; $j < size($annotationArray); ++$j) {
		if (size($annotationArray[$j]) > $maxWidthCol1)
			$maxWidthCol1 = size($annotationArray[$j]);
	}

	int $k;
	string $str;

	// textScrollList -e -visible false $scroll;
	textScrollList -e -removeAll $scroll;	

	for ($j = 0; $j < size($annotationArray); ++$j) {
		$str = $annotationArray[$j];

		for ($k = ($maxWidthCol1 + 3 - size($annotationArray[$j])); $k > 0; --$k)   // append spaces
			$str += " ";
		
		if ($isNamedCmdArray[$j]) {
			$str += "Accessible in Hotkey Editor";
		}
		else {
			string $hotBoxInfo[] = markingMenuEditorGenerateHotBoxInfo($annotationArray[$j]);

			if ($hotBoxInfo[0] != "") {
				$str += "Hotbox";
				switch ($hotBoxInfo[0]) {
					case "N" : $str += " North    ";  break;
					case "S" : $str += " South    ";  break;
					case "E" : $str += " East     ";   break;
					case "W" : $str += " West     ";   break;
					case "C" : $str += " Center   "; break;
					default :  break;
				}

				int $isLeft = 0, $isMiddle = 0, $isRight = 0;
				if ($hotBoxInfo[1] == "true")
					$isLeft = 1;
				if ($hotBoxInfo[2] == "true")
					$isMiddle = 1;
				if ($hotBoxInfo[3] == "true")
					$isRight = 1;

				if ($isLeft) {
					$str += "Left";
					if ($isMiddle || $isRight)
						$str += "/";
					else $str += " ";
				}
				else $str += "     ";

				if ($isMiddle) {
					$str += "Middle";
					if ($isRight)
						$str += "/";
					else $str += " ";
				}
				else $str += "       ";

				if ($isRight)
					$str += "Right";
				else $str += "     ";

				$str += " Mouse Button";
			}
		}
		textScrollList -e -append $str $scroll;
	}

	if ($zeroBasedIndexOfItemToSelect >= 0 && size($annotationArray) > 0) {
		if ($zeroBasedIndexOfItemToSelect < size($annotationArray))
			textScrollList -e -selectIndexedItem (1 + $zeroBasedIndexOfItemToSelect) $scroll;
		else
			textScrollList -e -selectIndexedItem (size($annotationArray)) $scroll;

		markingMenuEditorUpdateMappingInfo($scroll, $settingsOptionMenu, $settingsRadio_N, $settingsRadio_WCE, $settingsRadio_S, $settingsCheck, $settingsTabLayout);
	}
	else
		textScrollList -e -deselectAll $scroll;

	// textScrollList -e -visible true $scroll;
}

proc string markingMenuEditor_generatePressCommandStringForExportedMM(
	string $filename,
	int $displayAsMM
) {
//	string $fullName;

	//	Fix for bug #116118.  Do not use hardcode path names for marking
	//	menu scripts.
	//
//	$fullName = `internalVar -userPrefDir` + $filename;
//	if (!`exists $fullName`)
//		$fullName = $filename;

	return (
		"if (`popupMenu -exists tempMM`) { deleteUI tempMM; }\n"
		+ "popupMenu -button 1 -ctl false -alt false "
		+ "-allowOptionBoxes true -parent viewPanes -mm " + $displayAsMM + " tempMM;\n"
		+ "source \"" + $filename + "\";"
	);
}

proc string markingMenuEditor_generateReleaseCommandStringForExportedMM() {

	return "if (`popupMenu -exists tempMM`) { deleteUI tempMM; }";
}

global proc markingMenuEditorSaveChanges(
	int $isEdit, string $oldAnnotation,
	string $scroll, string $settingsControl1, 			
        string $settingsControl2, string $settingsControl3, string $settingsControl4,  // These are the Hotbox region radio-button controls
        string $settingsControl5, string $settingsControl6,
	string $windowName, string $theMenu, string $annField,
	string $markingMenuEditorWindowPrefix
) {
	// Retrieve the array of annotations.
	// Also determine the index of the menu.
	//
	string $annotationArray[];
	int $indexOfMenu = -1;
	int $j;
	if (`optionVar -exists markingMenuEditorAnnotations`) {
		$annotationArray = `optionVar -q markingMenuEditorAnnotations`;
		if ($isEdit) {
			for ($j = 0; $j < size($annotationArray); ++$j) {
				if ($oldAnnotation == $annotationArray[$j]) {
					$indexOfMenu = $j;
					break;
				}
			}
		}
	}

	// To make it easy to generate filenames from the annotation,
	// we disallow spaces in the annotation, as well as all but
	// the most standard characters.
	//
	// A note about regular expressions: [^abc...] will match with
	// the first character that is not in the set { 'a', 'b', 'c', ... }.
	// See "man ed" for more info on regular expression syntax.
	//
	string $annotation = `textFieldGrp -q -tx $annField`;
	if ($annotation == "") {
		confirmDialog -title "Alert"
			-button "OK"
			-parent "markingMenuEditorWnd"
			-defaultButton "OK"
			-message "       Please enter a Menu Name.       ";
		return;
	}
	string $regularExpression = "[^0-9a-zA-Z_-]";
	$match = match( $regularExpression, $annotation );
	if ($match != "") {
		string $msg;
		if (match( " ", $annotation) != "")
			$msg = "    The Menu Name cannot contain spaces. Please use    \n    underscores (like_this) or intercaps (LikeThis).    ";
		else
			$msg = "       Menu Name contains illegal characters.  Please enter another.       ";

		confirmDialog -title "Alert"
			-button "OK"
			-parent "markingMenuEditorWnd"
			-defaultButton "OK"
			-message $msg;
		return;
	}

	// Check if the annotation is unique.
	//
	if (size($annotationArray) > 0) {
		for ($j = 0; $j < size($annotationArray); ++$j) {
			if (!$isEdit || $j != $indexOfMenu) {
				if ($annotationArray[$j] == $annotation) {
					confirmDialog -title "Alert"
						-button "OK"
						-parent "markingMenuEditorWnd"
						-defaultButton "OK"
						-message "       Menu Name is not unique! Please select another.       ";
					return;
				}
			}
		}
	}

	if ($isEdit) {

		// Check if the menu was exported to the hotkey editor.
		//
		int $isNamedCmdArray[] = `optionVar -q markingMenuEditorIsNamedCommandFlags`;
		if ($isNamedCmdArray[$indexOfMenu]) {

			// The menu *was* exported to the hotkey editor.
			// Check if the annotation of the menu has changed.
			//
			if ($annotationArray[$indexOfMenu] != $annotation) {

				// The annotation has changed.
				// Tell the hotkey editor to rename the exported menu.
				//
				if (!`exists hotkeyEditor_renameMarkingMenu`)
					source hotkeyEditor;
				if (`exists hotkeyEditor_renameMarkingMenu`) {

					int $success = hotkeyEditor_renameMarkingMenu(
						$annotationArray[$indexOfMenu],               // old annotion
						$annotation,                                  // new annotation
						markingMenuEditor_generatePressCommandStringForExportedMM(generateMarkingMenuEditorFilenameFromAnnotation($annotation),`popupMenu -q -mm $theMenu`),    // new press command
						markingMenuEditor_generateReleaseCommandStringForExportedMM()   // new release command
					);
					if (! $success) {

						// The hotkey editor was unable to rename the exported menu
						// (probably because of a naming conflict).
						// We must handle the failure.
						//
						confirmDialog -title "Alert"
							-button "OK"
							-parent "markingMenuEditorWnd"
							-defaultButton "OK"
							-message "       The entered menu name is not acceptable.       ";
						return;
					}
				}
				else {
					warning "Cannot find definition of hotkeyEditor_renameMarkingMenu()";
				}
			}
		}
	}

	// Construct new filename.
	//
	string $fileName = generateMarkingMenuEditorFilenameFromAnnotation($annotation);

	// Retrieve previous filename.
	//
	string $filenameArray[];
	string $oldFileName;
	if ($isEdit) {
		$filenameArray = `optionVar -q markingMenuEditorFilenames`;
		$oldFileName = $filenameArray[$indexOfMenu];
	}

	// If the filename of the script for the menu has changed,
	// try to rename the old file with the new filename
	// (this way the old script won't be left lying around, and if
	// the "saveMenu" fails then the old script will not end up deleted).
	//
	if ($oldFileName != "" && $oldFileName != $fileName) {
		string $oldPathName = (`internalVar -userMarkingMenuDir` + $oldFileName + ".mel");
		string $pathName = (`internalVar -userMarkingMenuDir` + $fileName + ".mel");
		if (`file -q -exists $oldPathName`) {
			sysFile -rename $pathName $oldPathName;
		}
	}

	// Save the menu as a script.
	//
	saveMenu $theMenu $fileName;
	// Call rehash, so the new file will be found and sourced successfully
	//
	rehash;
	// Update the option vars
	//
	if ($isEdit) {

		setArrayEntryInMarkingMenuEditorFilenames($indexOfMenu, $fileName);
		setArrayEntryInMarkingMenuEditorAnnotations($indexOfMenu, $annotation);
		setArrayEntryInMarkingMenuEditorDisplayAsMMFlags($indexOfMenu, `popupMenu -q -mm $theMenu`);

		// Check if the menu is attached to the hotBox.
		//
		string $hotBoxInfo[] = markingMenuEditorGenerateHotBoxInfo($annotation);
		if ($hotBoxInfo[0] != "") {

			// The menu *is* attached to the hotBox.
			// The hotBox menus must be rebuilt
			// to reflect any changes to the edited menu.
			//
			global string $gMainWindow;
			setParent $gMainWindow;
			if (!`exists buildHotboxMenus`)
				source HotboxMenus;
			buildHotboxMenus();
			hotBox -updateMenus;
		}
	}
	else {
		optionVar
			-stringValueAppend markingMenuEditorFilenames $fileName
			-stringValueAppend markingMenuEditorAnnotations $annotation
			-intValueAppend markingMenuEditorDisplayAsMMFlags `popupMenu -q -mm $theMenu`
			-intValueAppend markingMenuEditorIsNamedCommandFlags 0;
	}

	// Update the scrolled list.
	//
	if ($isEdit)
		markingMenuEditorRefreshScrollList($scroll, $settingsControl1, $settingsControl2,
			$settingsControl3, $settingsControl4, $settingsControl5, $settingsControl6, $indexOfMenu);
	else
		markingMenuEditorRefreshScrollList($scroll, $settingsControl1, $settingsControl2,
			$settingsControl3, $settingsControl4, $settingsControl5, $settingsControl6,
			(`optionVar -arraySize markingMenuEditorFilenames` - 1) );

	// deleteUI $windowName;
}

global proc markingMenuEditorOpenEditWnd(
	int $isEdit,
	string $scroll, string $settingsControl1, string $settingsControl2, string $settingsControl3, string $settingsControl4, string $settingsControl5,
	string $settingsControl6, string $markingMenuEditorWindowPrefix
) {
	string $windowName;
	int $indexOfMenu;
	string $fileName;
	string $annotation = "";   // default value for a new menu (i.e. when $isEdit == false)
	int $isNamedCommand = false;   // default value for a new menu (i.e. when $isEdit == false)
	int $displayAsMM = true;   // default value for a new menu (i.e. when $isEdit == false)

	if ($isEdit) {
		// Retrieve the index of the menu.
		//
		int $indexArray[] = `textScrollList -q -selectIndexedItem $scroll`;
		$indexOfMenu = $indexArray[0] - 1;

		if ($indexOfMenu < 0)   // nothing is selected
			return;

		// Retrieve the filename of the script that will create the menu.
		//
		string $filenameArray[] = `optionVar -q markingMenuEditorFilenames`;
		$fileName = `internalVar -userMarkingMenuDir` + $filenameArray[$indexOfMenu];
		if (!`exists $fileName`)
			$fileName =  $filenameArray[$indexOfMenu];

		// Retreive other stuff ...
		//
		string $annotationArray[] = `optionVar -q markingMenuEditorAnnotations`;
		$annotation = $annotationArray[$indexOfMenu];
		int $displayAsMMArray[] = `optionVar -q markingMenuEditorDisplayAsMMFlags`;
		$displayAsMM = $displayAsMMArray[$indexOfMenu];

		// Check if the edit window already exists,
		// and create it if it doesn't.
		//
		$windowName = generateMarkingMenuEditWindowName($markingMenuEditorWindowPrefix,$indexOfMenu);
		if (`window -exists $windowName`) {
			showWindow $windowName;
			return;
		}
		else {
			window
			-resizeToFitChildren true
			-tlc 100 430 
			-t "Edit Marking Menu"
			$windowName;
		}
	}
	else {
		$windowName = `window
			-resizeToFitChildren true
			-tlc 100 430 
			-t "Create Marking Menu"`;
	}

	formLayout form1;
		global int $menuEditorCellWidth = 100;
		global int $menuEditorFudgeFactorDueToVerticalScrollBar = 29;
		string $theMenuEditor = `menuEditor
			-cellWidth $menuEditorCellWidth
			-w (3*$menuEditorCellWidth + $menuEditorFudgeFactorDueToVerticalScrollBar)
			-h 400
			-iconMenuCallback "createMenuEditorCellMenu"`;
		setParent ..;
		formLayout -e
			-af $theMenuEditor top 20
			-af $theMenuEditor left 20
			form1;

		string $label = `text -align left
			-l ("To create a menu item, drag commands from the Shelf\n"
			+ "or the Script Editor and drop over an icon above.\n"
			+ "To edit a menu item, click the RMB over its icon."
			)`;
		formLayout -e
			-ac $theMenuEditor "bottom" 10 $label
			-af $label left 20
			form1;

		separator zeparator;   // (for lack of a better name)
		formLayout -e
			-ac $label "bottom" 20 zeparator
			-af zeparator left 20
			-af zeparator right 20
			form1;

		// This is the "annotation" field.
		//
		string $annField;
		if(`about -mac`) { // attach the text label to the text field's left
			$annField = `textFieldGrp -l "Menu Name"
				-text $annotation
				-cw 1 85
				-cat 1 "both" 1
				-cat 2 "left" 0
				-adjustableColumn 2`;
		}
		else
		{
			 $annField = `textFieldGrp -l "Menu Name"
				-text $annotation
				-cw 1 85
				-cat 1 "left" 5
				-cat 2 "left" 0
				-adjustableColumn 2`;		
		}
			
		formLayout -e
			-ac zeparator "bottom" 20 $annField
			-af $annField left 20
			-af $annField right 20
			form1;

		string $testArea = `frameLayout
			-w 140
			-h 90
			-borderStyle "in"
			-l "Click Here to Test"
			-marginHeight 0
			-marginWidth 0`;

			text -al "center" -l "(Use LMB)";
		setParent ..;
		formLayout -e
			-ac $annField bottom 20 $testArea
			-af $testArea left 20
			form1;

		string $theMenu;
		if ($isEdit && "Unknown" != `whatIs $fileName`) {
			// Create a menu within the test area, and run a previously
			// saved script to create the contents of the menu.
			//
			$theMenu = `popupMenu
				-markingMenu $displayAsMM
				-b 1
				-allowOptionBoxes true
				-parent $testArea`;
			eval ("source \""+ $fileName + "\"");
		}
		else {
			// Must create a new, empty menu.
			$theMenu = `popupMenu
				-markingMenu $displayAsMM
				-b 1
				-allowOptionBoxes true
				-parent $testArea`;
			setParent -m ..;
		}
		menuEditor -e -topLevelMenu $theMenu $theMenuEditor;	// attach menu to menuEditor


		// The hotbox does not support Motif menus, only Marking Menus.
		// If the menu to be edited is used in the hotbox, we must disable the
		// "display as MM" checkbox, and ensure that the "display as MM" flag is set to true.
		//
		if ($isEdit) {
			string $hotBoxInfo[] = markingMenuEditorGenerateHotBoxInfo($annotation);
			if ($hotBoxInfo[0] != "") {   // The menu to be edited *is* used in the hotbox.
				if (!$displayAsMM) {   // this should never happen

					// Assertion error !  The $displayAsMM flag should have been
					// forced true when the "Apply Settings" button was pressed
					// to put the menu in the hotbox.

					// Spit out a warning.
					//
					warning "Unexpected condition in markingMenuEditorOpenEditWnd()";

					// Correct the situation.
					//
					setArrayEntryInMarkingMenuEditorDisplayAsMMFlags($indexOfMenu, true);
					$displayAsMM = true;   // Update our local copy of the array element just for safety (to keep all data in sync).
				}
			}
		}

		string $saveButton = `button
			-l "Save"
			-c ("markingMenuEditorSaveChanges(" + $isEdit + ",\"" + $annotation
			+ "\",\"" + $scroll + "\",\"" + $settingsControl1 + "\",\"" + $settingsControl2 + "\",\"" + $settingsControl3 + "\",\"" + $settingsControl4 + "\",\"" + $settingsControl5 + "\",\"" + $settingsControl6
			+ "\",\"" + $windowName + "\",\"" + $theMenu + "\",\"" + $annField
			+ "\",\"" + $markingMenuEditorWindowPrefix + "\")"
			)`;
		string $closeButton = `button -l "Close" -c ("deleteUI " + $windowName)`;
		int $divisions = `formLayout -query -numberOfDivisions form1`;
		formLayout -e
			//-ac $theMenuEditor "bottom" 20 $annField
			-ac $testArea bottom 20 $saveButton

			//-ac $saveButton top 20 $testArea
			-af $saveButton "left" 20
			-ap $saveButton "right" 10 ($divisions/2)
			-af $saveButton "bottom" 20

			-ap $closeButton "left" 10 ($divisions/2)
			-af $closeButton "right" 20
			-af $closeButton "bottom" 20
			form1;
	setParent ..;
	showWindow $windowName;
}

global proc markingMenuEditorDeleteMM(
	string $scroll,
	string $settingsControl1, string $settingsControl2, string $settingsControl3, string $settingsControl4, string $settingsControl5,
	string $settingsControl6, string $markingMenuEditorWindowPrefix
) {
	int $indexArray[] = `textScrollList -q -selectIndexedItem $scroll`;
	int $j = $indexArray[0] - 1;

	if ($j < 0)   // nothing is selected
		return;

	string $filenameArray[] = `optionVar -q markingMenuEditorFilenames`;
	string $annotationArray[] = `optionVar -q markingMenuEditorAnnotations`;
	//int $displayAsMMArray[] = `optionVar -q markingMenuEditorDisplayAsMMFlags`;
	int $isNamedCmdArray[] = `optionVar -q markingMenuEditorIsNamedCommandFlags`;

	// Check if an edit window is currently open for the item
	//
	string $windowName = generateMarkingMenuEditWindowName($markingMenuEditorWindowPrefix,$j);
	if (`window -exists $windowName`) {
		showWindow $windowName;
		confirmDialog -title "Alert"
			-button "OK"
			-parent "markingMenuEditorWnd"
			-defaultButton "OK"
			-message "       Close edit window before deleting.       ";
		return;
	}

	// This is no longer necessary, since the user can
	// "Cancel" when prompted about backing up the script.
	//
	// // Ask for confirmation.
	// //
	// string $pathName = (`internalVar -userPrefDir` + $filenameArray[$j] + ".mel");
	// if (system("test -f " + $pathName + " && echo 1 || echo 0") == "1\n") {
	//	string $response = `confirmDialog -title "Delete"
	//		-button "Yes"			
	//		-parent "markingMenuEditorWnd"
	//		-button "Cancel"
	//		-cancelButton "Cancel"
	//		-defaultButton "Cancel"
	//		-dismissString "Cancel"
	//		-messageAlign "left"
	//		-message ("The file\n\n" + $pathName + "\n\nwill be deleted.  Continue ?")`;
	//	if ($response == "Cancel")
	//		return;
	//	system ("rm " + $pathName);
	// }

	// Backup the script by appending a ".bak" to its filename.
	//
	string $pathName = (`internalVar -userMarkingMenuDir` + $filenameArray[$j] + ".mel");
	// GG: changed to portable file -q -exists
	if (`file -q -exists $pathName`) {
		string $response = `confirmDialog -title "Delete Menu"
			-button "Create Backup"
			-button "Do Not Backup"
			-button "Cancel"
			-parent "markingMenuEditorWnd"
			-cancelButton "Cancel"
			-defaultButton "Create Backup"
			-dismissString "Cancel"
			-messageAlign "left"
			-message ("The file\n\n" + $pathName + "\n\n"
				+ "will be deleted.  Would you like a backup\n"
				+ "(.bak) to be made before it is deleted ?\n\n"

				+ "Note: To restore a backed-up menu file,\n"
				+ "rename it to something of the form\n\n"
				+ markingMenuEditorFilemask() + "\n\n"
				+ "Then, the next time the Marking Menu Editor\n"
				+ "window is opened, you will be prompted for\n"
				+ "an auto-restoration of the file."
				)`;
		if ($response == "Cancel")
			return;
		if ($response == "Create Backup")
			sysFile -rename ($pathName + ".bak") $pathName;
		else
			sysFile -delete $pathName;
	}
	else {
		// There's no file to delete.  Don't bother asking for confirmation
		// from the user to delete all the data associated with the file.
		// Just get rid of the data, since it's garbage without the file anyways.
	}

	// Remove MM from hotkey editor
	//
	if ($isNamedCmdArray[$j]) {
		if (!`exists hotkeyEditor_deleteMarkingMenu`)
			source hotkeyEditor;
		if (`exists hotkeyEditor_deleteMarkingMenu`)
			hotkeyEditor_deleteMarkingMenu($annotationArray[$j]);
		else
			warning "Cannot find definition of hotkeyEditor_deleteMarkingMenu()";
	}

	optionVar -removeFromArray markingMenuEditorFilenames $j;
	optionVar -removeFromArray markingMenuEditorAnnotations $j;
	optionVar -removeFromArray markingMenuEditorDisplayAsMMFlags $j;
	optionVar -removeFromArray markingMenuEditorIsNamedCommandFlags $j;

	string $nameOfOptionVar;
	string $region[] = { "N", "S", "E", "W", "C" };
	int $r, $button;

	for ($r = 0; $r < size($region); ++$r) {
		for ($button = 1; $button <= 3; ++$button) {
			$nameOfOptionVar = generateNameOfHotBoxOptionVar($region[$r],$button);
			if (`optionVar -exists $nameOfOptionVar`)
				if (`optionVar -q $nameOfOptionVar` == $annotationArray[$j])
					optionVar -stringValue $nameOfOptionVar "";
		}
	}

	// Rebuild the hotbox menus so that the deleted
	// menu will no longer exist in the hotbox.
	// (Note that this is done *after* the optionVars have been updated).
	//
	global string $gMainWindow;
	setParent $gMainWindow;
	if (!`exists buildHotboxMenus`)
		source HotboxMenus;
	buildHotboxMenus();
	hotBox -updateMenus;

	// Update the list of menus.
	//
	markingMenuEditorRefreshScrollList($scroll, $settingsControl1, $settingsControl2, $settingsControl3, $settingsControl4, 
		$settingsControl5, $settingsControl6, $j);
}

global proc markingMenuEditorUpdateMappingInfo(
	string $scroll,
	string $settingsOptionMenu, string $settingsRadio_N, string $settingsRadio_WCE, string $settingsRadio_S, 
	string $settingsCheck, string $settingsTabLayout
) {
	int $tabForHotboxSettings = 1,
	    $tabForHotkeySettings = 2,
	    $tabForNoSettings = 3;

	int $indexArray[] = `textScrollList -q -selectIndexedItem $scroll`;
	int $j = $indexArray[0] - 1;

	if ($j < 0) {   // nothing is selected
		optionMenu -e -select $tabForNoSettings $settingsOptionMenu;
		tabLayout -e -selectTabIndex $tabForNoSettings $settingsTabLayout;
		radioButtonGrp -e -select 0 $settingsRadio_N;
		radioButtonGrp -e -select 0 $settingsRadio_WCE;
		radioButtonGrp -e -select 0 $settingsRadio_S;
		checkBoxGrp -e
			-v1 false -v2 false -v3 false
			$settingsCheck;
		return;
	}

	string $annotationArray[] = `optionVar -q markingMenuEditorAnnotations`;
	int $isNamedCmdArray[] = `optionVar -q markingMenuEditorIsNamedCommandFlags`;

	if ($isNamedCmdArray[$j]) {
		optionMenu -e -select $tabForHotkeySettings $settingsOptionMenu;
		tabLayout -e -selectTabIndex $tabForHotkeySettings $settingsTabLayout;
		radioButtonGrp -e -select 0 $settingsRadio_N;
		radioButtonGrp -e -select 0 $settingsRadio_WCE;
		radioButtonGrp -e -select 0 $settingsRadio_S;
		checkBoxGrp -e
			-v1 false -v2 false -v3 false
			$settingsCheck;
	}
	else {
		string $hotBoxInfo[] = markingMenuEditorGenerateHotBoxInfo($annotationArray[$j]);

		if ($hotBoxInfo[0] != "") {
			optionMenu -e -select $tabForHotboxSettings $settingsOptionMenu;
			tabLayout -e -selectTabIndex $tabForHotboxSettings $settingsTabLayout;

			switch ($hotBoxInfo[0]) {
				case "N" : radioButtonGrp -e -select 1 $settingsRadio_N; break;
				case "W" : radioButtonGrp -e -select 1 $settingsRadio_WCE; break;
				case "C" : radioButtonGrp -e -select 2 $settingsRadio_WCE; break;
				case "E" : radioButtonGrp -e -select 3 $settingsRadio_WCE; break;
				case "S" : radioButtonGrp -e -select 1 $settingsRadio_S; break;
				default :  radioButtonGrp -e -select 0 $settingsRadio_N;
				           radioButtonGrp -e -select 0 $settingsRadio_WCE;
				           radioButtonGrp -e -select 0 $settingsRadio_S;
					   break;
			}

			int $isLeft = 0, $isMiddle = 0, $isRight = 0;
			if ($hotBoxInfo[1] == "true")
				$isLeft = 1;
			if ($hotBoxInfo[2] == "true")
				$isMiddle = 1;
			if ($hotBoxInfo[3] == "true")
				$isRight = 1;

			checkBoxGrp -e
				-v1 $isLeft -v2 $isMiddle -v3 $isRight
				$settingsCheck;
		}
		else {
			optionMenu -e -select $tabForNoSettings $settingsOptionMenu;
			tabLayout -e -selectTabIndex $tabForNoSettings $settingsTabLayout;
			radioButtonGrp -e -select 0 $settingsRadio_N;
			radioButtonGrp -e -select 0 $settingsRadio_WCE;
			radioButtonGrp -e -select 0 $settingsRadio_S;
			checkBoxGrp -e
				-v1 false -v2 false -v3 false
				$settingsCheck;
		}
	}
}

proc markingMenuEditorScanForUnregisteredMenus(int $isUserToBePrompted) {

	// First, get an array of files matching the mask.
	//
	// print ("pwd before == " + `pwd` + "\n"); // This is for debugging; to ensure that the working directory isn't changed by the system() call.
	string $path = `internalVar -userMarkingMenuDir`;
	string $mask = markingMenuEditorFilemask();
	string $fileArray[] = `getFileList -folder $path  -fs $mask`;
	// print ("pwd after == " + `pwd` + "\n"); // This is for debugging; to ensure that the working directory isn't changed by the system() call.

	// Now scan the array of files.
	//
	string $annotationArray[] = `optionVar -q markingMenuEditorAnnotations`;
	string $unregisteredAnnotationsArray[];
	string $annotation;
	int $j, $k, $isRegistered;
	if (size($fileArray) > 0 && $fileArray[0] != "") {
		for ($j = 0; $j < size($fileArray); ++$j) {
			$annotation = generateMarkingMenuEditorAnnotationFromFilenameAndExtension($fileArray[$j]);

			// Check if the annotation is registered as a known menu.
			//
			$isRegistered = false;
			for ($k = 0; $k < size($annotationArray); ++$k)
				if ($annotationArray[$k] == $annotation) {
					$isRegistered = true;
					break;
				}

			if (!$isRegistered) {
				$unregisteredAnnotationsArray[size($unregisteredAnnotationsArray)] = $annotation;
			}
		}
	}

	// Now that we have our array of unregistered menus, prompt the user.
	//
	if (size($unregisteredAnnotationsArray) > 0) {
		if ($isUserToBePrompted) {
			string $message = "The following files were detected in your user-scripts directory:\n\n";
			for ($j = 0; $j < size($unregisteredAnnotationsArray); ++$j)
				$message += (generateMarkingMenuEditorFilenameFromAnnotation($unregisteredAnnotationsArray[$j]) + ".mel\n");
			$message +=    ("\nThese files are not registered with the Marking Menu Editor.\n"
			                + "You may now load these files into the Marking Menu list for\n"
					+ "editing.  Note that the integrity of the files will not be tested,\n"
					+ "and if they do not contain valid menus then errors could occur.\n\n"

					+ "If you don't want this dialog box to come up again, you should\n"
					+ "move the above files to another directory, or rename them so\n"
					+ "they don't match the \"" + markingMenuEditorFilemask() + "\" pattern.\n"
					);
			string $response = `confirmDialog -title "Restore Menu Files"
				-button "Load Menus"
				-parent "markingMenuEditorWnd"
				-button "Do Not Load"
				-cancelButton "Do Not Load"
				-defaultButton "Load Menus"
				-dismissString "Do Not Load"
				-messageAlign "left"
				-message $message`;
			if ($response == "Do Not Load")
				return;
		}

		// Go ahead and load 'em !
		//
		for ($j = 0; $j < size($unregisteredAnnotationsArray); ++$j)
			registerMenuWithMenuEditor(generateMarkingMenuEditorFilenameFromAnnotation($unregisteredAnnotationsArray[$j]), $unregisteredAnnotationsArray[$j]);
	}
}

global proc menuEditorWnd () {

	int $divisions;

	string $markingMenuEditorWindowPrefix = "MMEditorWnd_";

	if (!`exists generateNameOfHotBoxOptionVar` || !`exists registerMenuWithMenuEditor`)
		source menuEditorSetup;

	// Do not put anything before here that could modify the 
	// list of menus, since the scrolled will not update
	// if the Marking Menu Editor window already exists.
	//
	if (`window -exists markingMenuEditorWnd`) {
		showWindow markingMenuEditorWnd;
		return;
	}

	// This must be done *after* checking if the window already exists.
	// Remember that this call may modify the list of menus, and that
	// the scrolled list has to update apprpriately.
	//
	markingMenuEditorScanForUnregisteredMenus(true);

	waitCursor -state on;
	
	window -tlc 150 350 -h 500 -w 500
		-resizeToFitChildren true
		-title "Marking Menus"
		-iconName "Marking Menus"
		markingMenuEditorWnd;

	setUITemplate -pushTemplate NONE;

	string $form = `formLayout`;

		string $scroll = `textScrollList -font "fixedWidthFont" -allowMultiSelection false`;

		formLayout buttonForm1;
			string $editBtn = `button -l "Edit Marking Menu"`;
			string $newBtn = `button -l "Create Marking Menu"`;
			string $deleteBtn = `button -l "Delete Marking Menu"`;

			$divisions = `formLayout -query -numberOfDivisions buttonForm1`;
			formLayout -e
				-af $editBtn top 0
				-af $editBtn bottom 0
				-af $editBtn left 0
				-ap $editBtn right 5 ($divisions/3)

				-af $newBtn top 0
				-ap $newBtn left 5 ($divisions/3)
				-ap $newBtn right 5 (2*$divisions/3)

				-af $deleteBtn top 0
				-ap $deleteBtn left 5 (2*$divisions/3)
				-af $deleteBtn right 0
				buttonForm1;
		setParent ..;

		frameLayout
			-l "Settings"
			-labelAlign "center"
			-labelIndent 10
			-borderStyle "etchedIn"
			settingsFrame;

			columnLayout;
				string $settingsControl1 = `optionMenu -l " Use Marking Menu in:"`;
					menuItem -l "Hotbox";
					menuItem -l "Hotkey Editor";
					menuItem -l "(not set)";
				setParent -m ..;

				int $tabContentsHeight = 124;

				string $settingsControl6 = `tabLayout -tabsVisible false`;
					string $hotboxSettingsForm = `formLayout -w 370 -h $tabContentsHeight`;

						// These three radio-groups are arranged in their respective
						// positions (North, South, etc.) in a "compass" pattern.
						//
						// The heights are set to ensure all the controls fit on both NT and Irix
						// The widths are set on North and South because a bug (?) on NT
						// causes the label to be truncated if the height is set!
						//

						string $settingsControl2 = `radioButtonGrp -l ""
							-nrb 1
							-h 21 -w 290
							-cw2 210 80
							-label1 "North"`;

						string $settingsControl3 = `radioButtonGrp -shareCollection $settingsControl2 -l "Hotbox Region:"
							-nrb 3
							-h 21
							-cw4 130 80 80 80
							-label1 "West"
							-label2 "Center"
							-label3 "East"`;

						string $settingsControl4 = `radioButtonGrp -shareCollection $settingsControl2 -l ""
							-nrb 1
							-h 21 -w 290
							-cw2 210 80
							-label1 "South"`;

						string $settingsControl5 = `checkBoxGrp -l "Mouse Button(s):"
							-ncb 3
							-h 21
							-cw4 130 80 80 80
							-label1 "Left"
							-label2 "Middle"
							-label3 "Right"`;

						formLayout -e
							-af $settingsControl2 top 15
							-af $settingsControl2 left 0
							-ac $settingsControl3 top 2 $settingsControl2
							-af $settingsControl3 left 0
							-ac $settingsControl4 top 2 $settingsControl3
							-af $settingsControl4 left 0
							//-af $settingsControl4 right 0
							-ac $settingsControl5 top 15 $settingsControl4
							-af $settingsControl5 left 0
							// -af $settingsControl5 bottom 12
							$hotboxSettingsForm;
					setParent ..;
					string $hotkeySettingsForm = `formLayout -w 370 -h $tabContentsHeight`;
						$infoLabel = `text -l "The Marking Menu will be available\nfor editing in the Hotkey Editor."`;
						formLayout -e
							-af $infoLabel top 0
							-af $infoLabel bottom 0
							-af $infoLabel right 0
							-af $infoLabel left 0
							$hotkeySettingsForm;
					setParent ..;
					string $noSettingsForm = `formLayout -w 370 -h $tabContentsHeight`;
						$infoLabel = `text -l "No settings."`;
						formLayout -e
							-af $infoLabel top 0
							-af $infoLabel bottom 0
							-af $infoLabel right 0
							-af $infoLabel left 0
							$noSettingsForm;
					setParent ..;
				setParent ..;
			setParent ..;
		setParent ..;

		formLayout buttonForm2;
			button -l "Apply Settings"
				-c ("markingMenuEditorApplySettings(\"" + $scroll + "\",\"" + $settingsControl1 + "\",\"" + $settingsControl2 + "\",\"" + $settingsControl3 + "\",\"" + $settingsControl4 + "\",\"" + $settingsControl5 + "\",\"" + $settingsControl6 + "\",\"" + $markingMenuEditorWindowPrefix + "\")")
				applyBtn;
			button -l "Undo Settings"
				-c ("markingMenuEditorUndoSettings(\"" + $scroll + "\",\"" + $settingsControl1 + "\",\"" + $settingsControl2 + "\",\"" + $settingsControl3 + "\",\"" + $settingsControl4 + "\",\"" + $settingsControl5 + "\",\"" + $settingsControl6 + "\",\"" + $markingMenuEditorWindowPrefix + "\")")
				undoBtn;
			button -l "Restore Defaults"
				-c ("markingMenuEditorRestoreDefaultMenus(\"" + $scroll + "\",\"" + $settingsControl1 + "\",\"" + $settingsControl2 + "\",\"" + $settingsControl3 + "\",\"" + $settingsControl4 + "\",\"" + $settingsControl5 + "\",\"" + $settingsControl6 + "\",\"" + $markingMenuEditorWindowPrefix + "\")")
				restoreBtn;
			button -l "Close"
				-c "deleteUI markingMenuEditorWnd"
				closeBtn;

			$divisions = `formLayout -query -numberOfDivisions buttonForm2`;
			formLayout -e
				-af applyBtn top 0
				-af applyBtn bottom 0
				-af applyBtn left 0
				-ap applyBtn right 5 ($divisions/4)

				-af undoBtn top 0
				-ap undoBtn left 5 ($divisions/4)
				-ap undoBtn right 5 ($divisions/2)

				-af restoreBtn top 0
				-ap restoreBtn left 5 ($divisions/2)
				-ap restoreBtn right 5 (3*$divisions/4)

				-af closeBtn top 0
				-ap closeBtn left 5 (3*$divisions/4)
				-af closeBtn right 0
				buttonForm2;
		setParent ..;

		formLayout -e
			-af buttonForm2 bottom 10
			-af buttonForm2 left 10
			-af buttonForm2 right 10

			-ac settingsFrame bottom 10 buttonForm2
			-af settingsFrame left 10
			-af settingsFrame right 10

			-ac buttonForm1 bottom 10 settingsFrame
			-af buttonForm1 left 10
			-af buttonForm1 right 10

			-ac $scroll bottom 10 buttonForm1
			-af $scroll left 10
			-af $scroll right 10
			-af $scroll top 10

			$form;
	setParent ..;

	textScrollList -e
		-selectCommand ("markingMenuEditorUpdateMappingInfo(\"" + $scroll + "\",\"" + $settingsControl1 + "\",\"" + $settingsControl2 + "\",\"" + $settingsControl3 + "\",\"" + $settingsControl4 + "\",\"" + $settingsControl5 + "\",\"" + $settingsControl6 + "\")")
		-doubleClickCommand ("markingMenuEditorOpenEditWnd(1,\"" + $scroll + "\",\"" + $settingsControl1 + "\",\"" + $settingsControl2 + "\",\"" + $settingsControl3 + "\",\"" + $settingsControl4 + "\",\"" + $settingsControl5 + "\",\"" + $settingsControl6 + "\",\"" + $markingMenuEditorWindowPrefix + "\")")
		$scroll;
	button -e
		-c ("markingMenuEditorOpenEditWnd(1,\"" + $scroll + "\",\"" + $settingsControl1 + "\",\"" + $settingsControl2 + "\",\"" + $settingsControl3 + "\",\"" + $settingsControl4 + "\",\"" + $settingsControl5 + "\",\"" + $settingsControl6 + "\",\"" + $markingMenuEditorWindowPrefix + "\")")
		$editBtn;
	button -e
		-c ("markingMenuEditorOpenEditWnd(0,\"" + $scroll + "\",\"" + $settingsControl1 + "\",\"" + $settingsControl2 + "\",\"" + $settingsControl3 + "\",\"" + $settingsControl4 + "\",\"" + $settingsControl5 + "\",\"" + $settingsControl6 + "\",\"" + $markingMenuEditorWindowPrefix + "\")")
		$newBtn;
	button -e
		-c ("markingMenuEditorDeleteMM(\"" + $scroll + "\",\"" + $settingsControl1 + "\",\"" + $settingsControl2 + "\",\"" + $settingsControl3 + "\",\"" + $settingsControl4 + "\",\"" + $settingsControl5 + "\",\"" + $settingsControl6 + "\",\"" + $markingMenuEditorWindowPrefix + "\")")
		$deleteBtn;
	optionMenu -e
		-cc ("tabLayout -e -selectTabIndex `optionMenu -q -select \"" + $settingsControl1 + "\"` \"" + $settingsControl6 + "\"")
		$settingsControl1;

	markingMenuEditorRefreshScrollList($scroll, $settingsControl1, $settingsControl2, $settingsControl3, $settingsControl4, $settingsControl5, $settingsControl6, 0);

 	setUITemplate -popTemplate;
	waitCursor -state off;

	showWindow markingMenuEditorWnd;
}

// For debugging purposes only.
//
//global proc mmInv() {   // "Marking Menu Inventory"
//
//	string $filenameArray[] = `optionVar -q markingMenuEditorFilenames`;
//	string $annotationArray[] = `optionVar -q markingMenuEditorAnnotations`;
//	int $displayAsMMArray[] = `optionVar -q markingMenuEditorDisplayAsMMFlags`;
//	int $isNamedCmdArray[] = `optionVar -q markingMenuEditorIsNamedCommandFlags`;
//	int $j;
//
//	print ("\nFILES(" + size($filenameArray) + "):");
//	for ($j = 0; $j < size($filenameArray); ++$j)
//		print ($filenameArray[$j] + ", ");
//
//	print ("\nANNOS(" + size($annotationArray) + "):");
//	for ($j = 0; $j < size($annotationArray); ++$j)
//		print ($annotationArray[$j] + ", ");
//
//	print ("\nAS MM(" + size($displayAsMMArray) + "):");
//	for ($j = 0; $j < size($displayAsMMArray); ++$j)
//		print ($displayAsMMArray[$j] + ", ");
//
//	print ("\nN.CMD(" + size($isNamedCmdArray) + "):");
//	for ($j = 0; $j < size($isNamedCmdArray); ++$j)
//		print ($isNamedCmdArray[$j] + ", ");
//
//	// --------------------
//
//	string $nameOfOptionVar;
//	string $region[] = { "N", "S", "E", "W", "C" };
//	int $r;
//	for ($r = 0; $r < size($region); ++$r) {
//		print ("\nHotBox " + $region[$r] + " [");
//		for ($j = 1; $j <= 3; ++$j) {
//			$nameOfOptionVar = generateNameOfHotBoxOptionVar($region[$r],$j);
//			if (`optionVar -exists $nameOfOptionVar`)
//				print (`optionVar -q $nameOfOptionVar` + ",");
//			else
//				print "(none),";
//		}
//		print "]";
//	}
//
//	print "\n";
//}

global proc markingMenuEditorApplySettings(
	string $scroll,
	string $settingsOptionMenu, string $settingsRadio_N, string $settingsRadio_WCE, string $settingsRadio_S, string $settingsCheck, 
	string $settingsTabLayout, string $markingMenuEditorWindowPrefix
) {
	int $indexArray[] = `textScrollList -q -selectIndexedItem $scroll`;
	int $j = $indexArray[0] - 1;

	if ($j < 0)   // nothing is selected
		return;

	// Check if an edit window is currently open for the item.
	//
	string $windowName = generateMarkingMenuEditWindowName($markingMenuEditorWindowPrefix,$j);
	if (`window -exists $windowName`) {
		showWindow $windowName;
		confirmDialog -title "Alert"
			-button "OK"
			-parent "markingMenuEditorWnd"
			-defaultButton "OK"
			-message "       Close edit window before Applying new settings.       ";
		return;
	}

	string $filenameArray[] = `optionVar -q markingMenuEditorFilenames`;
	string $annotationArray[] = `optionVar -q markingMenuEditorAnnotations`;
	int $displayAsMMArray[] = `optionVar -q markingMenuEditorDisplayAsMMFlags`;
	int $isNamedCmdArray[] = `optionVar -q markingMenuEditorIsNamedCommandFlags`;

	int $tabForHotboxSettings = 1,
	    $tabForHotkeySettings = 2,
	    $tabForNoSettings = 3;

	int $hotboxMenuMustBeUpdated = false;

	// Undo previous settings related to the hotbox.
	//
	string $hotBoxInfo[] = markingMenuEditorGenerateHotBoxInfo($annotationArray[$j]);
	string $nameOfOptionVar;
	int $isLeft = 0, $isMiddle = 0, $isRight = 0;
	if ($hotBoxInfo[0] != "") {   // undo old hotbox settings
		$hotboxMenuMustBeUpdated = true;

		if ($hotBoxInfo[1] == "true")
			$isLeft = 1;
		if ($hotBoxInfo[2] == "true")
			$isMiddle = 1;
		if ($hotBoxInfo[3] == "true")
			$isRight = 1;
		if ($isLeft) {
			$nameOfOptionVar = generateNameOfHotBoxOptionVar($hotBoxInfo[0],1);
			optionVar -stringValue $nameOfOptionVar "";
		}
		if ($isMiddle) {
			$nameOfOptionVar = generateNameOfHotBoxOptionVar($hotBoxInfo[0],2);
			optionVar -stringValue $nameOfOptionVar "";
		}
		if ($isRight) {
			$nameOfOptionVar = generateNameOfHotBoxOptionVar($hotBoxInfo[0],3);
			optionVar -stringValue $nameOfOptionVar "";
		}
	}

	// Undo previous settings related to the hotkey editor.
	//
	if ($isNamedCmdArray[$j]) {
		if (`optionMenu -q -select $settingsOptionMenu` != $tabForHotkeySettings) {
			setArrayEntryInMarkingMenuEditorIsNamedCommandFlags($j,false);
			$isNamedCmdArray[$j] = false;

			if (!`exists hotkeyEditor_deleteMarkingMenu`)
				source hotkeyEditor;
			if (`exists hotkeyEditor_deleteMarkingMenu`)
				hotkeyEditor_deleteMarkingMenu($annotationArray[$j]);
			else
				warning "Cannot find definition of hotkeyEditor_deleteMarkingMenu()";
		} else {
			return;
		}
	}

	// Apply the new settings.
	//
	if (`optionMenu -q -select $settingsOptionMenu` == $tabForHotboxSettings) {
		$hotboxMenuMustBeUpdated = true;

		// The hotbox does not support Motif menus, only Marking Menus.
		// If the "display as MM" flag is set to false, we must force it to be set to true.
		//
		int $displayAsMMArray[] = `optionVar -q markingMenuEditorDisplayAsMMFlags`;
		if (! $displayAsMMArray[$j]) {
			$displayAsMMArray[$j] = true;   // Update our local copy of the array just for safety (to keep all data in sync).
			setArrayEntryInMarkingMenuEditorDisplayAsMMFlags($j, true);
		}

		string $region;		
		int $isARegionSelected = true;
		
		if(`radioButtonGrp -q -select $settingsRadio_N` == 1) {
			$region = "N";

		} else if(`radioButtonGrp -q -select $settingsRadio_S` == 1) {
			$region = "S";

		} else {
			int $radioButton = `radioButtonGrp -q -select $settingsRadio_WCE`;
			switch($radioButton) {
				case 1 : $region = "W"; break;
				case 2 : $region = "C"; break;
				case 3 : $region = "E"; break;
				default : $isARegionSelected = false; break;
			}
		}

		if ($isARegionSelected) {
			$isLeft   = `checkBoxGrp -q -v1 $settingsCheck`;
			$isMiddle = `checkBoxGrp -q -v2 $settingsCheck`;
			$isRight  = `checkBoxGrp -q -v3 $settingsCheck`;
			if ($isLeft) {
				$nameOfOptionVar = generateNameOfHotBoxOptionVar($region,1);
				optionVar -stringValue $nameOfOptionVar $annotationArray[$j];
			}
			if ($isMiddle) {
				$nameOfOptionVar = generateNameOfHotBoxOptionVar($region,2);
				optionVar -stringValue $nameOfOptionVar $annotationArray[$j];
			}
			if ($isRight) {
				$nameOfOptionVar = generateNameOfHotBoxOptionVar($region,3);
				optionVar -stringValue $nameOfOptionVar $annotationArray[$j];
			}

			if (!$isRight && !$isLeft && !$isMiddle) {
				confirmDialog -title "Alert"
					-button "OK"
					-parent "markingMenuEditorWnd"
					-defaultButton "OK"
					-message "       A mouse button must be selected.      ";
			}
		}
		else {
			confirmDialog -title "Alert"
				-button "OK"
				-parent "markingMenuEditorWnd"
				-defaultButton "OK"
				-message "       A Hotbox Region must be selected.       ";
		}
	}
	else if (`optionMenu -q -select $settingsOptionMenu` == $tabForHotkeySettings) {
		if (!`exists hotkeyEditor_createMarkingMenu`)
			source hotkeyEditor;
		if (`exists hotkeyEditor_createMarkingMenu`) {
			if (hotkeyEditor_createMarkingMenu(
				$annotationArray[$j],
				
				// press command string
				//
				markingMenuEditor_generatePressCommandStringForExportedMM($filenameArray[$j],$displayAsMMArray[$j]),

				// release comand string
				//
				markingMenuEditor_generateReleaseCommandStringForExportedMM()
			)) {
				// The Marking Menu was successfully exported to the hotkey editor.
				//
				setArrayEntryInMarkingMenuEditorIsNamedCommandFlags($j,true);
				$isNamedCmdArray[$j] = true;
			}
			else {
				// The Marking Menu was NOT successfully exported to the hotkey editor.
				//
				confirmDialog -title "Alert"
					-button "OK"
					-parent "markingMenuEditorWnd"
					-defaultButton "OK"
					-message "       Unable to apply settings.       ";
			}
		}
		else {
			warning "Cannot find definition of hotkeyEditor_deleteMarkingMenu()";
		}
	}

	// Rebuild the hotbox menus.
	//
	if ($hotboxMenuMustBeUpdated) {
		global string $gMainWindow;
		setParent $gMainWindow;
		if (!`exists buildHotboxMenus`)
			source HotboxMenus;
		buildHotboxMenus();
		hotBox -updateMenus;
	}

	markingMenuEditorRefreshScrollList($scroll, $settingsOptionMenu, $settingsRadio_N, $settingsRadio_WCE, $settingsRadio_S, 
		$settingsCheck, $settingsTabLayout, $j);
}

global proc markingMenuEditorUndoSettings(
	string $scroll,
	string $settingsOptionMenu, string $settingsRadio_N, string $settingsRadio_WCE, string $settingsRadio_S, 
	string $settingsCheck, string $settingsTabLayout, string $markingMenuEditorWindowPrefix
) {
	int $indexArray[] = `textScrollList -q -selectIndexedItem $scroll`;
	int $j = $indexArray[0] - 1;

	if ($j < 0)   // nothing is selected
		return;

	// BEGIN: "Undo"ing settings is equivalently to "Apply"ing the "not set" settings.
	//
	int $tabForNoSettings = 3;

	optionMenu -e -select $tabForNoSettings $settingsOptionMenu;
	tabLayout -e -selectTabIndex $tabForNoSettings $settingsTabLayout;

	// Turning off the radio buttons & check boxes is not necessary, but could be done.
	//
	//radioButtonGrp -e -select 0 $settingsRadio_NS;
	//radioButtonGrp -e -select 0 $settingsRadio_EWC;
	//checkBoxGrp -e -v1 false $settingsCheck;
	//checkBoxGrp -e -v2 false $settingsCheck;
	//checkBoxGrp -e -v3 false $settingsCheck;
	markingMenuEditorApplySettings($scroll, $settingsOptionMenu, $settingsRadio_N, $settingsRadio_WCE, $settingsRadio_S, $settingsCheck, $settingsTabLayout, $markingMenuEditorWindowPrefix);
	//
	// END: "Undo"ing settings is equivalently to "Apply"ing the "not set" settings.
}

global proc markingMenuEditorRestoreDefaultMenus(
	string $scroll,
	string $settingsOptionMenu, string $settingsRadio_N, string $settingsRadio_WCE, string $settingsRadio_S, 
	string $settingsCheck, string $settingsTabLayout, string $markingMenuEditorWindowPrefix
) {
	string $paStyleMenuNames[] = {"PA_Style_LMB", "PA_Style_RMB", "PA_Style_MMB"};

	// Check if any edit windows are open.  They must all be closed before restoring default menus.
	// Note that it's okay if non-edit, "new MM" windows are open.
	//
	if (areAnyMarkingMenuEditWindowsOpen($markingMenuEditorWindowPrefix)) {
		confirmDialog -title "Alert"
			-button "OK"
			-parent "markingMenuEditorWnd"
			-defaultButton "OK"
			-message "       Close all edit windows before restoring defaults.       ";
		return;
	}

	// Warn the user
	//
	string $response = `confirmDialog -title "Restore Default Menus"
		-button "Yes"
		-button "Cancel"
		-parent "markingMenuEditorWnd"
		-cancelButton "Cancel"
		-defaultButton "Cancel"
		-dismissString "Cancel"
		//-messageAlign "left"
		-message "    The Default Menus will be restored.  Continue ?    "`;

	if ($response == "Cancel")
		return;

	// Look for marking menus that have been exported to the hotkey editor,
	// and un-export them by deleting from the hotkey editor.
	//
	string $annotationArray[] = `optionVar -q markingMenuEditorAnnotations`;
	int $isNamedCmdArray[] = `optionVar -q markingMenuEditorIsNamedCommandFlags`;
	int $j;
	for ($j = size($isNamedCmdArray) - 1; $j >= 0; --$j)
		if ($isNamedCmdArray[$j]) {
			if (!`exists hotkeyEditor_deleteMarkingMenu`)
				source hotkeyEditor;
			if (`exists hotkeyEditor_deleteMarkingMenu`)
				hotkeyEditor_deleteMarkingMenu($annotationArray[$j]);
			else
				warning "Cannot find definition of hotkeyEditor_deleteMarkingMenu()";
		}

	// Clear all the optionVars.
	//
	optionVar
		-remove markingMenuEditorFilenames
		-remove markingMenuEditorAnnotations
		-remove markingMenuEditorDisplayAsMMFlags
		-remove markingMenuEditorIsNamedCommandFlags;
	string $nameOfOptionVar;
	string $region[] = { "N", "S", "E", "W", "C" };
	int $r, $button;
	for ($r = 0; $r < size($region); ++$r) {
		for ($button = 1; $button <= 3; ++$button) {
			$nameOfOptionVar = generateNameOfHotBoxOptionVar($region[$r],$button);
			optionVar -remove $nameOfOptionVar;
		}
	}

	// Restore default hotbox menus.
	// (The default menus will be automatically registered with us as they are built).
	//
	global string $gMainWindow;
	setParent $gMainWindow;
	if (!`exists buildHotboxMenus`)
		source HotboxMenus;
	buildHotboxMenus();
	hotBox -updateMenus;  // This is not necessary the first time the hotbox menus are built.


	//Reload the PA style menus
	for ($j = 0; $j < size($paStyleMenuNames); $j++) {
	   if (!isMenuRegisteredWithMenuEditor($paStyleMenuNames[$j])) {
	      registerMenuWithMenuEditor(generateMarkingMenuEditorFilenameFromAnnotation($paStyleMenuNames[$j]), 
	                                              $paStyleMenuNames[$j]);
	   }
	}
	// Reload any user-defined menus.
	//
	markingMenuEditorScanForUnregisteredMenus(false);

	// Update the list of menus.
	//
	markingMenuEditorRefreshScrollList($scroll, $settingsOptionMenu, $settingsRadio_N, $settingsRadio_WCE, $settingsRadio_S, $settingsCheck, $settingsTabLayout, 0);
}
