macro_file EXIT;

#INCLUDE winsmall.sh
// access to "save floating toolbox info" routine
#INCLUDE toolbox.sh
#INCLUDE mew.sh
#INCLUDE dialog.sh
#INCLUDE exit.sh
#INCLUDE menus.sh
#INCLUDE metools.sh
#INCLUDE mewlist2.sh

#DEFINE ME_VERSION_LENGTH 34



void show_restore(str cp, str sn)
{
  if ( TRUE /* global_int('!@SESSRSTRMSG@!') */ )
	{

		if ( cp != '' )
		{
      make_message('Restoring Session: '+sn+' ('+cp+' )');
		}
	}
}

void killshow_restore()
{
  if ( TRUE /* global_int('!@SESSRSTRMSG@!') */ )
	{
    MAKE_MESSAGE('');
	}
}


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

EXIT		- Standard exit routine

StrCrc16 - Converts a string into a 16bit CRC value.
CrcFileStr - Creates a CRC16 based filename
make_restr_name - Creates the name for the restore file

RESTORE - Restores editor according to file created by STATUS
STATUS	- Creates restore file.

							 (C) Copyright 1991 by American Cybernetics, Inc.
*******************************************************************************/

int SaveOnExitProc( int &retval, int dlg, int message, int wparam, int lparam, str parms ) no_break
{
  switch ( message )
  {
    case WM_COMMAND :
      switch ( wparam )
      {
        case 101 :
        case 102 :
        case DLG_Wcmd_Init :
          int flag, j, maxitems = SendDlgItemMessage( dlg, 1000, LB_GETCOUNT, 0, 0 );
          if ( wparam == 102 ) {
            flag = false;
          } else
            flag = true;
          for ( j=0; j<maxitems; ++j ) {
            SendDlgItemMessage( dlg, 1000, LB_SETSEL, flag, j);
          }
          return (1);
        case 100 :
          int jy = window_id, blarg = LBGetSelectCount(GetDlgItem(dlg, 1000));
          int j, maxitems = SendDlgItemMessage( dlg, 1000, LB_GETCOUNT, 0, 0 );
          for ( j=0;j<maxitems;++j ) {
            working;
            Make_Message('Saving files...');
            if ( LBIsItemSelected(GetDlgItem(dlg, 1000), j) ) {
              goto_line(j + 1);
              switch_win_id(parse_int('WID=', get_line));
              rm('MEUTIL1^SAVEFILE /NP=1');
              switch_win_id(jy);
            }
          }
          break;
      }
		case WM_SysCommand :
				if ( wparam == 61536)
          return (0);
  }
  return(DlgMessageProc(retval, dlg, message,wparam,lparam, parms ));
}

