 // $Header: /MEWIN/SRC/EXIT.S 100   3/27/96 12:09 Dan $

macro_file EXIT;

#include windows.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
#INCLUDE mewlib.sh
#include hex.sh

#ifdef _Debug_
  #include MSGLOG.SH
#endif

#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
{
  int j;
  int maxitems;
//  msglog (1, "Save", dlg, message, wparam, lparam);
	switch ( message )
	{
		case WM_COMMAND :
			switch ( wparam )
			{
				case 100 :
          int jy    = window_id;
          int blarg = LBGetSelectCount(GetDlgItem(dlg, 1000));
          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 101 :
				case 102 :
        case DLG_WCMD_INIT :
          int flag;

          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 WM_SysCommand :
        if ( wparam == SC_CLOSE)
					return (0);
	}
	return(DlgMessageProc(retval, dlg, message,wparam,lparam, parms ));
}

void Exit (no_prompt = Parse_Int("/NP=", mparm_str ),
           no_exit   = Parse_Int( "/NE=", mparm_str)) 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.
              /NE=  If 1, do not quit, used for session manager
                    If 2, do everything to Exit but the actual quit.

							 (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 for running tasks
  Rm( "QueryRunTasks /P=1" );
  if ( Return_Int == True ) {
    Return_Int = False;
    goto End_Of_Mac;
  }

	// Save the window position
	struct TWindowPlacement twp;
	twp.length = 22;
	GetWindowPlacement( frame_handle, &twp );

	temp_string = '/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(LocateDbPage("MECONFIG", "POSITION.CFG", TRUE ))
	{
		down;
		goto_col(1);
		if(cur_char == "\f")
		{
			up;
			eol;
			cr;
		}
		if(get_line != temp_string)
			put_line(temp_string);
	}


	// 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 there are any unsaved files, make a warning box */
  if( Not_Saved) {
    if (no_prompt) {
      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;
		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 ( BtnOnRight )  {
      BtnOnRight = 1;
    }
  	int fn_width;
  	if ( UseLongnames )
  	{                    // if  longnames use a wider width
    	fn_width = 40;
  	} else {
    	fn_width = 20;
		}

		int bw  = Dlg_StanBtnWidth;
		int bww = bw + 2;
		int w = 40 + fn_width;
    int dlg;

    DlgCreate(dlg);
    DlgAddCtrl( dlg, DLG_Icon, "IC_QUESTION",
      3 + (BtnOnRight * (w + 1)), 1, 0, 0,
      2010, 0, "" );
    DlgAddCtrl( dlg, DLG_Static, "Save modified files?",
      bww - ((bww - 1) * BtnOnRight), 1, 0, 0,
      2000, 0, "");
    DlgAddCtrl( dlg, DLG_ListBox,"WN=/W=12FN=/W=" + str (fn_width) + "FP=/W=255",
      bww - ((bww - 1) * BtnOnRight), DLG_PosOffset + 1, w, 4,
      1000, DLGF_LB_HSCROLL | DLGF_LB_EXTENDEDSEL, "/HSCROLL=" + str(MaxLength + fn_width + 20) + "/WIN=" + str(cur_window));
    DlgAddCtrl( dlg, DLG_PushButton, "&All",
      1 + (BtnOnRight * (w + 1)), DLG_PosOffset + 1, bw, 0,
      101, 0, "");
    DlgAddCtrl( dlg, DLG_PushButton, "N&one",
      Dlg_PosOffset, DLG_PosOffset + (DLG_Units | 15), bw, 0,
      102, 0, "");
    DlgAddCtrl( dlg, DLG_PushButton, "&Yes",
      bww - ((bww - 1) * BtnOnRight), DLG_PosOffset + 2, bw, 0,
      100, DLGF_DefButton, "/R=1");
    DlgAddCtrl( dlg, DLG_PushButton, "&No",
      DLG_PosOffset + bww, DLG_PosOffset, bw, 0,
      104, 0, "/R=3");
    DlgAddCtrl( dlg, DLG_PushButton, "Cancel",
      DLG_PosOffset + bww, DLG_PosOffset, bw, 0,
      103, 0, "/R=0");
    DlgAddCtrl( dlg, DLG_PushButton, "&Help",
      (bww * (BtnOnRight ^ 1)) + (w + 1) - bww, DLG_PosOffset, bw, 0,
      105, 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 /EXITING=" + str((no_exit == 0) || (no_exit == 2)));


    if ( no_exit == 1 ) {
      KillAllToolboxes();
    }
  }
	refresh = false;
  if( (no_exit == 2) || (no_exit == 0))
	{
		Rm( "ExecShutdown" );
	}
  if ( no_exit == 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;

	Restore_Path = AddTrailingSlash(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\
*/

	Dir_Spec = RemoveTrailingSlash(Dir_Spec);

	RETURN(dir_spec);
}


void RestoreScreenPos( str tstr, int showcmd )
{
	struct TWindowPlacement masterwp,twp;
		//  Save the application coordinates
	twp.length = 22;
	GetWindowPlacement( frame_handle, &twp );

	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(!((masterwp.rcNormPos_Bottom <= masterwp.rcNormPos_Top) ||
		(masterwp.rcNormPos_Right <= masterwp.rcNormPos_Left)))
	{
		masterwp.showcmd = SW_SHOWNA;
		if( showcmd != -1)
			masterwp.showcmd = showcmd;
		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;
	}
}


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
            /SD=    The working directory for sessions, "" defaults to current
                    working directory.

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,  Temp_Window,
      X1, Y1, X2, Y2,count, t_sc,
      new_screen_setup= 0,
      Active_Window   = 0,
      trestore        = global_int("@RESTORE"),
      restore_mode    = parse_int("/M=", mparm_str),
      bid_count       = 0,
      new_screen_layout = 0,
      main_showcmd    = -1,
      orig_showcmd,
      TInsert_Mode    = Insert_Mode,
      session_switch  = parse_int("/SS=",mparm_str);

  str TStr[ Max_Line_Length ],
			tstr2[1024], numstr[20];
  str SessName        = parse_str("/SN=",mparm_str);
  str SessName2       = "";
  str CurrentPath     = Parse_Str( "/SD=", MParm_Str );

	struct TWindowPlacement twp, masterwp;

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

  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 ( Caps( File_Name ) != "?NO-FILE?" ) {
    Active_Window = Window_Id;
    Create_Window;
  }

Load_Named:
  Load_File( Make_Restr_Name( Global_Int( "@Restore" ), SessName2 ) + ".MEW" );

	Truncate_Spaces = Temp_Integer;
	Status_Window = Cur_Window;
  if ( Error_Level != 0 ) {
    Temp_Integer = Error_Level;
    Refresh = TRUE;
		Error_Level = 0;

    Rm( "WINDOW^DelWin /NB=1" );

    if ( Temp_Integer == 3002 ) {
      if ( Svl( SessName ) ) {
        Set_Global_Str( "!Session_Name", SessName );
        Rm( "Status /NEW=1/SD=" + CurrentPath );
			}
			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;
	}
	tstr = remove_space(caps(copy(get_line,1,36)));
	if(  tstr != remove_space('@MULTI-EDIT FOR WINDOWS VERSION ' + Copy(version,1,3))  ) {
		if(tstr != remove_space('@MULTI-EDIT FOR WINDOWS VERSION 7.0'))
		{
			refresh = TRUE;
			Rm( "WINDOW^DelWin /NB=1" );
			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;


			int xxwin;
			if(LocateDBPage( "MECONFIG", "SESSMGR.CFG", TRUE ) )
			{
				xxwin = cur_window;
				if (!read_only && (caps( sessname ) != caps(get_line) ))
				{
					mark_pos;
					down;
					goto_col(1);
					while(!at_eof && (cur_char != "\f"))
					{
						del_line;
					}
					goto_mark;
					Insert_Mode = True;
					eol;
					cr;
					put_line( sessname );
					Insert_Mode = TInsert_Mode;
				}
				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(RemoveTrailingSlash((currentpath)));  // optional home dir for named sessions
        // check for a blank status file
				down;
				if (at_eof) {
					Rm( "WINDOW^DelWin /NB=1" );
					rm('tbmgr^build_toolboxes');
					RestoreResult = True;
					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;
				window_name = Parse_Str('/WNM=', tstr);
        File_Name   = Parse_Str('/FN=',TStr);
				Window_Attr = Parse_Int('/WA=',TStr);
				Make_Window_Visible (1);
        Temp_Window  = Cur_Window;
        // 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)));
							HexSetEvent( TRUE, temp_integer, 0 );
							temp_integer = window_id;
							switch_window(temp_window);
							HexSetEvent( TRUE, temp_integer, 0 );
						}
          }
          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:
					filetype_override = 255;
					if(parse_str('/LT=', tstr) != "" )
					{
						line_terminator = reconvert_string(parse_str('/LT=', tstr ));
						filetype_override = 0;
					}
					fixed_line_length = parse_int("/FLL=", tstr );
					if(  (File_Name != '?No-File?')  ) {
						XLoad_File(File_Name);
					}
					RM( 'EXTSETUP /FTO=255');
				}

				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));
        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) );
								//Restore the bookmarks here.
              tstr2 = Parse_Str( "/B" + NumStr, TStr );
              Set_Global_Str( "!BOOKMARK_" + Str( Buffer_Id ) + str( Jz ), tstr2 );
              if ( Copy( tstr2, 1, 1 ) == "G" ) {
								Set_Global_Int( "!GBookMark_" + Str( Jz ), Window_Id );
							}
						}
					}
			} 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) || (orientation == 6))) {
						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 ( Restore_Mode ) {
    /* if partial restore, we don't want to overwrite the named session status
       file upon exit */
    Set_Global_Str( "!Session_Name", "" );
	}
}  // Restore

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),
        TInsert_Mode  = Insert_Mode;
  str TStr[ Max_Line_Length ], numstr[20];
  str Session_Name  = Global_Str( "!Session_Name" );
  str Session_Name2 = "";
  str CurrentDir    = Parse_Str( "/SD=", MParm_Str );

  if ( ( Restore_Flags & _rest_SavNamedOnly ) && ( Svl( Session_Name ) == 0 ) ) {
    return ( );
  }

	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;
				Insert_Mode = True;
        Eol;
        Cr;
        Put_Line( Session_Name );
				Insert_Mode = TInsert_Mode;
        Save_File;
			}
      Switch_Window( Status_Window );
		}
    Session_Name2 = "0:" + Session_Name;
  }
  else {
    Session_Name = "";
	}

  File_Name = Make_Restr_Name( Restore_Type, Session_Name2) + ".MEW";

  if ( Svl( CurrentDir ) == 0 ) {
    CurrentDir = FExpand( "" );
  }
  if ( Svl( Session_Name ) == 0 ) {
    Put_Line( "@MULTI-EDIT FOR WINDOWS VERSION " +
        Remove_Space( Copy( Version, 1, 3 ) ) +
        "    \x7F" + "SESS_BY_DIR=" + CurrentDir );
  }
  else {
    Put_Line( "@MULTI-EDIT FOR WINDOWS VERSION " +
        Remove_Space( Copy( Version, 1, 3 ) ) +
        "    \x7F" + "SESS_BY_NAME=" + Session_Name +
        "\x7F" + "SESS_HOME_DIR=" + CurrentDir );
	}
  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;

	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 +
              '/OA='  + Str(Get_Oem_Ansi (Cur_Window)) +
              '/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);
			}
			// 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';
			}
			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 += "/L" + numstr + str( line ) +
									'/P' + numstr + str( position )+
									'/R' + numstr + str(  row ) +
									'/O' + numstr + str( offset ) +
                  '/B' + numstr + Global_Str( "!BOOKMARK_" + Str( Buffer_Id ) + str( Jz ) );
									// Added the above line for SAVING the bookmarks
						}
					}
				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:
  if ( ( File_Attr( File_Name ) & 0x01 ) == 0 ) {
    Save_File;
  }
  Error_Level = 0;

  /* if this is a named session, and we are exiting the editor,
     we need to save an identical session file by directory.
  */
  if ( ( Restore_Type == 3 ) && ( Svl( Session_Name ) ) &&
      ( Parse_Int( "/EXITING=", MParm_Str ) ) )
  {
    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;
	}
  if ( Parse_Int( "/NDEL=", MParm_Str ) == 0  ) {
		Delete_Window;
	}
  Switch_Window( Active_Window );

  Refresh   = True;
  Messages  = true;
	Undo_Stat = true;

End_Of_Mac:
  Backups = Temp_Backup;

}  // Status
