// $Header: /MeWin/Src/WINDOW.S 121   4/26/96 17:06 Dan $

Macro_File WINDOW;

#include WINDOWS.SH
#include WINDOW.SH
#include METOOLS.SH
#include MEW_DLGS.SH
#include MEWLIST2.SH
#include MEW_BTN.SH
#include DIALOG.SH
#include MEWHELP.SH
#include MEW.SH
#include MENUS.SH
#include MEWLIB.SH
#include COMMDLG.SH
#include PRINT.SH

#ifdef _Debug_
	#include MSGLOG.SH
#endif

#define SPLIT_MODE          Global_Int( 'SPLIT_EDGE_MODE' )
#define AUTO_ARRANGE_ICONS  (TRUE)

#define SAVEFILE_HELPLINK   "SAVE"
#define LINKWIN_HELPLINK    "LINK"
#define WINLIST_HELPLINK    "LIST"
#define WINCOPY_HELPLINK    "WINDOW COPY"
#define WINMOVE_HELPLINK    "WINDOW MOVE"

/*******************************************************************************
												MULTI-EDIT MACRO FILE

NAME: WINDOW

This file contains all of the window oriented macros.

WINMENU				- The general purpose window list (menu) routine
SELECT_WINDOW _ Takes the current window and makes it non hidden/minimized
FINDWIN				- If the current window is hidden, finds one that isn't
NEXTWIN				- Switches to the next non hidden window.
LASTWIN				- Switches to the preceding non hidden window.
ADJACENT_WIN	- Switches to an adjacent window
SCREEN_SHARE	- Routine used by ADJACENT_WIN.
SWITWIN				- The SWITCH WINDOW menu.  Uses WINMENU.
COPYBL				- Interwindow copy menu.  Uses WINMENU.
MOVEBL				- Interwindow move menu.  Uses WINMENU.
LINKWIN				- Link window menu.  Uses WINMENU.
DELWIN				- Delete window with verify.
MAKEWIN				- Creates a new window.
ZOOM					- ZOOMs a window.
SPLITWIN			- Creates a new window and splits it vertically  or horizontally
WORGANIZE			- Organizes windows by tiling, cascading or icons.
WIN_OP				- Performs various window operations.

										Copyright 1991 by American Cybernetics, Inc.
*******************************************************************************/

#DEFINE _WL_SELECT_BUTTON     1
#DEFINE _WL_CANCEL_BUTTON     2
#DEFINE _WL_CLOSEFILE_BUTTON  1003
#DEFINE _WL_HIDE_BUTTON       1004
#DEFINE _WL_UNHIDE_BUTTON     1005
#DEFINE _WL_SAVE_BUTTON       1006
#DEFINE _WL_MINIMIZE_BUTTON   1009
#DEFINE _WL_RESTORE_BUTTON    1011
#DEFINE _WL_FP_BUTTON         1013
#DEFINE _WL_PT_BUTTON         1014
#DEFINE _WL_HELP_BUTTON       1100


#define WINMENU_MAX_W         750

global {
	str g_WinMenuBufId			"!WinMenuBufId";
}