macro EXIT TRANS2 {
/*******************************************************************************
																MULTI-EDIT MACRO

Name:	EXIT

Description:  If any files are changed and not saved this macro displays them
							and asks for user verification.  The user is given the choice of
							quitting without saving, saving and then quitting, or cancelling
							the operation.

Returns:      1 if it is Exiting Ok.
              0 if did not Exit properly.

Parameters:
							/NP=  If 1, and there are modified files in memory, the usual
										"Do you want to save these files?" prompt will not appear,
										but the files will be unconditionally saved.

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

	int Old_Refresh,Temp_Integer,Not_Saved,Temp_Window,X1,X2,Y1,Y2,Str_X,
					 t_bc, jx, jy, jz, choice = global_int("!EXIT_PROMPT_CHOICE") ;
	str Temp_String;

	Old_Refresh = Refresh;
	Refresh = False;
	Temp_Window = CUR_WINDOW;
	working;


	temp_string = global_str('@ME_EXIT_MACRO@');
	while(  temp_string != ''  ) {
		jx = xpos( ';', temp_string, 1 );
		if(  jx == 0  ) {
			jx = svl(temp_string) + 1;
		}
		Return_Int = 1;
		if(  jx > 1  ) {
			RM( copy( temp_string, 1, jx -1)  );
		}
		temp_string = str_del( temp_string, 1, jx );
		if(  return_int == 0  ) {
			goto end_of_mac;
		}
	}

/* Check to see how many files are not saved */
	Temp_Integer = 1;
	Not_Saved = 0;
	while(  (Temp_Integer <= Window_Count)  ) {
		Switch_Window(Temp_Integer);
		if(  (File_Changed)  ) {
			if(  (window_attr & $80) == 0  ) {
					Not_Saved = Not_Saved + 1;
			} else {
				if(  caps( file_name ) != '?NO-FILE?') {
					save_file;
				}
			}
		}
		++Temp_Integer;
	}

	if(  (Not_Saved > 13)  ) {
		Not_Saved = 13;
	}

/* If there are any unsaved files, make a warning box */
	if(  (Not_Saved)  ) {
		if(  (parse_int('/NP=',mparm_str))  ) {
			working;
			Make_Message('Saving files...');
			RM('AUTOSAVE');
			goto skip_prompt;
		}

		switch_window( window_count );
		create_window;
		jy = cur_window;
		jz = 1;

		JX = 1;
    int MaxLength = 0, ScrollFlag = 0;
		while(  jx < window_count  ) {
			switch_window( jx );
			if(  (window_attr & $80) == 0  ) {
				if(  (File_Changed)  ) {
          put_line_to_win( 'WID=' + str(window_id) + 'WN=' + window_name + 'FN=' + truncate_path(File_Name) +
                         'FP=' + get_path(File_Name) , jz, jy, FALSE );
					++jz;
          if ( length(get_path(file_name)) > MaxLength )
            MaxLength = length(get_path(file_name));
				}
			}
			++jx;
		}
		switch_window( jy );
    if(choice > 2)
      choice = 2;
    if (choice < 0) {
      choice = 1;
    }
    if ( MaxLength > 22 )
      ScrollFlag = DLGF_es_AutoHScroll;

    /* This is going to check screen height for dialog sizing purposes.
    struct trect rect;
    GetWindowRect(GetDesktopWindow(), &rect);
    */
    int dlg;

    DlgCreate(dlg);
    DlgAddCtrl( dlg, DLG_Icon, "IC_QUESTION", 1, 2, 0,0,2010,0, "" );
    DlgAddCtrl( dlg, DLG_Static, "Save all modified files?", 12, 2, 0, 0, 2000, 0, "");
    DlgAddCtrl( dlg, DLG_PushButton, "&Yes", 10, DLG_PosOffset + 1, 8, 0, 100, DLGF_DefButton, "/R=1");
    DlgAddCtrl( dlg, DLG_PushButton, "&No", DLG_PosOffset + 10, DLG_PosOffset, 8, 0, 104, 0, "/R=3");
    DlgAddCtrl( dlg, DLG_PushButton, "Cancel", DLG_PosOffset + 10, DLG_PosOffset, 8, 0, 103, 0, "/R=0");
    DlgAddCtrl( dlg, DLG_PushButton, "&Help", 50, DLG_PosOffset, 8, 0, 105, 0, "/R=2");
    DlgAddCtrl( dlg, DLG_Static, "&Modified files:", 10, DLG_PosOffset + 2, 0, 0, 2001, 0, "");
    DlgAddCtrl( dlg, DLG_ListBox,"WN=/W=12FN=/W=17FP=/W=128", 10, DLG_PosOffset + 1, 60, 0, 1000, ScrollFlag | DLGF_LB_EXTENDEDSEL, "/HSCROLL=" + str(MaxLength + 39) + "/WIN=" + str(cur_window));
    DlgAddCtrl( dlg, DLG_PushButton, "&All", 1, DLG_PosOffset, 8, 0, 101, 0, "");
    DlgAddCtrl( dlg, DLG_PushButton, "N&one", 1, DLG_PosOffset + (DLG_Units | 15), 8, 0, 102, 0, "");
  //  DlgAddCtrl( dlg, DLG_Icon, "IC_QUESTION", 3, 1, 0,0,2010,0, "" );
  //  DlgAddCtrl( dlg, DLG_Static, "Save Selected Files?", 13, 1, 0, 0, 2000, 0, "");
  //  DlgAddCtrl( dlg, DLG_PushButton, "&All", 1, DLG_PosOffset + 3, DLG_StanBtnWidth, 0, 101, 0, "");
  //  DlgAddCtrl( dlg, DLG_PushButton, "&None", DLG_PosOffset, DLG_PosOffset + (DLG_Units | 15), DLG_StanBtnWidth, 0, 102, 0, "");
  //  //DlgAddCtrl( dlg, DLG_Static, "&Modified files:", DLG_PosOffset + DLG_StanBtnWidth + 2, DLG_NegOffset - 3, 0, 0, 2001, 0, "");
  //  DlgAddCtrl( dlg, DLG_ListBox,"WN=/W=12FN=/W=17FP=/W=128", DLG_PosOffset + DLG_StanBtnWidth + 2, 2, 60, 8, 1000, ScrollFlag | DLGF_LB_EXTENDEDSEL, "/HSCROLL=" + str(MaxLength + 39) + "/WIN=" + str(cur_window));
  //  DlgAddCtrl( dlg, DLG_PushButton, "OK", 1, DLG_PosOffset + 9, DLG_StanBtnWidth, 0, 100, DLGF_DefButton, "/R=1");
  //  DlgAddCtrl( dlg, DLG_PushButton, "Cancel", DLG_PosOffset + DLG_StanBtnWidth + 2, DLG_PosOffset, DLG_StanBtnWidth, 0, 103, 0, "/R=0");
  //  DlgAddCtrl( dlg, DLG_PushButton, "Help", 63, DLG_PosOffset, DLG_StanBtnWidth, 0, 104, 0, "/R=2");

    temp_integer = DlgExecute( dlg, 100, "Files have been modified!", "Files, Saving Modified", "/HOOK=SAVEONEXITPROC" ,0);

    dlgkill(dlg);
		refresh = FALSE;
		delete_window;
skip_prompt:

    if( (Temp_Integer == 0)  ) {
			return_int = 0;
			Goto End_OF_Mac;
		}
    Goto Go_Quit;
	} else {
		Goto Go_Quit;
	}
	return_int = 0;
	Goto End_OF_Mac;

Go_quit:
	Switch_Window(Temp_Window);
	Return_Int = 1;
  rm('mewsetup^check_setup /X=10/Y=3');
	if(  return_int < 1  ) {
		goto End_Of_Mac;
	}
  Working;

  // Phase II: -------------------------------------------------------
  // save the positions of any floating toolboxes
  // (regardless of the 'restore' setting?
  SaveFloatTB();         // save positions of all FLOATING toolboxes
  // =================================================================

  if(  Global_Int('@RESTORE')  ) {

			/* Clear out unneeded globals */

		JX = 12;
		temp_string = '0ISTR_';
		CALL CLEAR_GLOBAL_LIST;

		JX = 12;
		temp_string = 'X0ISTR_';
		CALL CLEAR_GLOBAL_LIST;

		jx = global_int('@KEYMACRO_COUNT@');
		temp_string = '@KM!#';
		CALL CLEAR_GLOBAL_LIST;

		set_global_int('@KEYMACRO_COUNT@', 0 );
		set_global_str('@KMTEMP!#','');


		RM('STATUS /SN=' + parse_str("/SN=",mparm_str) +
				"/EXITING=" + str(!parse_int("/NE=", mparm_str)));

// phase III: -----------------------------------------------------------

    // this is redundant ( if RESTORE == 0 )  <--- but is it necessary?
    KillAllToolboxes(); // destroy all toolbox windows and
                        //  global references to them

// ======================================================================

	}

	refresh = false;
  if( !parse_int("/NE=", mparm_str))
  {
    status_row = 0;
    Quit (0);
  }
  Return_Int = 1;
	goto end_of_mac;

Clear_global_list:
	JY = 0;
	while(  JY < JX  ) {
		++JY;
		SET_GLOBAL_STR( temp_string + STR(JY), '' );
	}
	RET;


End_of_mac:
	Switch_Window(Temp_Window);
	Refresh = Old_Refresh;


}