// Return_int will be -2 if a new file was loaded
void WinMenu( int WParent = Parse_Int( "/PAR=", MParm_Str ) ) {

	int main_dlg, list_hwnd,
			list_win_num, list_win_id, record_count,
			line_height, font_height, font_width, dfont,
			jx,jy,jz,
      xstyle,
      button_height,
      button_space,
      th, ell, half_line,
      Temp_Window,
      Num_Hidden            = 0,
      Num_Minimized         = 0,
      Field_Count           = 0,
      Result_Int            = 0,
      tr                    = refresh,
      Start_Win_Id          = window_id,
      Active_Win_Id         = window_id,
      Active_Win_Num        = cur_window,
      Active_Win_Line       = 1,
      Call_Fp               = 0,
      ActiveBufId           = Buffer_Id,
      Letter_First          = ( Global_Int( "@Window_List_Mode@" ) != 0 ),
      Hide_Enable           = Parse_Int( "/HE=", MParm_Str ),
      Display_Current       = Parse_Int( "/DC=", MParm_Str ),
      Display_Blocked_Only  = Parse_Int( "/DB=", MParm_Str ),
      Show_System_Windows   = Parse_Int( "/SYSTEM=", MParm_Str ),
      ShowNoLink            = Parse_Int( "/NL=", MParm_Str ),
      NoResize              = Parse_Int( "/NR=", MParm_Str ),
      NoHide                = Parse_Int( "/NH=", MParm_Str ),
			Switch_mode 					= Parse_Int( "/SW=", Mparm_Str );


	str Attr_Str[ 80 ],
			Temp_Str,
			vis_str[2048]   = "",
      Help_Str[ 40 ]  = Parse_Str('/HS=',MParm_Str),
      Title[ 132 ]    = Parse_Str('/WT=',MParm_Str);

	if ( !WParent ) {
		WParent = Frame_Handle;
	}

	Refresh = False;
	Create_Window;
	List_Win_Num = Cur_Window;
	List_Win_Id = Window_Id;

	// Build the window list
	call Build_WList;

	if ( Record_Count < 1 ) {

		str Error_Msg;

		if ( Display_Blocked_Only ) {
			Error_Msg = "No other windows with marked blocks available.";
		}
		else {
			Error_Msg = "No other windows available.";
		}
		Rm( "MEERROR^MessageBox /B=1/T=" + Title + "/M=" + Error_Msg );

		Result_Int = 0;
		goto Abort;
	}

	if( Svl( Title ) == 0 ) {
		Title = "Window List";
	}
	if( Svl( Help_Str ) == 0 ) {
		Help_Str = "WINLIST";
	}

	// Create the main dialog
	Main_Dlg = Create_MEW_Dlg( title, help_str, wparent, DLG_NOSIZE | DLG_NOCENTER );
	Get_MEW_Dlg_Metrics( main_dlg, line_height, font_height, font_width, dfont );

  xstyle        = bs_pushbutton | ws_tabstop | ws_visible;
	button_height = ((DLG_DefBtnHeight * font_height) / 8) + 1; //line_height + ( font_height / 4 );
  button_space  = button_height / 9;
  half_line     = button_height / 2;

  struct Trect  rcDlg;
  struct Tmsg   msg;

  int origin_x  = 5, origin_y = line_height + line_height;
	int select_min;
	int btn_width = font_width * 14;
	int button_x, list_x;


	if( BtnOnRight )
	{
		list_x = origin_x;
	}
	else
	{
		list_x = origin_x + btn_width + font_width + 1;
	}
	jz = list_x;


	int disp_height = font_height + 1;
	if( disp_height < 15)
	{
		disp_height = 15;
	}

  ell = 16;
	ell = (ell * disp_height) + 10;

	jy = origin_y;

  GetWindowRect (GetDesktopWindow(), &rcdlg);
  int fn_width;
  if ( UseLongnames )
  {                    // if  longnames use a wider width
    fn_width = 40;
  } else {
    fn_width = 20;
  }
  str disp_str  = "I1=/W=15/T=3I2=/W=15/T=3I3=/W=15/T=3";
	if ( !letter_first )
	{
    disp_str += "FN=/IS=1/W=" + str (fn_width) +"/T=0L=/W=15/T=0";
	}
	else
	{
    disp_str += "L=/IS=1/W=15/T=0FN=/W=" + str (fn_width) + "/T=0";
	}
  disp_str += "P=/W=255/T=0";

  int list_width_fixed  =  (15 + 15 + 15) + ((fn_width + 15) * font_width);
  int dlg_width         =  origin_x + btn_width + font_width + 1;

  int list_width_full;
  int window_max_width = rcdlg.right;
  if ( rcdlg.right > WINMENU_MAX_W)
  {
    window_max_width = WINMENU_MAX_W;
  }
  if ( (dlg_width + (70 * font_width) + list_width_fixed) > window_max_width )
  {
    list_width_full = list_width_fixed + (window_max_width - (list_width_fixed + dlg_width) - 50);
  }
  else
  {
    list_width_full = list_width_fixed + (70 * font_width);
  }

	List_hWnd = ListBoxCreate( list_win_num,          // The edit buffer/window number
										1,                    // The starting line in the buffer
									 record_count,          // The number of lines
                   list_x, jy, list_width_full, ell + button_height + 1,
									 100,                   // Ctrl id
							 		 _LB_FLAG_EXTENDEDSEL | // MNB-adding this causes 1st item to always be seleccted upon init.
							 		 _LB_FLAG_HSCROLL |
                   _LB_FLAG_INCSEARCH,
									 1,                     // Field number to use for  inc search
									 main_dlg,              // Parent window
									 disp_str               // display string
									 );

	GetClientRect(list_hwnd, &rcDlg);

	// Build the reference line
	jy = font_height;

	Create_MEW_Ctrl( "STATIC", "", ws_visible | ws_child | ss_blackframe,
			jz, jy - (font_height / 2),
      rcdlg.right - rcdlg.left,
      line_height + (font_height / 2),
			main_dlg, 2002 , app_handle, 0 );

	jz += font_width;
	if ( !NoHide ) {
		BuildMEWButton( main_dlg, MEWBTN_RT_RESNAME, "WINDOW_HIDDEN",
				ws_visible | ws_child, MEWBTN_STATICBUTTON | MEWBTN_SIZETOBITMAP,
				2001, jz, jy - 3, 0, 0 );

		jz += 18;
		Create_MEW_Ctrl( "STATIC", "Hidden", ws_visible | ws_child,
				jz, jy, font_width * 10, font_height,
				main_dlg, 2002 , app_handle, 0 );

		jz += (font_width * 8 );
	}
	BuildMEWButton( main_dlg, MEWBTN_RT_RESNAME, "WINDOW_CHANGED",
			ws_visible | ws_child, MEWBTN_STATICBUTTON | MEWBTN_SIZETOBITMAP,
			2003, jz, jy - 3, 0, 0 );
	jz += 18;
	Create_MEW_Ctrl( "STATIC", "Modified", ws_visible | ws_child,
			jz, jy, font_width * 10, font_height,
			main_dlg, 2004, app_handle, 0 );

	Jz += ( Font_Width * 11 );
	if ( !ShowNoLink ) {
		BuildMEWButton( main_dlg, MEWBTN_RT_RESNAME, "WINDOW_LINKED",
				ws_visible | ws_child, MEWBTN_STATICBUTTON | MEWBTN_SIZETOBITMAP,
				2005, jz, jy - 3, 0, 0 );
		jz += 18;
		Create_MEW_Ctrl( "STATIC", "Linked", ws_visible | ws_child,
				jz, jy, font_width * 8, font_height,
				main_dlg, 2006, app_handle, 0 );

		Jz += ( Font_Width * 9 );
	}
	BuildMEWButton( main_dlg, MEWBTN_RT_RESNAME, "WINDOW_READONLY",
			ws_visible | ws_child, MEWBTN_STATICBUTTON | MEWBTN_SIZETOBITMAP,
			2007, jz, jy - 3, 0, 0 );
	Jz += 18;
	Create_MEW_Ctrl( "STATIC", "Read-only", ws_visible | ws_child,
			jz, jy, font_width * 10, font_height,
			main_dlg, 2008 , app_handle, 0);

	jz += (font_width * 12);
	BuildMEWButton( main_dlg, MEWBTN_RT_RESNAME, "BT_FL_102_S",
			ws_visible | ws_child, MEWBTN_STATICBUTTON | MEWBTN_SIZETOBITMAP,
			2009, jz, jy - 3, 0, 0 );
	jz += 18;
	Create_MEW_Ctrl( "STATIC", "Minimized", ws_visible | ws_child,
			jz, jy, font_width * 10, font_height,
			main_dlg, 2010 , app_handle, 0 );

	if(show_system_windows)
	{
		jz += (font_width * 12);
		BuildMEWButton( main_dlg, MEWBTN_RT_RESNAME, "WINDOW_SYSTEM",
				ws_visible | ws_child, MEWBTN_STATICBUTTON | MEWBTN_SIZETOBITMAP,
				2011, jz, jy - 3, 0, 0 );
		jz += 18;
		Create_MEW_Ctrl( "STATIC", "System", ws_visible | ws_child,
				jz, jy, font_width * 8, font_height,
				main_dlg, 2012 , app_handle, 0 );
	}

		// Build the command buttons
	jy = origin_y + 5;

	if(BtnOnRight)
	{
		button_x = origin_x + rcDlg.right + 5;
	}
	else
	{
		button_x = origin_x;
	}
	jz = button_x;

	BuildMEWButton( main_dlg, MEWBTN_RT_RESNAME, "BT_WN_104",
						ws_visible | ws_child, MEWBTN_STATICBUTTON | MEWBTN_SIZETOBITMAP,
						2500, button_x + (btn_width / 2) - 13, 9, 0, 0 );


	int delete_button = Create_MEW_Ctrl( "BUTTON", "&Close File",
			xstyle | ws_tabstop, jz, jy, btn_width, button_height,
      main_dlg, _WL_CLOSEFILE_BUTTON , app_handle, 0 );

	if ( !Hide_Enable ) {
		// hide_enable actually affects more than just hiding.
		EnableWindow( Delete_Button, False );
	}

	Jy += Button_Height + Half_Line;
	int Hide_Button = Create_MEW_Ctrl( "BUTTON", "H&ide",
					xstyle | ws_tabstop, jz, jy, btn_width, button_height,
					Main_Dlg, _WL_HIDE_BUTTON , App_Handle, 0 );

	Jy += Button_Height + Button_Space;
  int Unhide_Button = Create_MEW_Ctrl( "BUTTON", "&Un-Hide",
					xstyle | ws_tabstop, jz, jy, btn_width, button_height,
          Main_Dlg, _WL_UNHIDE_BUTTON , App_Handle, 0 );

	if ( NoHide ) {
		EnableWindow( Hide_Button, False );
    EnableWindow( Unhide_Button, False );
	}

	Jy += Button_Height + Half_Line;
	int Minimize_Button = Create_MEW_Ctrl( "BUTTON", "&Minimize",
					xstyle | ws_tabstop, jz, jy, btn_width, button_height,
					Main_Dlg, _WL_MINIMIZE_BUTTON , App_Handle, 0 );

	Jy += Button_Height + Button_Space;
  int Restore_Button = Create_MEW_Ctrl( "BUTTON", "&Restore",
					xstyle | ws_tabstop, jz, jy, btn_width, button_height,
          Main_Dlg, _WL_RESTORE_BUTTON , App_Handle, 0 );

	if ( NoResize ) {
		EnableWindow( Minimize_Button, False );
    EnableWindow( Restore_Button, False );
	}

	Jy += Button_Height + Half_Line;

	int Save_Button = Create_MEW_Ctrl( "BUTTON", "&Save", xstyle | ws_tabstop,jz,jy,btn_width,button_height,
			main_dlg,_WL_SAVE_BUTTON , app_handle, 0);

  jy += button_height + button_space;
  int pt_button = Create_MEW_Ctrl( "BUTTON", "&Print", xstyle | ws_tabstop,jz,jy,btn_width,button_height,
      main_dlg,_WL_PT_BUTTON , app_handle, 0);


  jy += button_height + button_space;

  int fp_button = Create_MEW_Ctrl( "BUTTON", "&File Prompt", xstyle | ws_tabstop,jz,jy,btn_width,button_height,
      main_dlg,_WL_FP_BUTTON , app_handle, 0);

	jy += 2*(button_height + button_space);

	jy += button_height + half_line;


	jy = origin_y + rcDlg.bottom + half_line;

	jz = origin_x;
	int select_button = Create_MEW_Ctrl( "BUTTON", "Se&lect", xstyle | ws_tabstop | bs_defpushbutton,
		jz,jy,btn_width,button_height,main_dlg,_WL_SELECT_BUTTON , app_handle, 0);

	jz +=  btn_width + font_width;
  int cancel_button = Create_MEW_Ctrl( "BUTTON", "Close", xstyle | ws_tabstop,jz,jy,btn_width,
		button_height,main_dlg,_WL_CANCEL_BUTTON , app_handle, 0);

	int maxlength = 0;

	mark_pos;
	tof;
	while ( !at_eof ) {
		if ( length(parse_str("P=", get_line) ) > maxlength) {
			maxlength = length(parse_str("P=", get_line));
		}
		down;
	}
	goto_mark;
  LBSetHScroll (list_hwnd, (maxlength * font_width) + list_width_fixed + font_width);
	//SendDlgItemMessage(main_dlg, 100, LB_SETSEL, true, active_win_line - 1);


	Auto_Size_MEW_Dlg( main_dlg, 10, 10 );
	GetClientRect(main_dlg, &rcDlg);

	if(BtnOnRight)
	{
		jz = button_x;
	}
	else
	{
		jz =  rcdlg.right - btn_width - 2;
	}
	int help_button = Create_MEW_Ctrl( "BUTTON", "&Help", xstyle | ws_tabstop,jz,jy,btn_width,button_height,main_dlg,_WL_HELP_BUTTON , app_handle, 0);

	// Enable Delete key
  SendMessage( list_hwnd, WM_ML2_SETKEYWCMD, _WL_CLOSEFILE_BUTTON , 1);



	Center_MEW_Dlg( main_dlg, false );

	EnableWindow( main_dlg, TRUE );


	BringWindowToTop( main_dlg );
	goto_line(active_win_line);
	goto_col(1);
  senddlgitemmessage( main_dlg, 100, WM_ML2_SETCARET, 1, active_win_line - 1 );

	ShowWindow( main_dlg, TRUE );

	SetDefaultButton( main_dlg, _WL_SELECT_BUTTON );

	SetFocus( list_hwnd );
	update_status_line;

	int hide_button_stat = 0;
	int minimize_button_stat = 0, tint = 0, j = 0;
	int maxitems = 0;

  int downer = GetWindow( main_dlg, GW_OWNER );
	Result_Int = -1;
	while( GetMessage( &Msg, 0, 0, 0 ) && ( Result_Int == -1 ) ) {
		if (( Msg.Message == WM_MEW_DLGRETURN ) && (Msg.hWnd == downer)) {
			switch ( Msg.WParam ) {
        case _WL_FP_BUTTON :
          Call_Fp = True;

				case _WL_CANCEL_BUTTON :
				case 999 :
					Result_Int = 0;
					break;

				case 998 :
				case _WL_SELECT_BUTTON :
					Result_Int = 1;
					Active_Win_Id = Parse_Int( "ID=", Get_Line( ) );
					break;

        case _WL_CLOSEFILE_BUTTON :
					for ( J = 0; J < Record_Count; ++J ) {
						if ( LBIsItemSelected( List_Hwnd, J ) > 0 ) {
							if ( !TInt ) {
								TInt = J;
							}
							Goto_Line( J + 1 );
							Jx = Parse_Int( "ID=", Get_Line( ) );
							if( Switch_Win_Id( Jx ) ) {
                DelWin( 0, 0, 0 );
								Update_Status_Line;
								Jy = Window_Id;
								Switch_Win_Id( List_Win_Id );
								List_Win_Num = Cur_Window;
								if ( Jy != Jx ) {
									Del_Line;
									--Record_Count;
									Goto_Col( 1 );
									if ( At_Eof ) {
										Up;
									}
									SendMessage( List_Hwnd, LB_DELETESTRING, J, 0 );
									--J;
									call Redraw_List;
									Active_Win_Id = Parse_Int( "ID=", Get_Line( ) );
								}
							}
						}
					}
					if ( ( TInt + 1 ) > Record_Count ) {
						TInt = Record_Count - 1;
					}
          SendDlgItemMessage( Main_Dlg, 100, WM_ML2_SETCARET, 1,TInt );
					for ( J = 0; J < Record_Count; ++J ) {
						SendMessage( List_Hwnd, LB_SETSEL, False, J );
					}
					SendMessage( List_Hwnd, LB_SETSEL, True, TInt );
					TInt = 0;
					call Redraw_List;
					Result_Int = -1;
					break;

				case _WL_HELP_BUTTON :
					MewHelp_Context( ); //(help_str);
					Result_Int = -1;
					break;

				case _WL_SAVE_BUTTON :
					maxitems = SendDlgItemMessage(main_dlg, 100, LB_GETCOUNT, 0, 0);
					for ( j=0; j < maxitems; ++j )
					{
						if ( LBIsItemSelected(GetDlgItem(main_dlg, 100), j) ) {
							goto_line(j + 1);
							jx = parse_int("ID=", get_line );
							if(switch_win_id(jx))
							{
								RM("SAVEFILE /NP=1");
								call Rebuild_Win_Line;
							}
						}
					}
					break;

				case _WL_MINIMIZE_BUTTON :
        case _WL_RESTORE_BUTTON :
					for ( J=0; J < Record_Count; ++J ) {
						if ( LBIsItemSelected( List_hWnd, J ) > 0 ) {
							Goto_Line( J + 1 );
							Jx = Parse_Int( "ID=", Get_Line( ) );
							if ( Switch_Win_Id( Jx ) ) {
                if ( Msg.WParam == _WL_RESTORE_BUTTON ) {
									Rm( "WinOP /T=8" );
								}
								else {
									Rm( "WinOp /T=10" );
								}
								call Rebuild_Win_Line;
							}
						}
					}
					Result_Int = -1;
					break;

				case _WL_HIDE_BUTTON :
        case _WL_UNHIDE_BUTTON :
					MaxItems = SendDlgItemMessage( Main_Dlg, 100, LB_GETCOUNT, 0, 0 );
					for ( J = 0; J < MaxItems; ++J ) {
						if ( LBIsItemSelected( GetDlgItem( Main_Dlg, 100 ), J ) ) {
							Goto_Line( J + 1 );
							Jx = Parse_Int( "ID=", Get_Line( ) );
							if ( Switch_Win_Id( Jx ) ) {
								int flag = 0;
                if ( Msg.WParam == _WL_UNHIDE_BUTTON ) {
									if ( window_attr & 0x0001)
									{
										Window_Attr &= 0xFFFE;
										flag = 1;
									}
								}
								else {
									if ( !(window_attr & 0x0001))
									{
										Window_Attr |= 0x01;
										flag = 1;
									}
								}
								if ( flag)              // Setup a list of windows to update later.
								{
									if ( Parse_Int( "/" + str (window_id), vis_str ))
									{
										var_remove_str ("/" + str (window_id), vis_str);
									}
									else
									{
										vis_str = vis_str + "/" + str (window_id);
									}
								}
					 			call Rebuild_Win_Line;
							}
						}
					}
					result_int = -1;
					break;

        case _WL_PT_BUTTON :
					MaxItems = SendDlgItemMessage( Main_Dlg, 100, LB_GETCOUNT, 0, 0 );
          if ( MaxItems )
          {
            struct TPrintDlg pds;
            if ( PrintDialog (frame_handle, 0, pds) )
            {
              for ( J = 0; J < MaxItems; ++J ) {
                if ( LBIsItemSelected( GetDlgItem( Main_Dlg, 100 ), J ) ) {
                  Goto_Line( J + 1 );
                  Jx = Parse_Int( "ID=", Get_Line( ) );
                  if ( Switch_Win_Id( Jx ) ) {
                    PrintWindowRaw (frame_handle, cur_window, pds);

                    call Rebuild_Win_Line;
                  }
                }
              }
            }
          }
					result_int = -1;
					break;

				default:
					goto do_isdialog;
			}
			SetFocus(List_hwnd);
			SetDefaultButton( main_dlg, _WL_SELECT_BUTTON );

			refresh = false;
			if ( record_count < 1 ) {
        EnableWindow (GetDlgItem (main_dlg, _WL_CLOSEFILE_BUTTON), FALSE);
				EnableWindow (GetDlgItem (main_dlg, _WL_HIDE_BUTTON), FALSE);
        EnableWindow (GetDlgItem (main_dlg, _WL_UNHIDE_BUTTON), FALSE);
				EnableWindow (GetDlgItem (main_dlg, _WL_MINIMIZE_BUTTON), FALSE);
        EnableWindow (GetDlgItem (main_dlg, _WL_RESTORE_BUTTON), FALSE);
				EnableWindow (GetDlgItem (main_dlg, _WL_SAVE_BUTTON), FALSE);
				EnableWindow (GetDlgItem (main_dlg, _WL_SELECT_BUTTON), FALSE);
        EnableWindow (GetDlgItem (main_dlg, _WL_PT_BUTTON), FALSE);
			}
			else {
        EnableWindow (GetDlgItem (main_dlg, _WL_CLOSEFILE_BUTTON), TRUE);
        if ( !NoHide ) {
          EnableWindow (GetDlgItem (main_dlg, _WL_HIDE_BUTTON), TRUE);
          EnableWindow (GetDlgItem (main_dlg, _WL_UNHIDE_BUTTON), TRUE);
        }
        if ( !NoResize ) {
          EnableWindow (GetDlgItem (main_dlg, _WL_MINIMIZE_BUTTON), TRUE);
          EnableWindow (GetDlgItem (main_dlg, _WL_RESTORE_BUTTON), TRUE);
        }
				EnableWindow (GetDlgItem (main_dlg, _WL_SAVE_BUTTON), TRUE);
				EnableWindow (GetDlgItem (main_dlg, _WL_SELECT_BUTTON), TRUE);
        EnableWindow (GetDlgItem (main_dlg, _WL_PT_BUTTON), TRUE);
			}
		}
		else
		{
			do_isdialog:
			if( !IsDialogMessage( main_dlg, &msg) )
			{
					translatemessage( &msg );
					dispatchmessage( &msg );
			}
		}
	}
	Destroy_Mew_Dlg( Main_Dlg );
  while ( PeekMessage( &Msg, 0, WM_MEW_DLGRETURN, WM_MEW_DLGRETURN, PM_REMOVE ) ) {

	}

Abort:
	Switch_Win_Id( List_Win_Id );
	Delete_Window;

	Switch_Win_Id( Active_Win_Id );
	if ( Result_Int == 1 ) {
		Result_Int = Cur_Window;
		if ( switch_mode)
		{
			Refresh = Tr;
			RM('Select_Window');
			goto done;
		}
	}
	Switch_Win_Id( Start_Win_Id );
	if ( !Show_System_Windows ) {
		Rm( "FindWin" );
	}

	Refresh = Tr;
  if ( Call_Fp != 0 ) {
		Rm( "LoadFile /E=1" );
    if(return_int)
      Result_Int = -2;
  }
done:

	jx = cur_window;
	jy = 1;
	while (jy <= svl (vis_str))
	{
		jy++;
		jz = XPos( "/", vis_str, jy );
		if ( jz == 0)
		{
			jz = svl (vis_str) + 1;
		}
		Val( th, Copy (vis_str, jy, jz - jy) )
		switch_win_id ( th);
		make_window_visible ( 1);
		jy = jz;
	}
	Switch_window (jx);

	Return_Int = Result_Int;
	g_WinMenuBufId = "";
	return ( );

Reset_List:
	jx = SendMessage( list_hwnd, LB_GETCOUNT, 0, 0 );
	while(  jx < record_count )
	{
		SendMessage( list_hwnd, LB_ADDSTRING, 0, 0 );
		++jx;
	}
	while(  jx > record_count )
	{
		SendMessage( list_hwnd, LB_DELETESTRING, jx - 1, 0 );
		--jx;
	}
	sendmessage( list_hwnd, LB_SETCURSEL, c_line - 1, 0);
	ret;

Redraw_List:
	RedrawWindow( List_Hwnd, 0, 0, rdw_Invalidate );
	ret;

Rebuild_Win_Line:
	Switch_Win_Id( List_Win_Id );
	List_Win_Num = Cur_Window;
	Switch_Win_Id( Jx );
	call Build_Win_Line;
	Switch_Win_Id( List_Win_Id );
	call Redraw_List;
	Result_Int = -1;
	ret;

Build_WList:

	int Tx;
	int BufId;

	Active_Win_Line = 1;
	Switch_Win_Id( List_Win_Id );
	List_Win_Num = Cur_Window;
	Window_Attr = 0x81;
	Tof;
	Switch_Window( 1 );
	Working;
	do {
		Temp_Window = Cur_Window;
		if ( Window_Id != List_Win_Id ) {
			if ( ( ( ( Display_Current == True ) || ( Window_Id != Active_Win_ID ) ) &&
					( ( Display_Blocked_Only == False ) || ( Block_Stat != False ) ) ) &&
					( ( ( Window_Attr & 0x80 ) == 0 ) || ( Show_System_Windows ) ) ) {
				Jy = Window_Id;
				BufId = Buffer_Id;
				if ( ShowNoLink && Link_Stat ) {
					// Check for redundant members of a group of linked windows
					if ( XPos( " " + Str( Buffer_Id ) + " ", g_WinMenuBufId, 1 ) ) {
						if ( BriefMode ) {
							Rm( "BRIEF^BrSpecialWindow" );
							if ( Return_Int == FALSE ) {
								Jy = 0;
							}
						}
						else {
							Jy = 0;
						}
					}
					else {
						// set globals to keep track of linked windows
						g_WinMenuBufId += " " + Str( Buffer_Id ) + " ";
					}
				}
				if ( Jy != 0 ) {
					call Build_Win_Line;
					if ( BriefMode ) {
						if ( BufId == ActiveBufId ) {
							Active_Win_Line = C_Line;
						}
					}
					else if ( Jy == Active_Win_Id ) {
						Active_Win_Line = C_Line;
					}
					Down;
				}
			}
		}
		Switch_Window( Temp_Window + 1 );
	} while ( Cur_Window != 1 );

	Switch_Window( List_Win_Num );
	Record_Count = C_Line - 1;
	Tof;
	ret;


Build_Win_Line:
	Attr_Str = "";
	Tx = 0;
	if ( Read_Only ) {
		++Tx;
		Attr_Str = "\x7F" + "I" + Str( Tx ) + "=WINDOW_READONLY";
	}
	else if ( File_Changed ) {
		++Tx;
		Attr_Str = "\x7F" + "I" + Str( Tx ) + "=WINDOW_CHANGED";
	}
	if ( Link_Stat && !ShowNoLink ) {
		++Tx;
		Attr_Str += "\x7F" + "I" + Str( Tx ) + "=WINDOW_LINKED";
	}
	if ( Window_Attr & 0x80 ) {
		++Tx;
		Attr_Str += "\x7F" + "I" + Str( Tx ) + "=WINDOW_SYSTEM";
	}
	if ( ( Window_Attr & 0x01 ) && !NoHide ) {
		++Tx;
		Attr_Str += "\x7F" + "I" + Str( Tx ) + "=WINDOW_HIDDEN";
	}
	if ( Window_Attr & 0x40 ) { // minimized
		++Tx;
		Attr_Str += "\x7F" + "I" + Str( Tx ) + "=BT_FL_102_S";
	}
	Temp_Str = "FN=" + Truncate_Path( File_Name ) + "L=" + Window_Name +
			Attr_Str + "ATTR=" + Str( Window_Attr) + "P=" + Get_Path( File_Name ) +
			"ID=" + Str( Window_Id );
	Switch_Window( List_Win_Num );
	Put_Line( Temp_Str );
	ret;

}  // WinMenu

macro Select_Window {
/****************************Multi-Edit Macro********************************

 NAME:         Select_Window

 DESCRIPTION:  Takes the current window and makes it non-hidden and
							 non-minimized

 PARAMETERS:   /MAX=1
							 /BM=1			Do special processing for Brief style windows

 RETURNS:      Nothing

*****************************06-30-93 05:29pm*******************************/

	if ( BriefMode ) {
		if ( Parse_Int( "/BM=", MParm_Str ) ) {
			Window_Attr |= 0x01;
			Rm( "BRIEF^BrSwitchBuffer /NEWBUFF=" + Str( Window_Id ) + MParm_Str );
		}
	}

	int SavWindowAttr = Window_Attr;

	Window_Attr &= 0xFFFE;
	if ( !Window_Handle || ( SavWindowAttr & 0x01 ) ) {
		if ( Parse_Int( "/MAX=", MParm_Str ) ) {
			Make_Window_Visible( 3 );
		}
		else {
			Make_Window_Visible( 1 );
		}
	}
	if ( Window_Attr & 0x40 ) {
		Rm( "Zoom" );
	}
}  // Select_Window

void CreateNoFileWin( ) {

	if( nofile_hidden )
	{
		create_window;
		window_attr = $81;
	}
	else
	{
		rm("CREATEWINDOW");
		RM('EXTSETUP /PRE=1');
	}
}

macro FindWin trans2 {
/*******************************************************************************
																MULTI_EDIT MACRO
Name: FINDWIN

Description:  Finds the next non system/hidden window window
              also skips the error window and no-file windows.

Flags:  /B=       Finds the previous window
        /HIDDEN=  Find hidden windows
        /NM=      Don't find minimized windows

          Copyright 1995 by American Cybernetics, Inc.
*******************************************************************************/

	int Jx;
	int No_Min = Parse_Int( "/NM=", MParm_Str ),
			M = 0x81,
			Error_Win_Id = 0,
			Tr = Refresh,
			Back = Parse_Int('/B=', mparm_str);

	if ( global_int('!AutoArrangErrSrc') ) {
		error_win_id = Global_Int('~Meerr_ID');
	}

	if (parse_int("/HIDDEN=",mparm_str)) {
		m = 0x80;
	}
	if ( No_Min ) {
		M |= 0x40;
	}
	Refresh = False;

Again:
	Jx = Cur_Window;
	while ((window_handle == 0) || ((Window_Attr & m) != 0) || (window_id == error_win_id)) {
		if( window_id == error_win_id )
		{
			error_win_id = 0;
		}
		if ( back ) {
			switch_window(cur_window - 1);
		} else {
			switch_window(cur_window + 1);
		}
		if (jx == cur_window) {
			if (no_min) {
        m      = $81;
				no_min = FALSE;
				goto again;
			}

			for ( jx = 1; jx <= window_count; jx++ )
			{
				switch_window(jx);
				if(  (caps(file_name) == '?NO-FILE?') & (file_changed == FALSE)  ) {
					if((lines_in_mem == 0) && (eof_in_mem))
					{
						goto exit;
					}
				}
			}
			CreateNoFileWin();

		}
	}


EXIT:
	refresh = tr;
}

macro NextWin trans2 {
/*******************************************************************************
															 MULTI-EDIT MACRO
Name: NEXTWIN

Description:	Switch to next window

							Copyright (C) 1991-95 by American Cybernetics, Inc.
*******************************************************************************/

	if ( BriefMode && !Parse_Int( "/NB=", MParm_Str ) ) {
		Rm( "BRIEF^BrSwitchBuffer " + MParm_Str );
	}
	else {

		int SavRefresh = Refresh;
		int OldWin = Cur_Window;
		int NewWin;

		Refresh = False;

		Switch_Window( Cur_Window + 1 );
		Rm( "FindWin /NM=1" + MParm_Str );
		if ( Cur_Window == OldWin ) {
	 		Rm( "FindWin" );
		}
 //   NewWin = Cur_Window;
 //   Switch_Window( OldWin);
 //   Refresh = True;
 //   Switch_Window( NewWin );
		Refresh = SavRefresh;
	}
}  // NextWin

macro LastWin trans2 {
/*******************************************************************************
															 MULTI-EDIT MACRO
Name: LASTWIN

Description:	Switch to last window

							Copyright (C) 1991-95 by American Cybernetics, Inc.
*******************************************************************************/

	if ( BriefMode && !Parse_Int( "/NB=", MParm_Str ) ) {
		Rm( "BRIEF^BrSwitchBuffer /PREV=1" + MParm_Str );
	}
	else {

		int SavRefresh = Refresh;
		int OldWin = Cur_Window;
		int NewWin;

		Refresh = False;
		Switch_Window( Cur_Window - 1 );
		Rm( "FindWin /NM=1/B=1" + MParm_Str );
		if ( Cur_Window == OldWin ) {
	 		Rm( "FindWin /B=1" );
		}
  //  NewWin = Cur_Window;
  //   Switch_Window( OldWin);
  //  Refresh = True;
  //  Switch_Window( NewWin );
		Refresh = SavRefresh;
	}
}  // LastWin

#ifdef Windows

int Abs( int t_int ) {

	if (t_int < 0) {
		t_int = 0 - t_int;
	}
	return(t_int);
}

#define id_adj_Up				1401
#define id_adj_Down     1402
#define id_adj_Left			1403
#define id_adj_Right		1404