/*---------------02-07-93 08:07pm-------------------
 StrCrc16

		Calculates the CRC16 value of the passed string.
		Returns the integer result.
--------------------------------------------------*/
int StrCrc16( str szBuf )
{
  int crc = 0,
			temp;
  int i, j, iBufLen, ulTableEntry;

  // Calculate the crc value.
  iBufLen = svl( szBuf );
  for ( i = 1; i <= iBufLen; i++)
  {
		Temp = ((crc >> 8) & $FF) ^ ascii(  str_char( szbuf, i ));
		crc = ((crc << 8) & 0xFFFF) ^ get_crc_entry(Temp);
  }

  return( crc );
}


/*---------------02-07-93 10:19pm-------------------
 CrcFileStr
		Creates an 8 character unique name from the
		passed directory/file name.
--------------------------------------------------*/
str CrcFileStr( str dn )
{
	str fn[8] = "", crc[4];

	int jx;

	jx = xpos( "\\", dn, 4 );
	if( jx > 0 )
	{
		crc = Hex_Str( StrCrc16( copy( dn, jx + 1, 255 ) ) & 0xFFFF );

		crc = copy("0000", 1, 4  - svl(crc)) + crc;
		fn = crc;
		dn = copy( dn, 1, jx - 1 );
	}
	else
	{
		fn = "0000";
	}
	crc = Hex_Str( StrCrc16( dn ) & 0xFFFF);
	crc = copy("0000", 1, 4  - svl(crc)) + crc;
	return( crc + fn );
}

str fix_cmd_param(str cmd_param) {
/*
 makes a string suitable to be used as a DOS command line parameter
 by replacing illegal characters with an underscore
*/
	int space_pos;

	while ((space_pos = xpos(" ", cmd_param, 1)) > 0) {
		cmd_param = copy(cmd_param,1,space_pos - 1) + "_" +
								copy(cmd_param, space_pos + 1, 255);
	}

	return(cmd_param);
}