global {
	int g_hAdjacentDlg 	"!H_ADJACENT_DLG";
	int g_hAdjacentUp 	"!H_ADJACENT_UP";
	int g_hAdjacentDn 	"!H_ADJACENT_DN";
	int g_hAdjacentLf 	"!H_ADJACENT_LF";
	int g_hAdjacentRt 	"!H_ADJACENT_RT";
}

int Adj_Btn_Proc( int &retval, int window, message, wparam, lparam, str parms ) {
	int result = 0;
	switch (message) {
		case WM_GETDLGCODE :
			retval = DLGC_WANTARROWS;
			result = 1;
			break;

		case WM_KEYDOWN :
			switch ( WParam ) {
				case vk_up :  // up arrow
					if ( IsWindowEnabled( g_hAdjacentUp ) ) {
						PostMessage( g_hAdjacentDlg, WM_COMMAND , id_adj_Up,((BN_CLICKED) << 16) | g_hAdjacentUp);
					}
				break;
				case vk_down :  // down arrow
					if (IsWindowEnabled(g_hAdjacentDn)) {
						PostMessage(g_hAdjacentDlg, WM_COMMAND , id_adj_Down,((BN_CLICKED) << 16) | g_hAdjacentDn);
					}
				break;
				case vk_left :  // left arrow
					if (IsWindowEnabled(g_hAdjacentLf)) {
						PostMessage(g_hAdjacentDlg, WM_COMMAND , id_adj_Left,((BN_CLICKED) << 16) | g_hAdjacentLf);
					}
				break;
				case vk_right :  // right arrow
					if (IsWindowEnabled(g_hAdjacentRt)) {
						PostMessage(g_hAdjacentDlg, WM_COMMAND , id_adj_Right,((BN_CLICKED) << 16) | g_hAdjacentRt);
					}
				break;
			}
		break;
	}
	return(result);
}

int Adjacent_Hook(int &retval, int window, message, wparam, lparam, str parms ) {
	switch ( Message ) {
		case WM_Destroy :
			g_hAdjacentDlg = 0;
			g_hAdjacentUp = 0;
			g_hAdjacentDn = 0;
			g_hAdjacentLf = 0;
			g_hAdjacentRt = 0;
			break;

		case WM_COMMAND :
			switch( WParam ) {
				case DLG_WCMD_INIT :
					// this message is similar to WM_INITDIALOG
					g_hAdjacentDlg = Window;
					g_hAdjacentUp = GetDlgItem( Window, id_adj_Up );
					g_hAdjacentDn = GetDlgItem( Window, id_adj_Down );
					g_hAdjacentLf = GetDlgItem( Window, id_adj_Left );
					g_hAdjacentRt = GetDlgItem( Window, id_adj_Right );
					Subclass_With_Macro( g_hAdjacentUp, "Adj_Btn_Proc", "" );
					Subclass_With_Macro( g_hAdjacentDn, "Adj_Btn_Proc", "" );
					Subclass_With_Macro( g_hAdjacentLf, "Adj_Btn_Proc", "" );
					Subclass_With_Macro( g_hAdjacentRt, "Adj_Btn_Proc", "" );
					Subclass_With_Macro( GetDlgItem( Window, 1001 ), "Adj_Btn_Proc", "" );
					Subclass_With_Macro( GetDlgItem( Window, 1002 ), "Adj_Btn_Proc", "" );
				break;
			}
		break;
	}
	return ( DlgMessageProc( RetVal, Window, Message, WParam, LParam, Parms ) );
}

int SplitWinDlg( str Title, int Enables ) {
/******************************************************************************
															 Multi-Edit Macro
															 21-Aug-95  23:49

  Function:
  Entry   :
  Exit    :
  Globals :
  Macros  :

							 Copyright (C) 1995 by American Cybernectic, Inc.
********************************************************************( ldh )***/

	int hDlg;
	int Result;
	int DefCtrl = 1001;

	if ( Enables == 0 ) {
		Enables = 0x0F;
	}
	DlgCreate( hDlg);
	DlgAddCtrl( hDlg, DLG_BitmapBtn, "~obm_UpArrow",
			DLG_Units | 38, 1, 0, 0,
			id_adj_Up, !( Enables & 1 ), "/R=13" );

	DlgAddCtrl( hDlg, DLG_BitmapBtn, "~obm_DnArrow",
			Dlg_PosOffset, Dlg_Units | 40, 20, 20,
			id_adj_Down, !( ( Enables & 2 ) >> 1 ), "/R=14" );

	DlgAddCtrl( hDlg, DLG_BitmapBtn, "~obm_LfArrow",
			1, Dlg_Units | 20, 20, 20,
			id_adj_Left, !( ( Enables & 4 ) >> 2 ), "/R=12" );

	DlgAddCtrl( hDlg, DLG_BitmapBtn, "~obm_RGArrow",
			20, DLg_PosOffset, 20, 20,
			id_adj_Right, !( ( Enables & 8 ) >> 3 ), "/R=11" );

	DlgAddCtrl( hDlg, DLG_PushButton, "Cancel",
			Dlg_Units | 27, DLG_PosOffset, DLG_StanBtnWidth, 0,
			1001, 0, "/R=0");

	if ( Enables & 0x10 ) {
		DefCtrl = 1002;
		DlgAddCtrl( hDlg, DLG_PushButton, "&Full Screen",
				dlg_Units | 18, dlg_units | 60,
				dlg_StanBtnWidth + 4, 0,
				1002, 0, "/R=15");
	}
	Result = DlgExecute( hDlg, DefCtrl, Title, "", "/HOOK=Adjacent_Hook", 0 );
	DlgKill( hDlg );
	return ( Result );

}  // SplitWinDlg

void Adjacent_Win( ) trans2 {
/*******************************************************************************
															MULTI-EDIT MACRO
Name: Adjacent_Win

Description:	On a split window, prompts for and switches to an adjacent
							window.

									Copyright 1991 by American Cybernetics, Inc.
*******************************************************************************/

	int Active_Window = Window_Id;
	int New_Window = Window_Id;
	int TRefresh = Refresh;
	int Result = -1;

	str Direction = Parse_Str( "/DIR=", MParm_Str );

	Refresh = False;
	Rm( "Screen_Share" );
	if ( ( Return_Int & 0x7F ) != 0 ) {
		if ( Svl( Direction ) != 0 ) {
			switch ( Direction ) {
				case "RIGHT" :
					if ( Return_Int & 8 ) {
						Result = 11;
					}
					break;

				case "LEFT" :
					if ( Return_Int & 4 ) {
						Result = 12;
					}
					break;

				case "UP" :
					if ( Return_Int & 1 ) {
						Result = 13;
					}
					break;

				case "DOWN" :
					if ( Return_Int & 2 ) {
						Result = 14;
					}
					break;
			}
		}
		else {
			Result = SplitWinDlg( "Switch to Window", Return_Int );
		}
	}
	if ( Result > 0 ) {
		New_Window = Parse_Int( "/" + Str( Result - 10 ) + "=",
				Global_Str( "!Screen_Share" ) );
		Make_Message( "" );
	}
	else if ( Result ) {
		Make_Message( "No adjacent window there." );
	}
	Set_Global_Str( "!Screen_Share", "" );
	Refresh = TRefresh;
	Switch_Win_Id( New_Window );

}  // Adjacent_Win

int Win_Is_Visible( int ScreenNum ) {

	// if the window is minimized or hidden, no need to check any further
  if (( Window_Attr & 1 ) || (!window_handle)) {
    return ( 0 );
  }

  if ( IsIconic( Window_Handle ) ) {
    return ( 0 );
  }
	if ( ScreenNum ) {
		return ( True );
	}

  int ret_value = 0,
      t_win_num = cur_window,
      t_update_time = last_update_time,
      t_refresh = refresh,
      win_count,
      cur_window_area,
      intersect_area = 0
      ;

struct tRECt cur_window_rect, t_window_rect, intersect_rect;

  GetWindowRect(window_handle,&cur_window_rect);

  cur_window_area = (cur_window_rect.bottom - cur_window_rect.top) *
                    (cur_window_rect.right - cur_window_rect.left);
  refresh = false;

  for (win_count = 1; win_count <= window_count; win_count++) {
    if (win_count != t_win_num) {
      switch_window( win_count );
      if (!(window_attr & 0x81)) {
        if (last_update_time > t_update_time) {
          GetWindowRect(window_handle,&t_window_rect);
          IntersectRect(&intersect_rect, &cur_window_rect, &t_window_rect);
          intersect_area += (intersect_rect.bottom - intersect_rect.top) *
                            (intersect_rect.right - intersect_rect.left);
        }
      }
    }
  }


  if (cur_window_area > intersect_area) {
    ret_value = 1;
  } else {
    ret_value = 0;
  }

  refresh = t_refresh;

  switch_window(t_win_num);

  return ( Ret_value );

}  // Win_Is_Visible