/*---------------02-07-93 10:24pm-------------------
 make_restr_name

			Creates the proper name and path for the
			restore file.  Does not include an extension!

			restore_mode defines how the name is to be
			created.
				1 = The old restore_path + user_id + STATUS
				2 = ME_PATH + user_id + STATUS
				3 = The new CRC encode name
--------------------------------------------------*/
str make_restr_name( int restore_mode,str t_name[128])
{
  str n[8],
      restore_path[128];

  return_str = Global_Str("@RESTORE_PATH");
  rm("XlateCmdLine");
  restore_path = return_str;

  if( (svl(restore_path) != 0) &&
    (copy(restore_path,length(restore_path),1) != '\')
    )
    restore_path += '\';

	if (restore_mode == 3)
	{
		if (svl(t_name)) {
			n = CrcFileStr(caps(fix_cmd_param(t_name)));
		} else {
			n = CrcFileStr( fexpand("") );
		}
    if( restore_path != "" )
		{
      return_str = restore_path + n;
		}
		else
		{
			return_str = n;
			rm("MakeUserPath");
		}
	}
	else
	{
    if(  restore_mode == 2  ) {
      if( restore_path != '' )
      {
        return_str = restore_path + user_id + "STATUS";
      }
      else
      {
        return_str = "STATUS";
        rm("MakeUserPath");
      }
		} else {
      return_str = user_id + 'STATUS';
		}
	}
	return( return_str );
}

str fix_dir_spec(str dir_spec) {
/* properly gets rid of trailing backslash of a directory spec for use with
	 the change_dir() function.  This one will work even with network volumes
	 like SYS:\TEMP\
*/
	int t_len = svl(dir_spec);

	if (str_char(dir_spec,t_len) == "\\") {
		int t_int = xpos("\\",dir_spec,1);
		if ((t_int > 0) && (t_int < t_len)) {
			dir_spec = copy(dir_spec, 1, --t_len);
		}
	}

	RETURN(dir_spec);
}


macro RESTORE TRANS {
/*******************************************************************************
																MULTI-EDIT MACRO

Name:	RESTORE

Parameters:  /M=    Mode
								0 = Normal full restore
								1 = Partial restore.  Restore globals, and general status,
										but NOT windows and files.
            /SS     Session switch
                    indicates that restore is being called from the
                    session manager, and special handling of screens if performed

Description: This macro uses the file STATUS.MEW and restores the editor exactly
						 to the conditions contained therein.


--------------------------- MODIFICATIONS --------------------------------------

040593[scm]:
 Returns:      Global system variable Return_Int is set to the active window
							 (the window that is active upon entry to the this macro)
							 This change aids the Session Manager.

-------------------------------------------------------------------------------

							 (C) Copyright 1991-93 by American Cybernetics, Inc.
*******************************************************************************/
  int Temp_Integer,Status_Window,Active_Window = 0,Temp_Window,X1,Y1,X2,Y2,
          count, t_sc, new_screen_setup = 0, trestore = global_int("@RESTORE"),
          restore_mode = parse_int("/M=", mparm_str), bid_count = 0,
          new_screen_layout = 0, main_showcmd = -1, orig_showcmd;
	str  TStr[500], numstr[20] ;
  struct TWindowPlacement twp, masterwp;

  str sessname = parse_str("/SN=",mparm_str),
			sessname2 = "",
			currentpath = '';
  int session_switch = parse_int("/SS=",mparm_str);

  int master_redraw_off = false;

  RestoreResult = FALSE;
    //  Save the application coordinates
  twp.length = 22;
  GetWindowPlacement( frame_handle, &twp );
  //orig_showcmd = twp.showcmd;


	if (svl(sessname)) {
		sessname2 = "0:" + sessname;
	}
	Refresh = False;
	Messages = False;
	Error_Level = 0;
	working;
/* Turn truncate spaces off while loading STATUS.MEW lest certain global strings
with trailing spaces get screwed up. */
	Temp_Integer = Truncate_Spaces;
	Truncate_Spaces = False;
  if( restore_mode )
  {
		Active_Window = window_id;
		create_window;
  }

LOAD_NAMED:
  Load_File( make_restr_name( global_int("@RESTORE"),sessname2) + '.MEW' );

/*
	if(  Global_Int('@RESTORE_USE_ME_PATH')  ) {
    Load_File(me_path + user_id + 'STATUS.MEW');
	} else {
    Load_File( Global_Str('@RESTORE_PATH') + user_id + 'STATUS.MEW');
	}
*/
/*
messagebeep(-1);
make_message("RESTORE: FN=[" + file_name +
"] SN=[" + sessname + "] EL=[" + str(error_level));
while (!check_key) {
}
*/
	Truncate_Spaces = Temp_Integer;
	Status_Window = Cur_Window;
	if(  (ERROR_LEVEL != 0)  ) {
		Temp_Integer = error_level;
		refresh = TRUE;
		Error_Level = 0;

		rm('WINDOW^DELWIN');

  //  DeleteMenu (MainMenuHandle, 0, MF_BYPOSITION);
//    DeleteMenu (MainMenuHandle, GetMenuItemCount (MainMenuHandle) -1, MF_BYPOSITION);
//    DrawMenuBar (frame_handle);

		if (temp_integer == 3002) {
			if (svl(sessname)) {
				if (session_switch) {
// we would get here if we created a new named session
					set_global_str("!SESSION_NAME",sessname);
				} else {
/* if this was called via a named session on the DOS command line,
	 treat it as an error */
					RM("MEERROR^MessageBox /B=2/T=Restore Error/M=The session name " +
							sessname + " does not exist.");
				}
			}
			Error_Level = 0;
		} else {
			RM('MEERROR^MessageBox /B=2/M=ERROR OCCURRED DURING RESTORE MACRO!  Press any key for error message.');
			Error_level = temp_integer;
		}
// ------------------------------------------------------------------
//  restore mode is non-zero (global,eachdir,encoded)
//  <STATUS>.mew is not found, so build toolboxes according to current
//  settings in <wcmdmapname>.db^boxlist.db

    rm('tbmgr^build_toolboxes');

// -----------------------------------------------------------------

		Goto END_OF_MAC;
	}
  if(  remove_Space(copy(get_line,1, 38)) !=
       remove_space('@MULTI-EDIT FOR WINDOWS VERSION ' + Copy(version,1,3))  ) {
		refresh = TRUE;
		rm('WINDOW^DELWIN');
		Make_Message( ' STATUS FILE CREATED WITH DIFFERENT VERSION.  RESTORE ABORTED.');
		Goto END_OF_MAC;
	}


// for named sessions ------------------------------------------------------


  if ( !restore_mode )
  {

    if (global_int('@RESTORE') == 3)
		{

	    int tx, jx,jzz1,jzz2;
	    // str sessname,currentpath;

      if(LocateDBPage( "MECONFIG", "SESSMGR.CFG", TRUE ) )
      {
        if (!read_only && (caps( sessname ) != caps(get_line) ))
        {
          mark_pos;
          down;
          goto_col(1);
          while(!at_eof && (cur_char != "\f"))
          {
            del_line;
          }
          goto_mark;
          eol;
          cr;
          put_line( sessname );
        }
        switch_window( status_window );
      }



	    tstr = get_line;

			var_parse_str("SESS_BY_DIR=",tstr,currentpath);
			var_parse_str("SESS_BY_NAME=",tstr,sessname);
			if (svl(sessname)) {
				set_global_str("!SESSION_NAME",sessname);
				var_parse_str("SESS_HOME_DIR=",tstr,currentpath);
				change_dir(fix_dir_spec(currentpath));  // optional home dir for named sessions
// check for a blank status file
				down;
				if (at_eof) {
					RM("WINDOW^DELWIN");
    			rm('tbmgr^build_toolboxes');
					Goto END_OF_MAC;
				} else {
					up;
				}
			} else {
				set_global_str("!SESSION_NAME","");

				var_parse_str("SESS_CUR_NAME=",tstr,sessname);
 				sessname2 = "0:" + sessname;
				set_global_str("!SESSION_NAME",sessname);
				goto LOAD_NAMED;

			}
// what are these????
      var_parse_int('/V=', tstr, x1 );
      var_parse_int('/EV=', tstr, y1 );
      if ( !new_screen_setup )
      {
        show_restore(currentpath,sessname);
      }
		}
  }


// --------------------------------------------------------------------------


	if(!restore_mode)
	{
		Make_Message('Restoring previous status...');
		working;
	}
	window_attr = $81;

	reg_exp_stat = true;
	ignore_case = false;

	// Now, if partial restore only, then skip the window stuff
	if( restore_mode == 1 )
	{
		search_fwd("%/G_???=", 0);
	}
	else
	{
    RestoreResult = TRUE;
    down;
    tstr = get_line;
    down;
    if(  Parse_Int('/MISC=',TStr)  ) {
      Insert_Mode = Parse_Int('/I=',TStr);
      var_parse_int('/CC=', tstr, x1 );
      new_screen_layout = (global_int("CUR_SCRN") != x1);
      set_global_int('CUR_SCRN', x1 );
      var_parse_int('/SC=', tstr, t_sc );

      // Set the window placement
      // masterwp.flags = parse_int('/WP_F=', tstr );
      if( Restore_Flags & _REST_SCREEN_POS )
      {
        masterwp.flags = 0;
        masterwp.showcmd = parse_int('/WP_SC=', tstr );
        masterwp.ptMinPos_X = parse_int('/WP_MNX=', tstr );
        masterwp.ptMinPos_Y = parse_int('/WP_MNY=', tstr );
        masterwp.ptMaxPos_X = twp.ptMaxPos_X; // parse_int('/WP_MXX=', tstr );
        masterwp.ptMaxPos_Y = twp.ptMaxPos_Y; // parse_int('/WP_MXY=', tstr );
        masterwp.rcNormPos_left = parse_int('/WP_LT=', tstr );
        masterwp.rcNormPos_top = parse_int('/WP_TP=', tstr );
        masterwp.rcNormPos_right = parse_int('/WP_RT=', tstr );
        masterwp.rcNormPos_BOTTOM = parse_int('/WP_BT=', tstr );
        masterwp.length = 22;
        if( !session_switch )
        {
          if(!((masterwp.rcNormPos_Bottom <= masterwp.rcNormPos_Top) ||
            (masterwp.rcNormPos_Right <= masterwp.rcNormPos_Left)))
          {
            MEW_ShowCmd = masterwp.showcmd;
            masterwp.showcmd = SW_HIDE;
            SetWindowPlacement( frame_handle, &masterwp );
            if((MEW_ShowCmd == SW_Hide) ||
               (MEW_ShowCmd == SW_SHOWMINIMIZED) ||
               (MEW_ShowCmd == SW_MINIMIZE))
              MEW_ShowCmd = SW_Show;
          }
          else
          {
            MEW_ShowCmd =  SW_SHOW;
          }
        }
      }
    }

		count = 0;
		while(  NOT( At_EOF )  ) {
			TStr = Get_Line;
			if(  Copy( tstr, 1,3) == '/W=') {
				WORKING;
				Switch_Window( Window_Count );
				Create_Window;
        make_window_visible (1);
				Temp_Window = Cur_Window;
				temp_integer = XPOS('/ZOOM=', tstr, 1 );
				if(  temp_integer != 0  ) {
					set_global_str('!WINZOOM#' + str(window_id),
													copy(tstr,temp_integer + 6, 80 ) );
					tstr = copy(tstr, 1, temp_integer - 1);
					if(  global_str('!WINZOOM#' + str(window_id)) != ''  ) {
						zoom_char = parse_str( '/ZC=', Global_Str('!WINZOOM#' + str(window_id)) );
					}
				}
				File_Name = Parse_Str('/FN=',TStr);

				Window_Attr = Parse_Int('/WA=',TStr);

	/* Restore window coordinates while checking for out of bounds */
        // Set the window placement
        twp.flags             = parse_int('/WP_F=', tstr );
        twp.showcmd           = parse_int('/WP_SC=', tstr );
        twp.ptMinPos_X        = parse_int('/WP_MNX=', tstr );
        twp.ptMinPos_Y        = parse_int('/WP_MNY=', tstr );
        twp.ptMaxPos_X        = parse_int('/WP_MXX=', tstr );
        twp.ptMaxPos_Y        = parse_int('/WP_MXY=', tstr );
        twp.rcNormPos_left    = parse_int('/WP_LT=', tstr );
        twp.rcNormPos_top     = parse_int('/WP_TP=', tstr );
        twp.rcNormPos_right   = parse_int('/WP_RT=', tstr );
        twp.rcNormPos_BOTTOM  = parse_int('/WP_BT=', tstr );
        twp.length = 22;

        if(!((twp.rcNormPos_Bottom <= twp.rcNormPos_Top) ||
          (twp.rcNormPos_Right <= twp.rcNormPos_Left)))
        {
          if(twp.showcmd & SW_SHOWMINIMIZED)
          {
            twp.flags = twp.flags | 1;
          }
          SetWindowPlacement( window_handle, &twp );

          if(  parse_int('/A=', tstr) == 1  )
          {
            active_window = window_id;
            main_showcmd = twp.showcmd;
          }
        }

				if(  (Parse_Int('/LS=',TStr))  ) {
	/* If file is linked to another see if it is the first occurance or not */
          if(  (Global_Int('!Buffer_Id' + Parse_Str('/BI=',Tstr)))  ) {
	/* If not, link it to the window with the first occurance but don't load a file */
            Link_Window(Global_Int('!Buffer_Id' + Parse_Str('/BI=',Tstr)));

            // Check for a hex window
            if( (global_int('!Buffer_Hex' + Parse_Str('/BI=', tstr)))
                || (Parse_Int('/WA=',TStr) & 0x20))
            {
              temp_integer = window_id;
              switch_window( Global_Int('!Buffer_Id' + Parse_Str('/BI=',Tstr)));
              event_macro = "Hex^HexEventProc /W=" + str(temp_integer  );
              temp_integer = window_id;
              switch_window(temp_window);
              event_macro = "Hex^HexEventProc /W=" + str(temp_integer  );
            }
					} else {
	/* If so, set a global integer to indicate a first occurance and to store the
	window number of that one and then load the file */
            ++bid_count;
            set_global_int('!BID_' + str(bid_count), Parse_Int('/BI=',Tstr));
            Set_Global_Int('!Buffer_Id' + Parse_Str('/BI=',Tstr),Cur_Window);
            if( parse_int('/WA=', tstr) & 0x20)
              set_global_int('!Buffer_Hex' + Parse_Str('/BI=', tstr), 1);
						Goto LOAD_IT;
					}
				} else {
	LOAD_IT:
          if(parse_str('/LT=', tstr) != "" )
          {
            line_terminator = reconvert_string(parse_str('/LT=', tstr ));
          }
          fixed_line_length = parse_int("/FLL=", tstr );
					if(  (File_Name != '?No-File?')  ) {
            XLoad_File(File_Name);
					}
				/*  reset_virtual_display;  */
          RM( 'EXTSETUP /FTO=255');
				/*  set_virtual_display;   */
				}
				File_Changed = False;
				Goto_Col( Parse_int('/IL=',TStr));
				Set_Indent_Level;
				Var_Parse_Int('/R=',TStr, x1);
				while(  C_Row < X1  ) {
					X2 = C_ROW;
					Down;
					if(  X2 == C_Row  ) {
						break;
					}
				}
				// check for split error windows (kind of like split hair windows)
				if( parse_int('/ERWN=',tstr)) {
					set_global_int('~MEERR_ID', window_id);
				}
				else if (parse_int('/ERSPLT=', tstr) ) {
					set_global_int('~MEERR_SPLIT_ID',window_id );
				}
				Wrap_Stat = Parse_Int('/WS=',TStr);
				Right_Margin = Parse_Int('/RM=', tstr );
				Indent_Style = Parse_Int('/IS=',TStr);
				Var_Parse_Int('/D=', tstr, x1);
				if(  x1 > 0  ) {
					Doc_Mode = x1;
				}
				Block_Stat = Parse_Int('/BS=',TStr);
				if(  block_stat != 0 ) {
					block_line1 = Parse_Int('/BL1=',TStr);
					block_line2 = Parse_Int('/BL2=',TStr);
					block_col1 = Parse_Int('/BC1=',TStr);
					block_col2 = Parse_Int('/BC2=',TStr);
				}
				Goto_Col( Parse_Int('/C=',TStr));
				Goto_Line( Parse_Int('/L=',TStr));
//        Window_Attr = Parse_Int('/WA=',TStr);  moved above
				window_name = Parse_Str('/WNM=', tstr);
				screen_num = parse_int('/SN=', tstr );

      	if( window_id == Active_Window )
      	{
        	refresh = true;
        	redraw;
        	refresh = false;
      	}
			} else if( copy(  tstr, 1, 7 ) == '/MARKS=' ) {
				int jz, jk, line;
				Switch_Window( temp_window );
					// here is where we restore the position markers
				mark_stack_count = parse_int( '/MARKS=', tstr );
				for( jk = 1; jk <= 3; ++jk)
					for( jz = 1; jz <= 10; ++jz ) {
						numstr = str(jz + (10 * (jk - 1))) + '=';
						line = parse_int('/L' + numstr, tstr );
						if( line > 0 ) {
							set_mark_record( jz, jk, line, parse_int('/P' + numstr, tstr ),
										parse_int('/R' + numstr, tstr ),
										parse_int('/O' + numstr, tstr) );
						}
					}
			} else if(  copy(TStr, 1, 3) == '/G_') {
				goto do_globals;

// phase III of restoring toolboxes -------------------------------------
      } else if ((copy (tstr, 1, 3) == '/TB') && (restore_flags & _REST_TOOL_BARS)) {

        // RESTORE ALL TOOLBOXES FOR THIS SESSION HERE:
        //
        // basically:

        int tbhandle;

        int iconsize=parse_int('/Z=',tstr);
        int orientation=parse_int('/O=',tstr);

        //    parse the name of the toolbox from the gotten statusfile line
        str tboxname = parse_str('/TB=',tstr);

        //    check to see if it exists in the DefinedToolbox list (boxlist.db)

        //    if it exists, call BuildToolbox(name);
        //    buildtoolbox also sets the necessary global variables

        // create if it was not hidden
        int tbvisible = parse_int('/WP_SC=',tstr);

        if ( tbvisible != 0)
        {
          // show window if configured to be visible

          tbhandle = BuildToolbox(tboxname,TRUE
          , iconsize, orientation);

          // (yes, 'ignoreBS' - dont use  boxshown db field
          // because we're using the WP_SC show command parm
          // for setwindowplacement

          //    using the rest of statusfile line, setwindowplacement
          if ( tbhandle != 0 && (orientation == 5) )
          {
            RestoreTBpos(tbhandle,tstr);
          }
        }

// ======================================================================

			}
			Switch_Window(Status_Window);
			Down;
		}
	}

	while(  NOT( AT_EOF )  ) {

DO_GLOBALS:
		TStr = Copy(Get_Line,1,7);
		if(  TStr == '/G_STR='  ) {
			TStr = Copy(Get_Line,8,20);
			Down;
			Set_Global_Str(TStr,reconvert_string(Get_Line));
		} else if(  TStr == '/G_INT='  ) {
			TStr = Copy(Get_Line,8,20);
			Down;
			if(  Val(Temp_Integer, Get_Line) == 0  ) {
				Set_Global_Int(TStr,Temp_Integer);
			}
		}
		DOWN;
	}

	if ((restore_flags & _REST_TOOL_BARS) == 0) {
// build default tool bars if we aren't supposed to restore them
    rm('tbmgr^build_toolboxes');
	}
	Call CLEAR_LINK_GLOBALS;

	Switch_Window(Status_Window);
	if(  (Window_Count > 1)  ) {	// 082493[scm]: change 2 to 1 to fix
																// the 'extra window' bug
/* This is a "just in case" thing so that if there are no /W= commands in
STATUS.MEW, you will at least have one open window */
		Delete_Window;
		Switch_Win_Id(Active_Window);
	} else {
		Erase_Window;
		window_attr = $0;
    Make_Window_Visible (1);
	}

	if( !restore_mode )
	{
		set_global_int('@SCREEN_COUNT', t_sc );
	}

	RM('WINDOW^FindWin');
	set_global_int('MENU_LEVEL', 0 );
	set_global_int('SETUP_CHANGED', 0 );

	Refresh = True;
	New_Screen;
	if(!restore_mode)
  {
		Make_Message('Previous status restored.');
    if (global_int('@RESTORE')==3)
		{
			killshow_restore();
		}
  }
	Goto END_OF_MAC;


CLEAR_LINK_GLOBALS:
  Temp_Integer = 1;
  while(  (Temp_Integer <= bid_count)  ) {
    Set_Global_Int('!Buffer_Id' + Str(global_int("!BID_" + str(temp_integer))),0);
    Set_Global_Int('!BID_' + str( temp_integer), 0);
		++ Temp_Integer;
	}
	RET;

END_OF_MAC:
  set_global_int("@RESTORE", trestore );
	Messages = True;
	return_int = active_window; // 4-05-93[scm] does sessmgr need the window?

  if( main_showcmd != -1 )
    ShowWindow( window_handle, main_showcmd );


  if(master_redraw_off)
  {
    SendMessage( frame_handle, WM_SETREDRAW, 1, 0 );
    SendMessage( client_handle, WM_SETREDRAW, 1, 0 );
    RedrawWindow( frame_handle, 0, 0, rdw_Invalidate | rdw_erase);
    RedrawWindow( client_handle, 0, 0, rdw_Invalidate | rdw_erase);
  }
	if (restore_mode) {
/* if partial restore, we don't want to overwrite the named session
 status file upon exit
*/
		set_global_str("!SESSION_NAME","");
	}

//  SendMessage( frame_handle, WM_SETREDRAW, 1, 0 );
//  SendMessage( client_handle, WM_SETREDRAW, 1, 0 );

}

macro STATUS TRANS2 {
/*******************************************************************************
																MULTI-EDIT MACRO

Name:	STATUS

Description: This macro saves the current status of the editor for the purpose
						 of restoring the editor to exactly the state it was in.

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

int  JY,jx, Active_Window, Status_Window, Temp_Window, temp_backup,
      restore_type = global_int("@RESTORE"),
			new_session = parse_int("/NEW=",mparm_str);
str  TStr[500], numstr[20],
		 session_name = global_str("!SESSION_NAME"),
		 session_name2 = "";
  struct TWindowPlacement twp;

	temp_backup = backups;
	backups = false;
	Undo_Stat = False;
	Refresh = False;
	Messages = False;
	Active_Window = Cur_Window;

/* Find the numerically highest window */
	Switch_Window(Window_Count);
/* Create a window to store all status data */
	Create_Window;
	Status_Window = Cur_Window;
	if (restore_type == 3) {
		if (!svl(session_name)) {
			session_name = fexpand("");
		}
    if(LocateDBPage( "MECONFIG", "SESSMGR.CFG", TRUE ) )
    {
      if (!read_only && (caps( session_name ) != caps(get_line) ))
      {
        mark_pos;
        down;
        goto_col(1);
        while(!at_eof && (cur_char != "\f"))
        {
          del_line;
        }
        goto_mark;
        eol;
        cr;
        put_line(session_name );
        save_file;
      }
      switch_window( status_window );
    }
		session_name2 = "0:" + session_name;

	/*
		if (svl(session_name)) {
			session_name2 = "0:" + session_name;
		}
	*/
	} else {
		session_name = "";
	}

  file_name = make_restr_name(restore_type,session_name2) + '.MEW';

/*
// for named sessions -------------------------------------------------------

  str sessname[60], currentpath;
	int jzz1,jzz2,tx;
  sessname='';

  if ( global_int('RESTORE') == 3 )
  {
    str buf[256];
    int hn;
    if ( file_exists(file_name ) )
    {
        // Open the file up
      if( !s_open_file( file_name, 0x20, hn ) )
      {
          // read the first 256 bytes
        if( !s_read_bytes( buf, hn, 256 ))
        {
					tx = xpos("\r",buf,1); // make sure we have only 1 line
					buf = copy(buf,1,tx);

            // check to see if it is a valid restore file
          if(copy(buf, 1, ME_VERSION_LENGTH) == ("@MULTI-EDIT FOR WINDOWS VERSION "  + Copy(version,1,2)))
          {
            // is so, then find the start of the session name
            jx = ME_VERSION_LENGTH;

            while( str_char( buf, ++jx ) != " " ); // skip version
            while( str_char( buf, ++jx ) == " " ); // skip spaces
						jzz1 = xpos(' ',buf,jx); 		// is there more?
						if ( jzz1 )
						{
							jzz2 = jzz1;
							--jzz1;
							while( str_char(buf, ++jzz2) != ' '); // skip path
							while( str_char(buf, ++jzz2) == ' '); // skip spaces
						}
						else
						{
							jzz1 = tx;
							jzz2 = tx;
						}
						// find the end of the session name

            if ( tx != 0 )
            {
							currentpath = copy(buf, jx, jzz1-jx);
              sessname = copy(buf, jzz2, tx-jzz2);
							if ( sessname == '' ) 						 // if not named, then...
							{
								// sessname = copy(buf, jx, tx-jx); // use pathname
								sessname = FetchSessionName(currentpath,'',0);
							}
							else
							{
								sessname = FetchSessionName(currentpath,sessname,2);
							}
            }
          }
        }
      s_close_file(hn);
      }
    }
    else		// this is a new session file - name it!
    {
      sessname = FetchSessionName(fexpand(''),'',0);
    }
  }



// --------------------------------------------------------------------------
*/

  //Put_Line( '@MULTI-EDIT FOR WINDOWS VERSION ' + remove_space(Copy(version,1,3))
  //    + '    ' + fexpand( '' ));
	if (SESSION_NAME == "") {
  	Put_Line( '@MULTI-EDIT FOR WINDOWS VERSION ' + remove_space(Copy(version,1,3))
      + '    SESS_BY_DIR=' + fexpand(''));
	} else {
  	Put_Line( '@MULTI-EDIT FOR WINDOWS VERSION ' + remove_space(Copy(version,1,3))
      + '    SESS_BY_NAME=' + session_name +
						"SESS_HOME_DIR=" + fexpand(""));
	}
	if ((restore_type == 3) && (new_session)) {
// this is for the creation of a new session by the session manager
// it creates an essentially empty status file
		goto MAKE_DUMMY;
	}

/*
	down;
	put_line("/SESSIONMGR=/SESSIONNAME=" +
			global_str("!session_name") +
			"/SESSIONDIR=" + global_str("!session_dir"));
*/
	down;

	TStr = '/MISC=1' +
					'/I=' + Str(Insert_Mode) +
					'/SC=' + Str( global_int('@SCREEN_COUNT' ) ) +
					'/CC=' + Str(  global_int('CUR_SCRN'));


    //  Save the application coordinates
  twp.length = 22;
  GetWindowPlacement( frame_handle, &twp );

  tstr += '/WP_F=' + Str(twp.flags) +
          '/WP_SC=' + Str(twp.showcmd) +
          '/WP_MNX=' + Str(twp.ptMinPos_X) +
          '/WP_MNY=' + Str(twp.ptMinPos_Y) +
          '/WP_MXX=' + Str(twp.ptMaxPos_X) +
          '/WP_MXY=' + Str(twp.ptMaxPos_Y) +
          '/WP_LT=' + Str(twp.rcNormPos_left) +
          '/WP_TP=' + Str(twp.rcNormPos_top) +
          '/WP_RT=' + Str(twp.rcNormPos_right) +
          '/WP_BT=' + Str(twp.rcNormPos_BOTTOM);


	Put_Line(Tstr);
	Down;

	Switch_Window(1);
	while(  (Cur_Window < Status_Window)  ) {
		Temp_Window = Cur_Window;
    if( (window_handle != 0) && ((window_attr & $80) == 0 ) ) {
      twp.length = 22;

			TStr = '/W=' + Str(Cur_Window) +
							'/WNM=' + window_name +
							'/A=' + Str( Cur_Window == Active_Window ) +
							'/WA=' + Str( Window_Attr ) +
							'/FN=' + File_Name +
							'/C=' + Str(C_Col) +
							'/L=' + Str(C_Line) +
							'/R=' + Str(C_Row) +
							'/IL=' + Str(Indent_Level) +
							'/WS=' + Str(Wrap_Stat) +
							'/IS=' + Str(Indent_Style) +
							'/D=' + Str(Doc_Mode) +
							'/LS=' + Str(Link_Stat) +
							'/BI=' + Str(Buffer_Id) +
							'/RM=' + Str( right_margin ) +
              '/LT=' + convert_string(line_terminator) +
              '/FLL=' + str(fixed_line_length) +
							'/SN=' + str(screen_num);

      if( GetWindowPlacement( window_handle, &twp ) )
      {
        if (window_attr & 1) {
/* for some reason GetWindowPlacement sets twp.showcmd incorrectly
 if the window is hidden*/
          twp.showcmd = sw_hide;
        }
        tstr += '/WP_F=' + Str(twp.flags) +
               '/WP_SC=' + Str(twp.showcmd) +
               '/WP_MNX=' + Str(twp.ptMinPos_X) +
               '/WP_MNY=' + Str(twp.ptMinPos_Y) +
               '/WP_MXX=' + Str(twp.ptMaxPos_X) +
               '/WP_MXY=' + Str(twp.ptMaxPos_Y) +
               '/WP_LT=' + Str(twp.rcNormPos_left) +
               '/WP_TP=' + Str(twp.rcNormPos_top) +
               '/WP_RT=' + Str(twp.rcNormPos_right) +
               '/WP_BT=' + Str(twp.rcNormPos_BOTTOM);
     }

			if(  block_stat != 0  ) {
				tstr = tstr +
							'/BS=' + Str(Block_Stat) +
							'/BC1=' + Str(Block_Col1) +
							'/BC2=' + Str(Block_Col2) +
							'/BL1=' + Str(Block_Line1) +
							'/BL2=' + Str(Block_Line2);
			}
      /*
			if(  window_color_stat  ) {
				tstr = tstr + '/WCS=1/CTC=' + str(t_color ) +
												'/CCC=' + str( c_color ) +
												'/CBC=' + str( b_color ) +
												'/CHC=' + str( h_color ) +
												'/CSC=' + str( s_color ) +
												'/CLC=' + str( l_color ) +
												'/CLBC=' + str( lb_color ) +
												'/CEC=' + str( eof_color );
			}
       */

			// Add in checking for the error windows
			if( global_int('~MEERR_ID') == window_id) {
				tstr = tstr + '/ERWN=1';
			}
			else if ( global_int('~MEERR_SPLIT_ID') == window_id) {
				tstr = tstr + '/ERSPLT=1';
			}
			/* This MUST be the last item!!!!! */
			if(  global_str('!WINZOOM#' + str(window_id)) != ''  ) {
				Tstr = tstr + '/ZOOM=' + global_str('!WINZOOM#' + str(window_id ) );
			}
			Switch_Window( Status_Window );
			Put_Line(Tstr);
			down;
			Switch_Window(temp_window);

			{		// here is where we save the position markers
				int jz, jk, line, position, row, offset;
				tstr = '';

				for( jk = 1; jk <= 3; ++jk)
					for( jz = 1; jz <= 10; ++jz ) {
						get_mark_record( jz, jk, line, position, row, offset );
						if( line > 0 ) {
							numstr = str(jz + (10 * (jk - 1))) + '=';
							tstr = tstr + '/L' + numstr + str( line ) +
													'/P' + numstr + str( position )+
													'/R' + numstr + str(  row ) +
													'/O' + numstr + str( offset );
						}
					}
				if( tstr != '') {
					jk = mark_stack_count;
					Switch_Window( Status_Window );
					Put_Line('/MARKS=' + str( jk ) + Tstr);
					down;
				}
			}
		}
		Switch_Window(Temp_Window + 1);
	}

// --------------- TESTING :  SAVE ALL TOOLBOX INFORMATION ------------------

  Switch_Window(status_window);
  SaveAllTBinfo();

// ==========================================================================

/* Save some misc. general stuff at the end */
	Switch_Window(Status_Window);

	TStr =  First_Global( jx );
Loop:
	if(  (TStr != '')  ) {
		if(  (XPOS(str_char(tstr,1),'!@.~&',1) == 0)  ) {
			if(  jx == 1  ) {
				Put_Line('/G_INT=' + TStr);  DOWN;
				Put_Line(Str(Global_int(tstr))); DOWN;
			} else {
				Put_Line('/G_STR=' + TStr);  DOWN;
				Put_Line(convert_string(Global_str(tstr))); DOWN;
			}
		}
		TStr = Next_Global(jx);
		Goto Loop;
	}

MAKE_DUMMY:
	Save_File;

/* if this is a named session, and we are exiting the editor, we
	 we need to save an identical session file by directory.
*/
	if ((restore_type == 3) &&
			(svl(SESSION_NAME)) && (parse_int("/EXITING=",mparm_str))) {
//		tof;
		erase_window;
  	Put_Line( '@MULTI-EDIT FOR WINDOWS VERSION ' + remove_space(Copy(version,1,3))
      + '    SESS_BY_DIR=' + fexpand('') +
			"SESS_CUR_NAME=" + session_name);
		file_name = make_restr_name( restore_type,"") + '.MEW';
		save_file;
/*
messagebeep(-1);
make_message("Saving " + file_name + " " + str(error_level));
while (!check_key) {
}
*/
	}

	if(  parse_int('/NDEL=',mparm_str) == 0  ) {
		Delete_Window;
	}

	Switch_Window(Active_Window);

	Refresh = True;
	Messages = true;
	Undo_Stat = true;
	GOTO END_OF_MAC;



END_OF_MAC:
	backups = temp_backup;
}