macro Screen_Share trans2 {
/*******************************************************************************
															MULTI-EDIT MACRO
Name: SCREEN_SHARE

Description:	Determines if the current window's screen is shared by another
							window.

Returns:
							Return_Int := 0, window is not shared
								OTHERWISE:
								Bit 0 = We can switch to window above
								Bit 1 = We can switch to window below
								Bit 2 = We can switch to window left
								Bit 3 = We can switch to window right
								BIT 7 = This is the ONLY available window

									Copyright 1991 by American Cybernetics, Inc.
*******************************************************************************/

	int upw = 0, downw = 0, leftw = 0, rightw = 0,
			upt = 0, downt = 0, leftt = 0, rightt = 0,
			upl = 0, downl = 0, leftl = 0, rightl = 0,
			ups = 0, downs = 0, lefts = 0, rights = 0,
			visible_count = 0,
			sn = screen_num,
			jx = 0,
			jy,
			jz,
			tr = refresh,
			tw = cur_window,
			x1, x2, y1, y2,
//      maybe_count = 0,
			maybe_win,
			maybe_update_time,
			maybe_x1,
			maybe_x2,
			maybe_y1,
			maybe_y2,
			distance_to_caret
			;
	int OrgScreenNum = Screen_Num;

	struct trect Cur_Window_Rect;
	struct tpoint Cur_Caret_Pos;

	Return_Int = 0;
	if ( IsZoomed( Window_Handle ) ) {
		goto None;
	}
	if ( OrgScreenNum ) {
		X1 = 0;
		for ( Jx = 1; Jx <= Window_Count; ++Jx ) {
			if ( Jx != Tw ) {
				Switch_Window( Jx );
				if ( OrgScreenNum == Screen_Num ) {
					++X1;
				}
			}
		}
		Switch_Window( Tw );
		if ( X1 == 0 ) {
			Screen_Num = 0;
			OrgScreenNum = 0;
		}
	}

	GetCaretPos( &Cur_Caret_Pos );
	ClientToScreen( Window_Handle, &Cur_Caret_Pos );
	GetWindowRect( Window_Handle, &Cur_Window_Rect );
	X1 = Cur_Window_Rect.Left;
	X2 = Cur_Window_Rect.Right;
	Y1 = Cur_Window_Rect.Top;
	Y2 = Cur_Window_Rect.Bottom;

	/*
 	proposed logic:
 	example is for looking for a window to the right

 	the premise is that we will create a list of possible candidates,
 	then decide which candidate is the best choice

	STEP ONE: Find the candidates
		if the new window's right border is to the right of old window

	STEP TWO: eliminate the ones that are not currently visible
		based on coordinates and last_update_time, we can find out which
		windows are obscured by others
			get coordinates of candidate.
			create a composite set of coordinates based on all other
			windows that have last_update_time greater that the candidate

	STEP THREE: Find the one who's right border is closest to the right
	border of the old window.  If two windows are identical in this
	respect, check the caret position against the coordinates to
	determine which is better.

	*/

	// **************** RIGHT DIRECTION
	Maybe_X2 = 65535;
	Maybe_Win = 0;
	Maybe_Y1 = 65535;
	Maybe_Y2 = -65534;
	for ( Jx = 1; Jx <= Window_Count; ++Jx ) {
		if ( Jx != Tw ) {
			Switch_Window( Jx );
			if ( !( Window_Attr & 0x81 ) ) {
				if ( OrgScreenNum ) {
					if ( OrgScreenNum != Screen_Num) {
						continue;
					}
				}
				++Visible_Count;
				GetWindowRect( Window_Handle, &Cur_Window_Rect );
				if ( Cur_Window_Rect.Right > X2 ) {
          if ( ( Cur_Window_Rect.Bottom > Y1 ) && ( Cur_Window_Rect.Top < Y2 ) ) {
						if ( Win_Is_Visible( OrgScreenNum ) ) {
              if ( ( Cur_Window_Rect.Left == X2 ) ||
                	( Cur_Window_Rect.Right <= Maybe_X2 ) ) {
								if ( Cur_Window_Rect.Right == Maybe_X2 ) {
									call Get_Best_X;
								}
								else {
									Maybe_X2 = Cur_Window_Rect.Right;
									Maybe_Y1 = Cur_Window_Rect.Top;
									Maybe_Y2 = Cur_Window_Rect.Bottom;
									Maybe_Win = Window_Id;
								}
							}
						}
					}
				}
			}
		}
	}
	RightW = Maybe_Win;

	// ****************** LEFT DIRECTION
	Maybe_X1 = -65534;
	Maybe_Win = 0;
	Maybe_Y1 = 65535;
	Maybe_Y2 = -65534;
	for ( Jx = 1; Jx <= Window_Count; ++Jx ) {
		if ( Jx != Tw ) {
			Switch_Window( Jx );
			if ( !( Window_Attr & 0x81 ) ) {
				if ( OrgScreenNum ) {
					if ( OrgScreenNum != Screen_Num) {
						continue;
					}
				}
				GetWindowRect( Window_Handle, &Cur_Window_Rect );
				if ( Cur_Window_Rect.Left < X1 ) {
          if ( ( Cur_Window_Rect.Bottom > Y1 ) && ( Cur_Window_Rect.Top < Y2 ) ) {
						if ( Win_Is_Visible( OrgScreenNum ) ) {
              if ( ( Cur_Window_Rect.Right == X1 ) ||
              		( Cur_Window_Rect.Left >= Maybe_X1 ) ) {
								if ( Cur_Window_Rect.Left == Maybe_X1 ) {
									call Get_Best_X;
								}
								else {
									Maybe_X1 = Cur_Window_Rect.Left;
									Maybe_Y1 = Cur_Window_Rect.Top;
									Maybe_Y2 = Cur_Window_Rect.Bottom;
									Maybe_Win = Window_Id;
								}
							}
						}
					}
				}
			}
		}
	}
	LeftW = Maybe_Win;

	// **************** DOWN DIRECTION
	Maybe_Y2 = 65535;
	Maybe_Win = 0;
	Maybe_X1 = 65535;
	Maybe_X2 = -65534;
	for ( Jx = 1; Jx <= Window_Count; ++Jx ) {
		if ( Jx != Tw ) {
			Switch_Window( Jx );
			if ( !( Window_Attr & 0x81 ) ) {
				if ( OrgScreenNum ) {
					if ( OrgScreenNum != Screen_Num) {
						continue;
					}
				}
				GetWindowRect( Window_Handle, &Cur_Window_Rect );
				if ( Cur_Window_Rect.Bottom > Y2 ) {
          if ( ( Cur_Window_Rect.Right > X1 ) && ( Cur_Window_Rect.Left < X2 ) ) {
						if ( Win_Is_Visible( OrgScreenNum ) ) {
              if ( ( Cur_Window_Rect.Top == Y2) ||
                	( Cur_Window_Rect.Bottom <= Maybe_Y2 ) ) {
								if ( Cur_Window_Rect.Bottom == Maybe_Y2 ) {
									call Get_Best_Y;
								}
								else {
									Maybe_Y2 = Cur_Window_Rect.Bottom;
									Maybe_X1 = Cur_Window_Rect.Left;
									Maybe_X2 = Cur_Window_Rect.Right;
									Maybe_Win = Window_Id;
								}
							}
						}
					}
				}
			}
		}
	}
	DownW = Maybe_Win;

	// ****************** TOP DIRECTION
	Maybe_Y1 = -65534;
	Maybe_Win = 0;
	Maybe_X1 = 65535;
	Maybe_X2 = -65534;
	for ( Jx = 1; Jx <= Window_Count; ++Jx ) {
		if ( Jx != Tw ) {
			Switch_Window( Jx );
			if ( !( Window_Attr & 0x81 ) ) {
				if ( OrgScreenNum ) {
					if ( OrgScreenNum != Screen_Num) {
						continue;
					}
				}
				GetWindowRect( Window_Handle, &Cur_Window_Rect );
				if ( Cur_Window_Rect.Top < Y1 ) {
          if ( ( Cur_Window_Rect.Right > X1 ) && ( Cur_Window_Rect.Left < X2 ) ) {
						if ( Win_Is_Visible( OrgScreenNum ) ) {
              if ( ( Cur_Window_Rect.Bottom == Y1 ) ||
              	  ( Cur_Window_Rect.Top >= Maybe_Y1 ) ) {
								if ( Cur_Window_Rect.Top == Maybe_Y1 ) {
									call Get_Best_Y;
								}
								else {
									Maybe_Y1 = Cur_Window_Rect.Top;
									Maybe_X1 = Cur_Window_Rect.Left;
									Maybe_X2 = Cur_Window_Rect.Right;
									Maybe_Win = Window_Id;
								}
							}
						}
					}
				}
			}
		}
	}
	UpW = Maybe_Win;

None:
	Switch_Window( Tw );
	if ( UpW ) {
	 	Return_Int |= 0x01;
	}
	if ( DownW ) {
	 	Return_Int |= 0x02;
	}
	if ( LeftW ) {
	 	Return_Int |= 0x04;
	}
	if ( RightW ) {
	 	Return_Int |= 0x08;
	}
	if ( Visible_Count == 0 ) {
	 	Return_Int |= 0x80;
	}
	Set_Global_Str( "!SCREEN_SHARE", "/3=" + Str( UpW ) + "/4=" + Str( DownW ) +
			"/2=" + Str( LeftW ) + "/1=" + Str( RightW ) );
	goto Exit;


Get_Best_X:
	Distance_To_Caret = 65535;
	if ((maybe_y1 < cur_caret_pos.y) && (maybe_y2 > cur_caret_pos.y)) {
		distance_to_caret = abs(cur_caret_pos.y - maybe_y1);
		if (abs(cur_caret_pos.y - maybe_y2) < distance_to_caret) {
			distance_to_caret = abs(cur_caret_pos.y - maybe_y2);
		}
	}
	if ((cur_window_rect.top < cur_caret_pos.y) && (cur_window_rect.bottom > cur_caret_pos.y)) {
		if (abs(cur_caret_pos.y - cur_window_rect.top) < distance_to_caret) {
			distance_to_caret = abs(cur_caret_pos.y - cur_window_rect.top);
			maybe_win = window_id;
		}
		if (abs(cur_caret_pos.y - cur_window_rect.bottom) < distance_to_caret) {
			distance_to_caret = abs(cur_caret_pos.y - cur_window_rect.bottom);
			maybe_win = window_id;
		}
	}
	if ( Maybe_Win == Window_Id ) {
		Maybe_X1 = Cur_Window_Rect.Left;
		Maybe_X2 = Cur_Window_Rect.Right;
		Maybe_Y1 = Cur_Window_Rect.Top;
		Maybe_Y2 = Cur_Window_Rect.Bottom;
	}
	ret;


Get_Best_Y:
	Distance_To_Caret = 65535;
	if ((maybe_x1 < cur_caret_pos.x) && (maybe_x2 > cur_caret_pos.x)) {
		distance_to_caret = abs(cur_caret_pos.x - maybe_x1);
		if (abs(cur_caret_pos.x - maybe_x2) < distance_to_caret) {
			distance_to_caret = abs(cur_caret_pos.x - maybe_x2);
		}
	}
	if ((cur_window_rect.left < cur_caret_pos.x) && (cur_window_rect.right > cur_caret_pos.x)) {
		if (abs(cur_caret_pos.x - cur_window_rect.left) < distance_to_caret) {
			distance_to_caret = abs(cur_caret_pos.x - cur_window_rect.left);
			maybe_win = window_id;
		}
		if (abs(cur_caret_pos.x - cur_window_rect.right) < distance_to_caret) {
			distance_to_caret = abs(cur_caret_pos.x - cur_window_rect.right);
			maybe_win = window_id;
		}
	}
	if ( Maybe_Win == Window_Id ) {
		Maybe_X1 = Cur_Window_Rect.Left;
		Maybe_X2 = Cur_Window_Rect.Right;
		Maybe_Y1 = Cur_Window_Rect.Top;
		Maybe_Y2 = Cur_Window_Rect.Bottom;
	}
	ret;


Exit:
	Refresh = Tr;

}  // Screen_Share
#else

macro Adjacent_Win trans2 {
/*******************************************************************************
															MULTI-EDIT MACRO
Name: ADJACENT_WIN

Description:	On a split window, prompts for and switches to an adjacent
							window.

									Copyright 1991 by American Cybernetics, Inc.
*******************************************************************************/
	int Active_Window,New_Window,Active_Screen,Active_X1,Active_Y1,Active_X2,
					Active_Y2,T_Refresh,Common=0,T_Common=0,Ev_Count=0,T_Update_Time = 0;

	T_Refresh = Refresh;
	Refresh = False;
	Active_Window = Window_Id;
	Active_Screen = Screen_Num;
	New_Window = Active_Window;
	Active_X1 = Win_X1;
	Active_Y1 = Win_Y1;
	Active_X2 = Win_X2;
	Active_Y2 = Win_Y2;

	RM('SCREEN_SHARE');

	Put_Box(26,2, 55, 13, 0, m_b_color, 'Switch to window', true);

	if ((Return_Int & $7F) == 0) {
/* We stuck the checking of return_int from SCREEN_SHARE down here to minimize
the delay between the PUT_BOX and this message */
		RM('MEERROR^Beeps /C=1');
		Write('No adjacent windows',30,5,0,m_b_color);
		Write('to switch to!',33,6,0,m_b_color);
		Write('PRESS ANY KEY' ,34,10,0,m_b_color);
		Read_Key;
		Kill_Box;
		Goto EXIT;
	}

	if (Return_Int & 1) {
/* Enable up movement */
		++Ev_Count;
		Set_Global_Str('@WSEV#' + Str(Ev_Count), '/3D=1/T=/KC=  |30  /K1=0/K2=72/R=3/W=5/X=37/Y=4');
	}
	if (Return_Int & 2) {
/* Enable down movement */
		++Ev_Count;
		Set_Global_Str('@WSEV#' + Str(Ev_Count), '/3D=1/T=/KC=  |31  /K1=0/K2=80/R=4/W=5/X=37/Y=8');
	}
	if (Return_Int & 4) {
/* Enable left movement */
		++Ev_Count;
		Set_Global_Str('@WSEV#' + Str(Ev_Count), '/3D=1/T=/KC=  |17  /K1=0/K2=75/R=2/W=5/X=29/Y=6');
	}
	if (Return_Int & 8) {
/* Enable right movement */
		++Ev_Count;
		Set_Global_Str('@WSEV#' + Str(Ev_Count), '/3D=1/T=/KC=  |16  /K1=0/K2=77/R=1/W=5/X=44/Y=6');
	}
	++Ev_Count;
	Set_Global_Str('@WSEV#' + Str(Ev_Count), '/3D=1/T=Cancel/KC=<ESC>/K1=27/K2=1/R=0/W=11/X=35/Y=10');
	RM('USERIN^CheckEvents /M=2/G=@WSEV#/#=' + Str(Ev_Count));
	Read_Key;

	if ((key1 == 0) && (key2 == 250)) {
		RM('CheckEvents /G=@WSEV#/M=1/#=' + Str(Ev_Count));
	} else {
		RM('CheckEvents /G=@WSEV#/M=0/#=' + Str(Ev_Count));
	}
	Kill_Box;
	if (return_int != 0) {
		New_WIndow = Parse_Int('/' + Str(parse_int('/R=', return_str)) + '=',
									Global_Str('!SCREEN_SHARE'));
	}

EXIT:
	RM('USERIN^CheckEvents /M=3/G=@WSEV#/#=' + Str(Ev_Count));
	Set_Global_Str('!SCREEN_SHARE','');
	Refresh = TRUE;
	Switch_Win_Id(New_Window);
}

macro Screen_Share trans2 {
/*******************************************************************************
															MULTI-EDIT MACRO
Name: SCREEN_SHARE

Description:	Determines if the current window's screen is shared by another
							window.

Returns:
							Return_Int := 0, window is not shared
								OTHERWISE:
								Bit 0 = We can switch to window above
								Bit 1 = We can switch to window below
								Bit 2 = We can switch to window left
								Bit 3 = We can switch to window right
								BIT 7 = This is the ONLY available window

									Copyright 1991 by American Cybernetics, Inc.
*******************************************************************************/

	int upw = 0, downw = 0, leftw = 0, rightw = 0,
			upt = 0, downt = 0, leftt = 0, rightt = 0,
			upl = 0, downl = 0, leftl = 0, rightl = 0,
			ups = 0, downs = 0, lefts = 0, rights = 0,
			visible_count = 0,
			sn = screen_num,
			jx = 0,
			jy,
			tr = refresh,
			tw = cur_window,
			x1 = win_x1, x2 = win_x2, y1 = win_y1, y2 = win_y2
			;

	refresh = false;
	return_int = 0;

	for (jx = 1; jx <= window_count; jx++) {
		if (jx != tw) {
			switch_window( jx );
			if (!(window_attr & 0x81)) {
				++visible_count;
				if (((x1 == win_x2) || (x1 == (win_x2 + 1))) &&
						(win_y2 > y1) && (win_y1 < y2)) {
					call calc_y;
					if (screen_num == sn) {
						if ((jy > leftt) || (lefts != sn))
								call set_left;
					} else if (last_update_time > leftl) {
						call set_left;
					}
				} else if (((x2 == win_x1) || (x2 == (win_x1 - 1))) &&
						(win_y2 > y1) && (win_y1 < y2)) {
					call calc_y;
					if (screen_num == sn) {
						if ((jy > rightt) || (rights != sn))
								call set_right;
					} else if (last_update_time > rightl) {
						call set_right;
					}
				} else if (((y2 == win_y1) || (y2 == (win_y1 - 1))) &&
						(win_x2 > x1) && (win_x1 < x2)) {
					call calc_x;
					if (screen_num == sn) {
						if ((jy > downt) || (downs != sn))
								call set_down;
					} else if (last_update_time > downl) {
						call set_down;
					}
				} else if (((y1 == win_y2) || (y1 == (win_y2 + 1))) &&
						(win_x2 > x1) && (win_x1 < x2)) {
					call calc_x;
					if (screen_num == sn) {
						if ((jy > upt) || (ups != sn))
								call set_up;
					} else if (last_update_time > upl) {
						call set_up;
					}
				}
			}
		}
	}

	switch_window( tw );
	if (upw)
			return_int |= 0x01;
	if (downw)
			return_int |= 0x02;
	if (leftw)
			return_int |= 0x04;
	if (rightw)
			return_int |= 0x08;
	if (visible_count == 0)
			return_int |= 0x80;
	Set_Global_Str('!SCREEN_SHARE',
									'/3=' + Str(UpW) +
									'/4=' + Str(DownW) +
									'/2=' + Str(LeftW) +
									'/1=' + Str(RightW)
									);
	goto exit;

calc_y: {
	if (win_y2 <  y2) {
		if (win_y1 > y1) {
			jy = win_y2 - win_y1 + 1;
		} else {
			jy = win_y2 - y1 + 1;
		}
	} else {
		if (y1 > win_y1) {
			jy = y2 - y1 + 1;
		} else {
			jy = y2 - win_y1 + 1;
		}
	}
	ret;
}

calc_x: {
	if (win_x2 <  x2) {
		if (win_x1 > x1) {
			jy = win_x2 - win_x1 + 1;
		} else {
			jy = win_x2 - x1 + 1;
		}
	} else {
		if (x1 > win_x1) {
			jy = x2 - x1 + 1;
		} else {
			jy = x2 - win_x1 + 1;
		}
	}
	ret;
}

set_left: {
	leftt = jy;
	leftw = window_id;
	leftl = last_update_time;
	lefts = screen_num;
	ret;
}

set_right: {
	rightt = jy;
	rightw = window_id;
	rightl = last_update_time;
	rights = screen_num;
	ret;
}

set_up: {
	upt = jy;
	upw = window_id;
	upl = last_update_time;
	ups = screen_num;
	ret;
}

set_down: {
	downt = jy;
	downw = window_id;
	downl = last_update_time;
	downs = screen_num;
	ret;
}

exit:
	refresh = tr;
}
#endif

macro SwitWin trans2 {
/*******************************************************************************
															MULTI-EDIT MACRO
Name: SWITWIN

Description:	Brings up a menu of all windows for the purpose of switching
							directly to a new window without toggling through those in
							between

 Parameters:

								Copyright 1994 by American Cybernetics, Inc.
*******************************************************************************/

	if ( BriefMode ) {
		Rm( "BRIEF^BrBufferList " + MParm_Str );
	}
	else {
		Rm( "WinMenu /WT=Window List" + "/HS=" + WINLIST_HELPLINK +
				"/HE=1/DB=0/DC=1/SW=1" + MParm_Str );
		Redraw;
	}
}  // SwitWin

macro CopyBl trans2 {
/*******************************************************************************
															MULTI-EDIT MACRO
Name: COPYBL

Description:	Brings up a menu of all windows who have a block defined for
							inter-window block copying

								Copyright 1991 by American Cybernetics, Inc.
*******************************************************************************/

	RM( 'WINMENU /WT=Inter-Window Copy/HS=' + WINCOPY_HELPLINK +
			'/HE=0/DB=1/DC=0' + MParm_Str);
	Window_Attr = Window_Attr & 0xFFFE;
	if (Return_Int != 0) {
		Window_Copy(Return_Int);
		if( global_int("BlockOffAfterPaste"))
		{
			block_off;
		}
	}
}

macro MoveBl trans2 {
/*******************************************************************************
															MULTI-EDIT MACRO
Name: MOVEBL

Description:	Brings up a menu of all windows who have a block defined for
							inter-window block moving

								Copyright 1991 by American Cybernetics, Inc.
*******************************************************************************/

	RM( 'WINMENU /WT=Inter-Window Move/WH=Select window to move from and press <ENTER>, or <ESC> to abort/HS=' +
			WINMOVE_HELPLINK + '/EM=No windows with marked blocks available/HE=0/DB=1/DC=0' + MParm_Str);
	Window_Attr = Window_Attr & 0xFFFE;
	if (Return_Int != 0) {
		Window_Move(Return_Int);
		if( global_int("BlockOffAfterPaste"))
		{
			block_off;
		}
	}
}

void LinkWin trans2 {
/*******************************************************************************
															MULTI-EDIT MACRO
Name: LINKWIN

Description:	Brings up a menu of all windows for linking

Parameters:

								Copyright 1991 by American Cybernetics, Inc.
*******************************************************************************/

	int jx, mr;

	MR = Parse_Int('/Y=',MParm_Str);
	if (MR == 0) {
		MR = 2;
	}
	if (link_stat == 0) {
		if (global_str('@DEL_VERIFY_MACRO') != '') {
			rm( global_str('@DEL_VERIFY_MACRO'));
		}
		if (File_Changed) {
			RM('USERIN^CHECKFILE /H=' + LINKWIN_HELPLINK + '/Y=' + str(mr) + '/X=' +
					parse_str('/X=',mparm_str));
			if (return_int <= 0) {
				Return_Int = 0;
				GOTO Exit;
			}
		}
	}

	RM( 'WINMENU /WT=Link Window/WH=Select window to link to and press <ENTER>, or <ESC> to abort/HS=' +
			LINKWIN_HELPLINK + '/HE=0/DB=0/DC=0' + MParm_Str);
	if (Return_Int != 0) {
		Link_Window(Return_Int);
		Return_Int = 1;
		RM('SetWindowNames');
	}
	Window_Attr = Window_Attr & 0xFFFE;

	return_int = 100;
EXIT:

}

int DelWin(
			int NoDel = Parse_Int( "/NODEL=", MParm_str ),
			int MR = Parse_Int( "/Y=", MParm_Str ),
			int BC = Parse_int( "/BC=", MParm_Str )
) trans2 {
/******************************************************************************
															MULTI-EDIT MACRO
Name: DelWin

Description:	Deletes a window after checking to see if file has been saved

Parameters:
							/BC=	Number of boxes leave upon exit
							/NODEL=1  Perform all operations as if the window was
												deleted (like resizing other windows) but do not
												actually delete the window.
							/NB=1			Do not do special Brief mode processing

								Copyright 1991-95 by American Cybernetics, Inc.
******************************************************************************/

	if ( BriefMode && !NoDel && !Parse_Int( "/NB=", MParm_Str ) ) {
		Rm( "BRIEF^BrDeleteBuffer" );
	}
	else {

		int OrgWin 		 = Window_Id;
		int SavScrNum  = Screen_Num;
		int SavRefresh = Refresh;
		int NewWin 		 = 0;
		int EventFound = Event_Mode & EVENT_DELETE_WIN;
		int	Jx;

		if ( Mr == 0 ) {
			Mr = 2;
		}
		Return_Int = False;
		if ( !NoDel && ( Link_Stat == 0 ) ) {
			Rm( "USERIN^CheckFile /H=" );
			if ( Return_Int <= 0 ) {
				Return_Int = False;
				goto Exit;
			}
		}
		Return_Int = True;
		Working;
		Refresh = False;
		if ( !NoDel && ( Window_Id == Global_Int( "~MEERR_SPLIT_ID" ) ) ) {
			Jx = Window_Id;
			if ( Switch_Win_Id( Global_Int( "~MEERR_ID" ) ) ) {
				if( !File_Changed ) {
					DelWin( 0, 0, 0 );
				}
				Switch_Win_Id( Jx );
			}
		}
		if ( Cur_Window == Window_Count ) {
			Switch_Window( Cur_Window - 1 );
			NewWin = Window_Id;
			Switch_Window( Cur_Window + 1 );
		}
		else {
			Switch_Window( Cur_Window + 1 );
			NewWin = Window_Id;
			Switch_Window( Cur_Window - 1 );
		}
		if ( NoDel ) {
			Switch_Win_Id( OrgWin );
		}
		else {
			Delete_Window;
			if ( !EventFound ) {
				Switch_Win_Id( NewWin );
			}
		}
		Rm( "FindWin /NM=1" );
		Rm( "SetWindowNames" );
		New_Screen;
		if ( Auto_Arrange_Icons ) {
			Win_Icon_Arrange( );
		}
		Return_Int = NewWin;
		Refresh = SavRefresh;
	}

Exit:
	 return ( Return_Int );

}  // DelWin

void Win_Icon_Arrange( ) {
/*******************************************************************************
																MULTI_EDIT MACRO

Name: WIN_ICON_ARRANGE

Description:  Arranges window icons at the bottom of the screen.

							 (C) Copyright 1991 by American Cybernetics, Inc.
*******************************************************************************/
	SendMessage (client_handle, WM_MDIICONARRANGE, 0, 0);
	return();
}

void MakeWin trans2 {
/*******************************************************************************
															MULTI-EDIT MACRO
Name: MAKEWIN

Description:	Creates a new window after checking to see if the window limit
							has been reached

Parameters:
							/NL=1		Will not load a file or attempt a link.  Use this if you
											just want to create a window with a window name and you'll
											take care of loading a file yourself.

							/L=1		Will cause the new window to be linked to the
											original window if the file is already loaded AND
											the user has requested the file NOT be reloaded.

							/NC=1		Will bypass the creation of the window, and just prompt for
											loading a file and taking care of linking if the file is already
											loaded.

								Copyright 1991 by American Cybernetics, Inc.
*******************************************************************************/

	int  tw1, tw2, jx;

	if (Window_Count >= 100) {
		Error_Level = 1001;
		Goto Exit;
	}
	int nc = parse_int('/NC=', mparm_str);
	int nl = parse_int ('/NL=', mparm_str);

	refresh = FALSE;
	if (nc == 0) {
		tw2 = window_id;
		RM('CreateWindow');
		tw1 = cur_window;
		switch_win_id( tw2);
		refresh = true;
		switch_window( tw1 );
		tw1 = window_id;
		RM('EXTSETUP /PRE=1');
	} else {
		tw1 = window_id;
	}

	if (nl) {
		Goto NL_EXIT;
	}
Bypass_Create:
	RM('MEUTIL1^LOADFILE /X=' + Str(win_x1) + '/Y=' + str(win_y1) + '/E=' + Str(nc == 0));
	tw2 = window_id;
	if (tw2 != tw1) {
		refresh = false;
		jx = cur_window;
		if (switch_win_id( tw1 )) {
			if (caps(file_name) == '?NO-FILE?') {
				if (parse_int('/L=',mparm_str)) {
					link_window( jx );
					make_message('Window linked.');
				} else if (nc == 0) {
					delete_window;
					new_screen;
					if (switch_win_id( tw2 )) {
					}
				}
			}
		}
	}
NL_EXIT:
	RM('SetWindowNames');
Exit:
}

void Zoom( ) trans2 {
/*******************************************************************************
															 MULTI-EDIT MACRO

NAME:  ZOOM

DESCRIPTION: Replaces the ZOOM macro command.

							 (C) Copyright 1991 by American Cybernetics, Inc.
*******************************************************************************/

  int Temp = SendMessage( Client_Handle, WM_MDIGETACTIVE, 0, 0 ) ;

	if ( ( Window_Attr & 0x40 ) != 0 ) {
		if ( Temp & 0xFFFF0000 ) {
      make_window_visible (SW_MAXIMIZE);
    }
    else {
			SendMessage( Client_Handle, WM_MDIRESTORE, Window_Handle, 0 );
    }
    if ( Auto_Arrange_Icons ) {
      Win_Icon_Arrange( );
    }
	}
	else {
		if ( Temp & 0xFFFF0000 ) {
			SendMessage( Client_Handle, WM_MDIRESTORE, Window_Handle, 0 );
		}
		else {
      make_window_visible (SW_MAXIMIZE);
		}
	}
	return ( );

}  // Zoom

void Minimize( ) {
  int Temp = SendMessage( Client_Handle, WM_MDIGETACTIVE, 0, 0 ) ;
  if ( Temp & 0xFFFF0000 ) {
    SendMessage (Client_Handle, WM_SETREDRAW, 0, 0);
    int twin      = cur_window;
    int trefresh  = refresh;
    refresh = false;

    switch_window (cur_window + 1);
    Rm ('FindWin /NM=1');
    if ( twin == cur_window ) {
			SendMessage( Client_Handle, WM_MDIRESTORE, Window_Handle, 0 );
      make_window_visible (SW_MINIMIZE);
      temp =1;

    }
    else {
      switch_window (twin);
      make_window_visible (SW_MINIMIZE);
   //   switch_window (cur_window + 1);
      Rm ('FindWin /NM=1');
      make_window_visible (SW_MAXIMIZE);
      temp =0;
    }
    Refresh = tRefresh;
    SendMessage (Client_Handle, WM_SETREDRAW, 1, 0);
		RedrawWindow (window_handle, 0, 0, RDW_ALLCHILDREN | RDW_INVALIDATE);

    if ( temp) {
			RedrawWindow (frame_handle, 0, 0, RDW_ALLCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW);
    }
  }

  else {
    make_window_visible (SW_MINIMIZE);
    Rm ('FindWin /NM=1');
//    RM ('Nextwin');
  }
  if ( Auto_Arrange_Icons ) {
    Win_Icon_Arrange( );
  }
	return ( );

}  // Minimize

void Maximize( ) {

  make_window_visible (SW_MAXIMIZE);
	return ( );

}  // Maximize

int WinViewCount( ) {
/****************** Multi-Edit INTEGER Macro Function ***********************

 NAME:         WinViewCount()

 DESCRIPTION:  Returns the total number of windows that are NOT defined with
							 the $80 attribute.

*****************************07-19-93 10:25am*******************************/
	int r = refresh, tw = cur_window,
			count = 0;
	refresh = false;

	do
	{
		switch_window( cur_window + 1 );
		if(!(window_attr & $80))
			++count;
	} while ( cur_window != tw );

	refresh = r;
	return(count);
}

void SplitWin(
			int Split_Size 			= Parse_Int( "/LN#=", MParm_Str ),
			str Direction[ 10 ] = Caps( Parse_Str( "/DIR=", MParm_Str ) ),
			int Win2_Id 				= Parse_Int( "/ID=", MParm_Str )
) trans2 {
/*******************************************************************************
																MULTI_EDIT MACRO

Name: SPLITWIN

Description: Splits a window horizontally or vertically.

Parameters:  Prompts the user if no parameters are passed.

						/DIR=str	Direction (str is NOT case sensitive)
									str = Up
									str = Down
									str = Left
									str = Right
						/LN#=n   Number of lines (or columns) in the new window.
									 0 means use half of the original window.
						/ID=     ID of window to split with, bypasses user in put of file
										 name to split with.
						/WL=1 Show window list.
							 (C) Copyright 1991 by American Cybernetics, Inc.
*******************************************************************************/

	int cur_window_width,
			cur_window_height,
			cur_window_left,
			cur_window_top,
			t_int,
			new_window_left,
			new_window_top,
			window1_left,
			window1_top,
			window1_width,
			window1_height,
			window2_left,
			window2_top,
			window2_width,
			window2_height,
			line_height, font_height, font_width, dfont,
			cur_screen,
			x_offset,
			y_offset,
			tw1,
			tw2,
			j1,
			old_win = cur_window
			;

	str DirStr = "RIGHTLEFT UP   DOWN ";

	struct TRECT cur_window_rect, client_rect;

	if ( Svl( Direction ) == 0 ) {
		if ( Return_Int = SplitWinDlg( "Split Window", 0 ) ) {
			Direction = Remove_Space( Copy( DirStr, ( ( Return_Int - 11 ) * 5 ) + 1, 5 ) );
		}
	}
	if ( Svl( Direction ) != 0 ) {
		if ( IsZoomed( Window_Handle ) ) {
	//  messagebeep(-1);
			SendMessage( Client_Handle, WM_MDIRESTORE, Window_Handle, 0 );
			GetClientRect( Client_Handle, &Client_Rect );
			cur_window_width = client_rect.right - client_rect.left;
			cur_window_height = client_rect.bottom - client_rect.top;
			cur_window_left = client_rect.left;
			cur_window_top = client_rect.top;
		}
		else {
			GetWindowRect( Window_Handle, &Cur_Window_Rect );
			Cur_Window_Width = Cur_Window_Rect.Right - Cur_Window_Rect.Left;
			Cur_Window_Height = Cur_Window_Rect.Bottom - Cur_Window_Rect.Top;

			// convert coordinates for MoveWindow function
			ScreenToClient( Client_Handle, &Cur_Window_Rect );
			Cur_Window_Left = Cur_Window_Rect.Left;
			Cur_Window_Top = Cur_Window_Rect.Top;
			GetClientRect(window_handle,&client_rect);
		}
		if ( Split_Size > 0 ) {
			if ( ( Direction == "LEFT" ) || ( Direction == "RIGHT" ) ) {
				++split_Size;  // this is to sort of compensate for the space at the left of the window
			}
			int TFont;
			int Xdc;

			struct TTextMetric xTextMetrics;

      // fonts_get(0,tfont,xdc,xdc);
      Get_Window_Font_Handle (0, tfont, xdc, xdc, xdc);

			Xdc = GetDc( window_handle );
			SelectObject( xdc, tfont );
			GetTextMetrics(xDC, &xTextMetrics);
			ReleaseDC(window_handle, xDC);
//      font_height = xTextMetrics.tmHeight;
//      font_width = xTextMetrics.tmAveCharWidth;



			y_offset = ((cur_window_height - (client_rect.bottom - client_rect.top)) +
									(xTextMetrics.tmHeight * split_size));

			x_offset = ((cur_window_width - (client_rect.right - client_rect.left)) +
									(xTextMetrics.tmAveCharWidth * split_size));

			switch ( Direction ) {
				case "UP" :
					window1_left = cur_window_left;
					window1_top = cur_window_top + y_offset;
					window1_width = cur_window_width;
					window1_height = cur_window_height - y_offset;

					window2_left = cur_window_left;
					window2_top = cur_window_top;
					window2_width = cur_window_width;
					window2_height = y_offset;
					break;

				case "DOWN" :
					window1_left = cur_window_left;
					window1_top = cur_window_top;
					window1_width = cur_window_width;
					window1_height = cur_window_height - y_offset;

					window2_left = cur_window_left;
					window2_top = cur_window_top + cur_window_height - y_offset;
					window2_width = cur_window_width;
					window2_height = y_offset;
					break;

				case "LEFT" :
					window1_left = cur_window_left + x_offset;
					window1_top = cur_window_top;
					window1_width = cur_window_width - x_offset;
					window1_height = cur_window_height;

					window2_left = cur_window_left;
					window2_top = cur_window_top;
					window2_width = x_offset;
					window2_height = cur_window_height;
					break;

				case "RIGHT" :
					window1_left = cur_window_left;
					window1_top = cur_window_top;
					window1_width = cur_window_width - x_offset;
					window1_height = cur_window_height;

					window2_left = cur_window_left + cur_window_width - x_offset;
					window2_top = cur_window_top;
					window2_width = x_offset;
					window2_height = cur_window_height;
					break;

				default:
					goto Exit;
					break;
			}
		}
		else {
			switch ( Direction ) {
				case "UP" :
					window1_left = cur_window_left;
					window1_top = cur_window_top + (cur_window_height / 2);
					window1_width = cur_window_width;
          window1_height = cur_window_height / 2 + (cur_window_height % 2);

					window2_left = cur_window_left;
					window2_top = cur_window_top;
					window2_width = cur_window_width;
					window2_height = cur_window_height / 2;
					break;

				case "DOWN" :
					window1_left = cur_window_left;
					window1_top = cur_window_top;
					window1_width = cur_window_width;
					window1_height = cur_window_height / 2;

					window2_left = cur_window_left;
					window2_top = cur_window_top + (cur_window_height / 2);
					window2_width = cur_window_width;
          window2_height = cur_window_height / 2 + (cur_window_height % 2);
					break;

				case "LEFT" :
					window1_left = cur_window_left + (cur_window_width / 2);
					window1_top = cur_window_top;
          window1_width = cur_window_width / 2 + (cur_window_width % 2);
					window1_height = cur_window_height;

					window2_left = cur_window_left;
					window2_top = cur_window_top;
					window2_width = cur_window_width / 2;
					window2_height = cur_window_height;
					break;

				case "RIGHT" :
					window1_left = cur_window_left;
					window1_top = cur_window_top;
					window1_width = cur_window_width / 2;
					window1_height = cur_window_height;

					window2_left = cur_window_left + (cur_window_width / 2);
					window2_top = cur_window_top;
          window2_width = cur_window_width / 2 + (cur_window_width % 2);
					window2_height = cur_window_height;
					break;

				default:
					goto Exit;
					break;
			}
		}
 /*		if ( ( window1_width < GetSystemMetrics( SM_CXMIN ) ) ||
				( window2_width < GetSystemMetrics( SM_CXMIN ) ) ||
				( window1_height < GetSystemMetrics( SM_CYMIN ) ) ||
				( window2_height < GetSystemMetrics( SM_CYMIN ) ) ) {
			Rm( "MESSAGEBOX /B=1/T=Split Window/M=Window too small to split" );
		}
		else
		{ */
			if ( Screen_Num == 0 ) {
				Screen_Num = Global_Int( "@SCREEN_COUNT" ) + 1;
				if ( Screen_Num <= 1 ) {
					Screen_Num = 2;
				}
				Set_Global_Int( "@SCREEN_COUNT", Screen_Num );
			}
			Cur_Screen = Screen_Num;

			MoveWindow( window_handle, window1_left, window1_top, window1_width,
					window1_height, true );

			if ( Win2_Id ) {
				Switch_Win_Id( Win2_Id );
			}
			else {
        Rm( "CreateWindow" );
			}
			MoveWindow( Window_Handle, Window2_Left, Window2_Top, Window2_Width,
					Window2_Height, True );
			Screen_Num = Cur_Screen;

			if ( Win2_Id ) {
				return ( );
			}

			tw1 = window_id;
			return_int = 0;
			if (parse_int('/WL=', mparm_str)) {
				if( WinViewCount() > 2 ) {
					RM( "WINMENU /WT=Link Window/HE=0/DB=0/DC=0" +
							"/WH=Select window to link to and press <ENTER>, or <ESC> to abort" +
							"/HS=" + LINKWIN_HELPLINK  + MParm_Str);
          if ( Return_Int > 0 ) {
						Link_Window(Return_Int);
						// This is a work-around for a bug in link_window that sets screen
						// num to the same as the window you are linking to.  It should not
						// do this.
						Screen_Num = Cur_Screen;

						Return_Int = 1;
						Rm( "SetWindowNames" );
						Return_Int = 1;
					}
          else
          if (return_int == -2)
          {
            tw2 = window_id;
            j1 = cur_window;
            if (tw2 != tw1) {
              refresh = false;
              if (switch_win_id( tw1 )) {
                if (caps(file_name) == '?NO-FILE?') {
                  link_window( j1 );
                  make_message( 'Window linked.');
                }
              }
            }
          }
				}
        else
        {
          Rm( "MEUTIL1^LOADFILE /X=" + Str( Win_X1 ) + "/Y=" + Str( Win_Y1 ) );
        }
			}
			if ( Return_Int == 0 ) {
					link_window(old_win);
					make_message( 'Window linked.');
			}
			refresh = false;
			Rm( "SetWindowNames" );
	//	}
		Return_Int = 1;
	}
	else {
		Return_Int = 0;
	}

Exit:

}  // SplitWin

int UnSplitWin( Win2Id = Parse_Int( "/ID=", MParm_Str ) ) {
/******************************************************************************
															 Multi-Edit Macro
																9/20/95 3:12PM

  Function:
  Entry   :
  Exit    :
  Globals :
  Macros  :

							 Copyright (C) 1995 by American Cybernectic, Inc.
********************************************************************( ldh )***/

	int ActiveWinId	= Window_Id;
	int SavRefresh	= Refresh;
	int Result 			= False;

	struct TWindowPlacement OrgTwp;
	struct TWindowPlacement CurTwp;

	Refresh = False;
	if ( Switch_Win_Id( Win2Id ) ) {
		OrgTwp.Length = 22;
		CurTwp.Length = 22;
		GetWindowPlacement( Window_Handle, &OrgTwp );
		Switch_Win_Id( ActiveWinId );
		GetWindowPlacement( Window_Handle, &CurTwp );
		if ( ( CurTwp.rcNormPos_Top == OrgTwp.rcNormPos_Top ) &&
				( CurTwp.rcNormPos_Bottom == OrgTwp.rcNormPos_Bottom ) ) {
			if ( CurTwp.rcNormPos_Left < OrgTwp.rcNormPos_Left ) {
				// Expand right
				CurTwp.rcNormPos_Right = OrgTwp.rcNormPos_Right;
			}
			else {
				// Expand left
				CurTwp.rcNormPos_Left = OrgTwp.rcNormPos_Left;
			}
			Result = True;
		}
		else if ( ( CurTwp.rcNormPos_Left == OrgTwp.rcNormPos_Left ) &&
				( CurTwp.rcNormPos_Right == OrgTwp.rcNormPos_Right ) ) {
			if ( CurTwp.rcNormPos_Top < OrgTwp.rcNormPos_Top ) {
        // Expand down
				CurTwp.rcNormPos_Bottom = OrgTwp.rcNormPos_Bottom;
			}
			else {
				// Expand up
				CurTwp.rcNormPos_Top = OrgTwp.rcNormPos_Top;
			}
			Result = True;
		}
		if ( Result ) {
			SetWindowPlacement( Window_Handle, &CurTwp );
		}
	}
	Refresh = SavRefresh;
	return ( Return_Int = Result );

}  // UnSplitWin

#define file_meerr    (user_id + "MEERR.TMP")

void WinCustomize( ) {
/********************************************************************************
 * Allow  for customization of the MDI window for attached to current ME Buffer
 *
 *
 ********************************************************************************/
	int jx, jy, id;
	int flags, k1, k2;
	str tstr1, tstr2;
	int numItems;
	int hMenu, hSysMenu;
	str sMenuText [80];
	str passedstr = global_str('ACTIVE_MDI');

	if ( passedstr == '' )
		passedstr = 'MDI';

	if ( window_handle )
	{
		hMenu    = CreateMenuFromDB (WCmdMapName, passedstr, MENU_PopUp);
		if ( hMenu != 0 )
		{
			hSysMenu = GetSystemMenu (window_handle, FALSE);

			if ( hSysMenu != 0)
			{
				numItems =  GetMenuItemCount (hSysMenu);
				if((numItems > 0) && (numItems < 32000))
				{
					jy = 0;
					for ( jx = 0; jx < numItems; jx++ )
					{
						id = GetMenuItemID (hSysMenu, jy);
						switch (id )
						{
							case SC_CLOSE :
								if (Wcmd_Find (0, Global_Int ("~CLOSE_WCMD_ID"), flags, k1, k2, tstr1, tstr2)) {
									if ( k1 | k2 )
									{
										tstr1 = "&Close\t" + Make_Key_Name (k1 | (k2 << 8));
										ModifyMenu (hSysMenu, jy, MF_STRING | MF_BYPOSITION, id, tstr1);
									}
								}
								jy++;
								break;
							case SC_MINIMIZE :
								if (Wcmd_Find (0, Global_Int ("~MIN_WCMD_ID"), flags, k1, k2, tstr1, tstr2)) {
									if ( k1 | k2 )
									{
										tstr1 = "Mi&nimize\t" + Make_Key_Name (k1 | (k2 << 8));
										ModifyMenu (hSysMenu, jy, MF_STRING | MF_BYPOSITION, id, tstr1);
									}
								}
								jy++;
								break;
							case SC_MAXIMIZE :
								if (Wcmd_Find (0, Global_Int ("~MAX_WCMD_ID"), flags, k1, k2, tstr1, tstr2)) {
									if ( k1 | k2 )
									{
										tstr1 = "Ma&ximize\t" + Make_Key_Name (k1 | (k2 << 8));
										ModifyMenu (hSysMenu, jy, MF_STRING | MF_BYPOSITION, id, tstr1);
									}
								}
								jy++;
								break;
							case SC_RESTORE :
								if (Wcmd_Find (0, Global_Int ("~RESTORE_WCMD_ID"), flags, k1, k2, tstr1, tstr2)) {
									if ( k1 | k2 )
									{
										tstr1 = "&Restore\t" + Make_Key_Name (k1 | (k2 << 8));
										ModifyMenu (hSysMenu, jy, MF_STRING | MF_BYPOSITION, id, tstr1);
									}
								}
								jy++;
								break;
							case SC_MOVE :
                if (Wcmd_Find (0, Global_Int ("~MOVE_WCMD_ID"), flags, k1, k2, tstr1, tstr2)) {
                  if ( k1 | k2 )
                  {
                    tstr1 = "&Move\t" + Make_Key_Name (k1 | (k2 << 8));
                    ModifyMenu (hSysMenu, jy, MF_STRING | MF_BYPOSITION, id, tstr1);
                  }
                }
                jy++;
								break;
							case SC_SIZE :
								if (Wcmd_Find (0, Global_Int ("~SIZE_WCMD_ID"), flags, k1, k2, tstr1, tstr2)) {
									if ( k1 | k2 )
									{
										tstr1 = "&Size\t" + Make_Key_Name (k1 | (k2 << 8));
										ModifyMenu (hSysMenu, jy, MF_STRING | MF_BYPOSITION, id, tstr1);
									}
								}
								jy++;
								break;
							case 0 :
								jy++;
								break;
							default:
								DeleteMenu ( hSysMenu, jy, MF_BYPOSITION);
						}
					}

					numItems = GetMenuItemCount (hMenu);
					if((numItems > 0) && (numItems < 32000))
					{
						for ( jx = 0; jx < numItems; jx++ )
						{
							GetMenuString (hMenu, jx, sMenuText, 80, MF_BYPOSITION);
							AppendMenu (hSysMenu,
								GetMenuState(hMenu, jx, MF_BYPOSITION),
								GetMenuItemID (hMenu, jx),
								sMenuText);
						}
					}
					else
					{
						beep;
					}
				}
			//  DrawMenuBar (hSysMenu);
			}
			else
			{
				beep;
			}
			DestroyMenu (hMenu);
		}
    if (g_DefaultRuler) // if ruler to default on
    {
      if ( window_name != "OUTPUT")
      {
        RulerOn (cur_window);
      }
    }
    else if ( g_DefaultAllRuler ) // default all control
    {
      int jx;
      int t_win = cur_window;
      int t_refresh = refresh;
      refresh = False;
      // Check for any window with ruler on, if so we will turn on
      for ( jx = 1; jx <= Window_Count; jx++ )
      {
        switch_window (jx);
        if ( window_name != "OUTPUT")
        {
          if ( window_handle && (RulerStatus(jx) != 0))
          {
            break;
          }
        }
      }
      switch_window (t_win);
      refresh = t_refresh;
      if ( jx <= Window_Count )
      {
        RulerOn (cur_window);
      }
    }
	}
}


void WOrganize( int Op = Parse_Int( "/M=", MParm_Str ) ) trans2 {
/*******************************************************************************
																MULTI_EDIT MACRO

Name:				WOrganize

Description:	Organizes all non hidden windows on the screen by either
							cascading, tiling or minimizing them.

Parameters:   /M=0		Cascade
							/M=1    Tile vertical
							/M=2		Minimize
							/M=3    Tile horizontal

							 (C) Copyright 1991 by American Cybernetics, Inc.
*******************************************************************************/
	switch (op)
	{
		case 0 :
			SendMessage (client_handle, WM_MDICASCADE, 0, 0);
			break;
		case 1 :
			SendMessage (client_handle, WM_MDITILE, MDITILE_VERTICAL, 0);
			break;
		case 2 :
			break;
		case 3 :
			SendMessage (client_handle, WM_MDITILE, MDITILE_HORIZONTAL, 0);
			break;
	}
}

void WinOp( int Op = Parse_Int( "/T=", MParm_Str ) ) trans2 {
/*******************************************************************************
																MULTI_EDIT MACRO

Name: WINOP

Description:  Performs various window operations

Parameters:		/T=0	Create window
							/T=1  Delete window
							/T=2  Hide window
							/T=3  Window list
							/T=4  Split window
							/T=5  Resize window
							/T=6  Link window
							/T=7  Unlink window
							/T=8  Zoom window
							/T=9  Delete all windows
							/T=10 Minimize Window

							 (C) Copyright 1991 by American Cybernetics, Inc.
*******************************************************************************/

	int Tt ;
  int treturn_int = return_int;
  str treturn_str[max_line_length] = return_str;

	switch ( Parse_Int( "/T=", MParm_Str ) ) {
		case 0 :
			Rm( "MakeWin" );
			break;

		case 1 :
			Rm( "DelWin " + MParm_Str );
//			Make_Message( "" );
			break;

		case 2 :
			Window_Attr |= 0x01;
			Make_Window_Visible( 0 );
			Rm( "FindWin /NM=1" );
			//New_Screen;
			break;

		case 3 :
			Rm( "SwitWin " + MParm_Str );
			break;

		case 4 :
			RM( "SplitWin /WL=1" );
			break;

		case 5 :
			// Mod_Win(0,0,0);
			break;

		case 6 :
			Rm( "Linkwin " + MParm_Str );
			break;

		case 7 :
			Unlink_Window;
			break;

		case 8 :
			Zoom( );
			break;

		case 9 :
			do {
				Tt = Window_Count;
				DelWin( 0, 0, 0 );
			}	while ( Tt > Window_Count );
			//Make_Message( "" );
			break;

		case 10 :
			Minimize( );
			break;

		case 11 :
			Maximize( );
			break;

		case 15 :
			WinCustomize( );
			break;
	}
  return_int = treturn_int;
  return_str = treturn_str;
}  // WinOp