
macro_file tbmgr;

#include windows.sh
#include mew.sh
#include metools.sh
#include tbwin.sh
#include toolbox.sh
#include dialog.sh
#include db.sh
#include mewlib.sh

// for new resource loading routines
#include mew_btn.sh

#INCLUDE dbtools.sh

#DEFINE tb_icon_big        1
#DEFINE tb_icon_big_text   2
#DEFINE tb_icon_small      3
#DEFINE tb_icon_small_text 3
#DEFINE tb_icon_text       3


#define TRAIT_ICONSIZE      1
#define TRAIT_ORIENTATION   2
#define TRAIT_VISIBLE       3

#define TOOLBAR_HELPLINK "TOOLBARS//BOXES"

prototype tbmgr
{
	void display_message(str msgstr, str title, int showxicon);
	void var_replace_str(str & parm_str, str var, str new);
	void add_ufld_to_rcd(str  & datarec, str fld, str recval);
	void MODIFY_RECORD( int when,int creat,int delet,int cancl);
	str  FindTBMgrParm(str szBoxToFind, str szParmToFind);
	int  FindTBMgrIndex(int hToFind);
	int  FindTBMgrWindow(str title);
	void UpdateShownFlags();
	void ChangeTraits(str boxid, int Trait, int newTrait);

	int AddToolToToolbox(str tool, int hTb, int useicon );
	void display_message(str msgstr, str title, int showxicon);
	int continue_message(str msgstr, str title);
	void RestoreFloatTB();
	void RestoreFloatNfo(int hTBHandle, str caption);
	void SaveFloatTB();
	void SaveFloatNfo(int hTBHandle, int iconsize);
	void KillAllToolboxes();
	void KillToolbox(int tbhandle);
	void SaveAllTBinfo();
	void RestoreTBpos(int hTBHandle, str positionRec);
	int BuildToolBox(str tbtobuild, int ignoreBS, int iconsize, int orientation);
	void RecordCurrentTB();


	int  FindTBWindow(str tbtobuild);
  void AddTbHistory(int tbhandle, struct TtbSysMenuInfo , int iconsize, int orientation, str tbinfo);
	str GetTbHistory(int tbhandle);
	void KillTbHistory(int tbhandle);
	void KillTbWcmd(int tbhandle);

	void ClearSysMenuInfo(struct TtbSysMenuInfo);

	void AddPopupWcmds(struct TtbSysMenuInfo , str tbname, int hTBWindow);
	void GetPopupWcmds(struct TtbSysMenuInfo , str tbname);     // passed as reference!

	void SetCheckmarks(str tbname,int iOrientation,int iIconsize);
	void ClearCheckmarks(str tbname,int iOrientation,int iIconsize);
	void GetCheckmarks(str tbname, int htbMenu, int &iOrientation, int &iIconsize);

	void SetChkMrkBitmaps(str tbname, struct TtbSysMenuInfo);

}




global
{
	str gListOfChanges;
	str save_boxid;
	str gConfigFile;
	str gTarget_fld;
	str gToolAdded;
	str gFetchedWcmd;
	int giAddTool;
	str gtoolset;

  int savefloatcount "!savefloatcount";

	str wcmdrec "!@WCMDREC@!";
	str gFloatRec "!@gFloatRec@!";
	int ToolhelpDelay "TOOLHELPDELAY";
}


//
// this macro gets control whenever the toplevel toolbox record (in BOXLIST.DB)
// is being modified.
// Gets called: before _and_ after modification  (/P=0, /P=1)
//              once when the record is being copied
//              when the record is being created
//
macro REC_PROCESS
{

	str gls = parse_str('/GLO=',mparm_str);
	str record = global_str(gls);
	gtoolset = parse_str('BOXID=',record);

	int befaft = parse_int('/P=',mparm_str);
	int d = parse_int('/D=',mparm_str);
	int creat = parse_int('/CREATE=',mparm_str);
	int cancl = parse_int('/C=',mparm_str);
	int copying = parse_int('/COPY=',mparm_str);
	str cln = get_line;

if ( !creat )
{

	if ( d )            // delete the toolset items
	{
		int thiswinid = window_id;
		mark_pos;

		if ( LocateDBPage(wcmdmapname,gtoolset + ".TBX",FALSE) )
		{
			DEL_LINE;
			while ( !at_eof & (cur_char != '|12')  )
			{
				del_line;
			}
		}

		switch_win_id(thiswinid);
		goto_mark;

	}
	else
	{

		// allow for user to change the toolbox identifier
		// which also happens to be the page title

		if ( !befaft )           // before record is edited
		{
			save_boxid = gtoolset;

			if ( copying )
			{

				str sourcercd = global_str(parse_str('/COPYREC=',mparm_str));
				int thiswinid = window_id;
				str boxidline;
				mark_pos;

				// locate original record.
				if ( LocateDBPage(wcmdmapname,sourcercd + ".TBX",FALSE) )
				{
					int tpb = persistent_blocks;
					int insmode = insert_mode;

					insert_mode = TRUE;
					persistent_blocks = TRUE;

					down;               // move to first record
					if ( (copy(get_line,1,1) != char(12)) &&
								!at_eof ) // are there items defined?
					{
						// mark all items, copy to buffer
						block_begin;  // line marking!
						while ( (copy(get_line,1,1) != char(12)) &&
										!at_eof )
						{
							down;
						}
						up; // dont want the page break line
						block_end;

						// move to new position (create new db page)
						LocateDBPage(wcmdmapname,save_boxid + ".TBX",TRUE);
						down; // insert after title line
						// copy block
						copy_block;
					}

					persistent_blocks = tpb;
					insert_mode = insmode;
					block_off;
				}

				switch_win_id(thiswinid);
				goto_mark;

			}
		}
		else                    // after record has been edited, before update
		{
//      if ( gtoolset != save_boxid )
//      {
//        int thiswinid = window_id;
//        str boxidline;
//        mark_pos;
//
//        int located = FALSE;
//
//        located = LocateDBPage(wcmdmapname,save_boxid + ".TBX",FALSE);
//       // if ( LocateDBPage(wcmdmapname,save_boxid + ".TBX",FALSE) )
//        if ( located )
//        {
//
//
//          boxidline = get_line;
//
//          boxidline = '|12' + gtoolset + '.TBX';
//
//          put_line(boxidline);
//
//
//          down;
//
//          up;
//
//          // also change the caption in the toolbox window
//          str tstr = 'METoolbox';
//          str classname = tstr;
//          str wintext = save_boxid;
//          int hTBWnd = FindTBMgrWindow(wintext);
//          if ( hTBWnd  )
//          {
//
//            SetWindowText(hTBWnd,gtoolset); // set caption, if any
//            wintext = gtoolset;
//            ToolboxSetTitle(hTBWnd,wintext);
//
//            // we also need to change the globals
//            struct TtbSysMenuInfo newts;
//            str glovar = GetTbHistory(hTBWnd);
//            KillTbWcmd(hTBWnd);
//            GetPopupWcmds(newts, wintext);
//            AddPopupWcmds(newts, wintext, hTBWnd);
//            KillTbHistory(hTBWnd);
//            AddTbHistory(
//              hTBWnd,
//              newts,
//              parse_int('/Z=',glovar),
//              parse_int('/O=',glovar));
//            // need to update the caption
//            SendMessage(hTbWnd,WM_NCPAINT,0,0);
//          }
//          save_file;
//        }
//        switch_win_id(thiswinid);
//        goto_mark;
//        save_boxid = '';
//
//      }
		}
	}
}
}

/****************************Multi-Edit Macro********************************

 NAME:         tbmgr (toolbox manager)

 DESCRIPTION:  maintain toolboxes & tool items

 PARAMETERS:   none

 RETURNS:
							if called to directly edit a toolbox
											NOTHING
							otherwise
											NOTHING

*****************************04-28-93 09:50am*******************************/
macro tbmgr
{
	int trf = refresh;

	gListOfChanges = '';

	refresh = false;

	gConfigFile = "MECONFIG.DB";

	int this_window = window_id;

	int directedit = False;
	str tboxname = parse_str('/TBOXNAME=',mparm_str);
	if ( tboxname != '' )
	{
		directedit = True;
	}
	if ( parse_int('/PICKLIST=',mparm_str) )
	{
		// used only as a picklist

		rm('DB /LT=Select a Toolbox/PRE=TBL'+
			 '/F=' + wcmdmapname + '/DPT=BOXLIST.DB'+
			 '/BMP=BT_GN_111/HF=MEWHDRS.DB/HPT=BOXLIST.HDR/NOALPHA=1'+
			 '/NDF=1/NDH=1/GLO=TOOLSETNAME'+
			 '/LO=1'+
			 '/NC=1/NE=1/NI=1/ND=1/H='+   // no delete,create,modify,insert
			 TOOLBAR_HELPLINK
			 );
		return_str = parse_str('BOXID=',global_str('TOOLSETNAME'));
	}
	else
	{
		// update the BoxShown field for all toolboxes
		// and Iconsize
		// and orientation
		// based on this session's active toolboxes
		UpdateShownFlags();

		// edit the list of defined toolboxes or directly edit a toolbox
		db(wcmdmapname,"BOXLIST.DB",
			 "MEWHDRS.DB","BOXLIST.HDR",
			 "Toolboxes", "","TOOLSETNAME",
			 0,
			 '/PRE=TBL'+
			 '/NOALPHA=1'+
			 '/NDF=1/NDH=1'+
			 '/CANMAC=1/DELMAC=1/MOVE=1/EMAC=TbEditBox'+
	// if called to directly edit a toolbox/toolset
			 '/FV='+tboxname+
			 '/NL='+str(directedit)+
			 '/BMP=BT_GN_111/FFLD=BOXID'+
			 "/H=" + TOOLBAR_HELPLINK +
			 '/MACRO=REC_PROCESS'
			 );

	 /*
		rm('DB /LT=Toolboxes/PRE=TBL'+
			 '/F=' + wcmdmapname + '/DPT=BOXLIST.DB'+
			 '/HF=MEWHDRS.DB/HPT=BOXLIST.HDR/NOALPHA=1'+
			 '/NDF=1/NDH=1/GLO=TOOLSETNAME'+
			 '/CANMAC=1/DELMAC=1/MOVE=1/EMAC=TbEditBox'+
	// if called to directly edit a toolbox/toolset
			 '/FV='+tboxname+
			 '/NL='+str(directedit)+
			 '/FFLD=BOXID'+
			 '/MACRO=REC_PROCESS'
			 );
			 */
	}
	if( Global_Int( '@DB_FILE_CHANGED' ) || Global_Int("!*TBXTEMP.TBX"))
	{

		if ( directedit )
		{

			BuildToolbox(tboxname,FALSE, 0, 0);             // rebuild a single toolbox
			// (dont 'ignoreBS' - use boxshown field in db file)
		}
		else
		{
			rm('build_toolboxes');  // rebuild all toolboxes
			// rebuild only those toolboxes that have changed.
			// ????
		}
		Set_Global_Int("!*TBXTEMP.TBX",0);
	}
	gConfigFile = '';
	refresh = trf;
	switch_win_id(this_window);

}


void TbEditBox( )
{
	str page_title;
	str tstr = global_str("TOOLSETNAME");
	str tstr1 = global_str("TOOLSETNAME");
	str tstr2;

	int tr = refresh;

	refresh = false;
	page_title = parse_str("BOXID=", tstr) ;
	if ( page_title == '' )
	{
		page_title = 'NEW';
	}

	if ( page_title != '' )
	{

//      // find the set of tools for the corresponding toolbox, create if not exist
		if ( LocateDBPage(wcmdmapname + ".DB",page_title + ".TBX",True) )
		{
				int dlg;
				int tw = window_id,  work_win, work_win_num;
				int tid;

				create_window;
				window_attr = 0x81;
				work_win = window_id;
				work_win_num = cur_window;

        file_name = GetLongName(GetUserPath() + "TBXTEMP.TBX");

				switch_win_id( tw );
				down;
				goto_col(1);
				int jl = 0,flags,k1,k2;
				while( !at_eof && (cur_char != "\f") )
				{
					tstr = Get_Line;
					tid = parse_int("WCMD=", tstr );
					if ( tid )
					{
						Wcmd_Find( 0, tid, flags, k1,k2, tstr, tstr );
					}
					put_line_to_win( tstr, ++jl, work_win_num , false);
					down;
				}

				switch_window(work_win_num);
				tof;
				file_changed = FALSE;

				tstr = global_str("TOOLSETNAME");
				DlgCreate(dlg);

				DlgAddCtrl( dlg, DLG_BlackFrame, "",1,DLG_Units | DLG_Units_Hline,58,DLG_Units |
          ((DLG_Units_Per_Line * 3) + DLG_Units_Qline ), 3100,0, "");

				DlgAddCtrl( dlg, DLG_Static, "&Title:",2,DLG_Units | DLG_Units_Hline + 1,0,0, 3000,0, "");
				DlgAddCtrl( dlg, DLG_Text, parse_str("BOXID=", tstr),DLG_PosOffset + 7,DLG_PosOffset,14,0, 3001,0, "");

				DlgAddCtrl( dlg, DLG_CheckBox, "&Hidden",
																					9,DLG_PosOffset + 1,0,0, 3006,0, "");

        DlgAddCtrl( dlg, DLG_Static, "Sh&ow on:",2,(DLG_Units | DLG_PosOffset) | (DLG_Units_Per_Line + 2),0,0, 6000,0, "");
        DlgAddCtrl( dlg, DLG_Text, parse_str("SO=", tstr),DLG_PosOffset + 10,DLG_PosOffset,30,0, 6001,0, "");

				int tbOnScreen = FindTBMgrWindow(page_title);
				if ( tbOnScreen )
				{
					DlgSetInt( dlg, 3006, 0);
				}
				else
				{
					DlgSetInt( dlg, 3006, 1);
				}
				if ( tbOnScreen != parse_int("BOXSHOWN=",tstr) )
				{
					return_str='BOXSHOWN';
					rm('chngparm /G=TOOLSETNAME/P='+str(tbOnScreen));
					tstr = global_str('TOOLSETNAME');
				}

				DlgAddCtrl( dlg, DLG_Static, "P&osition:",28,DLG_Units | DLG_Units_Hline + 1,0,0, 3101,0, "");
				DlgAddCtrl( dlg, DLG_Choice, "Top Horizontal()Bottom horizontal()Left vertical()Right vertical()Floating()Roving()",
																					DLG_PosOffset + 10,DLG_PosOffset + 0,20,0, 3003,0, "");
				DlgSetInt( dlg, 3003, parse_int("BOXSTYLE=", tstr));

				DlgAddCtrl( dlg, DLG_Static, "St&yle:",28,DLG_PosOffset + 1,0,0, 3101,0, "");
				DlgAddCtrl( dlg, DLG_Choice, "Big icon()Small icon()",
																					DLG_PosOffset + 10,DLG_PosOffset + 0,20,0, 3007,0, "");
				int useicon = 1;
				if(parse_int("USEICON=", tstr) == 3)
					useicon = 2;
				DlgSetInt( dlg, 3007, useicon);


				db( file_name, "", "MEWHDRS.DB", "BOXEDIT.HDR",
						"Edit Toolbox", "", "TBBRECORD",
						0,
						'/NSF=1/NDF=1/NDH=1/PRE=TBB'+
						'/MOVE=1'+
						'/NOALPHA=1'+
						'/NDF=1/NDH=1'+
						'/NC=1'+
						'/NDH=1'+
						'/EMAC=SELECTCMD' +
						'/ADF=1/ADH=' + str(dlg) +
						"/H=" + TOOLBAR_HELPLINK
					 );

					 /*
				rm('DB /X=10/Y=8/LT=Edit Toolbox'+
						'/NSF=1/NDF=1/NDH=1/PRE=TBB'+
						'/MOVE=1'+
						'/F=' + file_name +
						'/HPT=BOXEDIT.HDR/HF=MEWHDRS.DB'+
						'/NOALPHA=1'+
						'/NDF=1/NDH=1'+
						'/NC=1'+
						'/NDH=1'+
						'/GLO=TBBRECORD'+
						'/EMAC=SELECTCMD' +
						'/ADF=1/ADH=' + str(dlg)+
						'/LS=2'
				);
						 */

				switch_win_id( work_win );
				work_win_num = cur_window;
				if(file_changed || global_int('!*' + truncate_path(file_name)))
				{
					set_global_int('!*' + truncate_path(file_name), 1);
					tof;
					while( !at_eof && (cur_char != "\f") )
					{
						put_line("WCMD=" + parse_str("WCMD=",get_line));
						down;
					}
					tof;
					block_begin;
					eof;
					block_end;


					if (LocateDBPage(wcmdmapname,page_title + ".TBX",True) )
					{
						undo_stat = false;
						down;
						while( !at_eof && (cur_char != "\f") )
						{
							del_line;
						}

						window_copy( work_win_num );
						undo_stat = TRUE;
					}
				}

				switch_window( work_win_num );
				delete_window;
				switch_win_id(tw);

				useicon = 1;
				if(DlgGetInt(dlg,3007) == 2)
					useicon = 3;

				tstr =
					 "BOXID=" +
				DlgGetStr( dlg, 3001 ) +
           "SO=" +
        DlgGetStr( dlg, 6001 ) +
					 "BOXSHOWN=" +
				Str((DlgGetInt( dlg, 3006 ) != 1) + 1) +
					 "BOXSTYLE=" +
				Str(DlgGetInt( dlg, 3003 )) +
					 "USEICON=" +
				str(useicon);

				set_global_str("TOOLSETNAME", tstr);

				DlgKill(dlg);

// **********************
// *** RENAME TOOLBOX ***
// **********************
				if(parse_str("BOXID=", tstr) != page_title)
				{
					str oldname = page_title;
					if (LocateDBPage(wcmdmapname,page_title + ".TBX",True) )
					{
						page_title = parse_str('BOXID=',tstr);
						str newrec = '|12' + page_title + '.TBX';
						put_line(newrec);

// ------------------------------------------------------------------------
					 {
						str boxidline;
						mark_pos;

						// also change the caption in the toolbox window
						str wintext = oldname; //page_title;
						int hTBWnd = FindTBMgrWindow(wintext);
						if ( hTBWnd  )
						{
							// first, save float info using old name
							SaveFloatNfo(hTbWnd,useicon);

							SetWindowText(hTBWnd,page_title); // set caption, if any
							wintext = page_title;
							ToolboxSetTitle(hTBWnd,wintext);

							// we also need to change the globals
							struct TtbSysMenuInfo newts;
							str glovar = GetTbHistory(hTBWnd);
							KillTbWcmd(hTBWnd);
							GetPopupWcmds(newts, wintext);
							AddPopupWcmds(newts, wintext, hTBWnd);
							KillTbHistory(hTBWnd);
							AddTbHistory(
								hTBWnd,
								newts,
								parse_int('/Z=',glovar),
                parse_int('/O=',glovar),tstr);
							// need to update the caption
							SendMessage(hTbWnd,WM_NCPAINT,0,0);
							SaveFloatNfo(hTbWnd,useicon);
						}
						save_file; // ???
					 }
// ------------------------------------------------------------------------
					}
				}


				return_int = 1;
		} // if data page located
	}
	refresh = tr;
}


void add_ufld_to_rcd(str & datarec, str field, str recval)
{
	int varpos = XPos(field, datarec, 1);
	if (varpos) {
		var_remove_str(field, datarec);
	} else {
		varpos = length(datarec) + 1;
	}
	datarec = str_ins( field + recval, datarec, varpos);
}

// called by USERIN^DB
// /F=TOOLBOX.DB
// /DPT=selected tool set id
// /HPT=BOXIDHDR'
//
// depends on globals gFetchedWcmd & gToolAdded?
//
void MODIFY_RECORD( int when = parse_int('/P=',mparm_str)
										,int creat= parse_int('/CREATE=',mparm_str)
										,int delet= parse_int('/D=',mparm_str)
										,int cancl= parse_int('/C=',mparm_str)
										// ,str gstr = parse_str('/GLO=', mparm_str)
)
{
	str gname[20] = parse_str('/GLO=',mparm_str);
	str gsval[2048] = global_str(gname);
	str page_title[8];


	switch ( when )
	{
		case  0:        // before
			if ( creat )
			{
				giAddTool = True;
				page_title = gtoolset;

			}
			break;
		case  1:        // after
			if ( gFetchedWcmd != '' )
			{
				add_ufld_to_rcd(gsval,'WCMD=',gFetchedWcmd);
				set_global_str(gname,gsval);
			}
			giAddTool = False;
			break;
	}
	giAddTool = False;

}

void var_replace_str(str & parm_str, str var, str new)
{

	int varpos = 0;

	varpos = XPos(var,parm_str,1);
	if (varpos) {
		var_remove_str(var,parm_str);
	} else {
		varpos = length(parm_str) + 1;
	}

	parm_str = str_ins( var + new,
											parm_str,
											varpos
	);
}



/****************************Multi-Edit Macro********************************

 NAME:         SELECTCMD

 DESCRIPTION:

 PARAMETERS:

 RETURNS:

*****************************04-28-93 09:51am*******************************/
macro SELECTCMD
{
	str findfield = '';
  str editToolIdx = '/FFLD=WCMD/FV='+parse_str('WCMD=',Global_Str(parse_str("/GLO=", mparm_str)));


	gFetchedWcmd = '';

	if ( !giAddTool )
	{
		findfield = editToolIdx;
	}


	RM("CommandMapEdit /LO=1" + findfield );
 /*
	// list-only, get cmd-desc only into return_str
	rm('USERIN^DB /F='+ wcmdmapname +'/DPT=WCMDMAP.DB/LT=Select Command'+
		 '/HF=MEWHDRS.DB/HPT=WCMDMAP.HDR/LO=1'+
		 '/NI=1'+
		 '/NC=1'+
		 '/NE=1'+
		 '/ND=1'+
		 '/NDF=1/NDH=1'+
		 '/U=1'+
		 '/2TOP=0'+
		 '/NOALPHA=1'+
		 '/PRE=TBLO'+
		 '/GLO=' + WCMDGloName +
		 findfield+
		 ''
	);
	*/
	// fetch wcmd from command map record
	// so it can be later stuffed into
	// the tool record
	//gFetchedWcmd = parse_str('WCMD=',global_str('WCMDRECORD'));

	//gTarget_fld = return_str;

	if(return_int)
	{
		set_global_str(parse_str('/GLO=', mparm_str), Global_Str( WCMDGloName ));
		set_global_str(WCMDGloName, '');

		if( NeedLoadWcmds )
		{
			RebuildWcmds();
		}
	}

}



int FindTBMgrWindow(str title2find)
{
	int i;
	int thandle;
	int found=FALSE;
	str foundTitle;

	int numtboxs = parse_int('/#=',global_str('!TOOLBOXES'));

	for ( i=1; i <= numtboxs; i++ )
	{
		thandle = parse_int('/H=',global_str('!TOOLBOXES'+str(i)));
		ToolboxGetTitle(thandle,foundTitle);
		if ( title2find == foundTitle )
		{
			found = TRUE;
			break;
		}
	}
	if ( found )
	{
		return (thandle);
	}
	else
	{
		return (0);
	}
}



int FindTBMgrIndex(int hToFind)
{
	int i;
	int thandle;
	int found=FALSE;
	str foundTitle;

	int numtboxs = parse_int('/#=',global_str('!TOOLBOXES'));

	for ( i=1; i <= numtboxs; i++ )
	{
		thandle = parse_int('/H=',global_str('!TOOLBOXES'+str(i)));
		if ( hToFind == thandle )
		{
			found = TRUE;
			break;
		}
	}
	if ( found )
	{
		return (i);
	}
	else
	{
		return (0);
	}
}



str FindTBMgrParm(str title2find, str szParmToFind)
{
	int i;
	int thandle;
	int found=FALSE;
	str foundParm;
	str foundTitle;

	int numtboxs = parse_int('/#=',global_str('!TOOLBOXES'));

	for ( i=1; i <= numtboxs; i++ )
	{
		thandle = parse_int('/H=',global_str('!TOOLBOXES'+str(i)));
		ToolboxGetTitle(thandle,foundTitle);
		if ( title2find == foundTitle )
		{
			found = TRUE;
			foundParm = parse_str(szParmToFind, global_str('!TOOLBOXES'+str(i)));
			break;
		}
	}
	if ( found )
	{
		return (foundParm);
	}
	else
	{
		return ('');
	}
}



void display_message(str msgstr=parse_str('/M=',mparm_str), str title=parse_str('/T=',mparm_str), int showxicon=parse_int('/S=',mparm_str))
{
#ifdef WINDOWS
	messagebox(0x0000,msgstr, title, mb_ok | showxicon);
#else
	rm('MESSAGEBOX /T='+TITLE+'/M='+MSGSTR);
#endif
}



void UpdateShownFlags()
{
	if ( global_int('RESTORE') )
	{

		str tbname;
		int i;
		int active_window = window_id;

		i = 1;
		while (
			GetDbRecord(
						wcmdmapname,  // db filename
						'BOXLIST.DB',        // data page title
						'BOXID',             // field name
						'',                  // field value
						i,                   // record # to return (overrides fv
																 //   and dbf).  Example:  If /#=3 then the
																 //   3rd record will be returned.
						1,                   // 1 = case sensitive search
						'!@tbrecord@!',      // name of global variable to store record
						false,               // if TRUE, then remove DB file from memory
																 //    after operation
						''                   // Misc parameters
																 //   /AGLO=n  name  of global integer
																 //            to store total #  of
																 //            records
																 //   /LD=str  Delimit to use, default is
																 //            ASCII 127
			) == 1
		)
		{
			int tbhandle;


			if ( (tbhandle = FindTBMgrWindow(parse_str('BOXID=',global_str('!@tbrecord@!')))) )
			{
				int tbidx = FindTbMgrIndex(tbhandle);
				int new_value;

				return_str = 'BOXSHOWN=';
				rm('CHNGPARM /G=!@tbrecord@!/P=2');    // show the window

				return_str = 'BOXSTYLE=';
				new_value = parse_int('/O=',global_str('!TOOLBOXES'+str(tbidx)));
				rm('CHNGPARM /G=!@tbrecord@!/P='+str(new_value));

				return_str = 'USEICON=';
				new_value =  parse_int('/Z=',global_str('!TOOLBOXES'+str(tbidx)));
				rm('CHNGPARM /G=!@tbrecord@!/P='+str(new_value));

			}
			else
			{
				return_str = 'BOXSHOWN=';
				rm('CHNGPARM /G=!@tbrecord@!/P=1');   // hide the window

			}


      str tval[1] = "";
      int ti = i, dbflags = _dbf_noDelWin | _dbf_Update;
			// :: putdb
      DbPutRecord(
						wcmdmapname,  // db filename
						'BOXLIST.DB',        // data page title
						'BOXID',             // field name
            tval,                  // field value
            ti,                   // record # to return (overrides fv
																 //   and dbf).  Example:  If /#=3 then the
																 //   3rd record will be returned.
            dbflags,                   // 1 = case sensitive search
            '',
            Global_Str('!@tbrecord@!')
            );
			i++;
		}
		LocateDBPage(wcmdmapname,'BOXLIST.DB',FALSE);
		SAVE_FILE;
		//DELETE_WINDOW;

		set_global_str('!@tbrecord@!','');

		switch_win_id(active_window);
	}
}


macro DoCmdLeft
{
	ChangeTraits(parse_str('/T=',mparm_str), TRAIT_ORIENTATION, 3);
}

macro DoCmdRight
{
	ChangeTraits(parse_str('/T=',mparm_str), TRAIT_ORIENTATION, 4);
}

macro DoCmdTop
{
	ChangeTraits(parse_str('/T=',mparm_str), TRAIT_ORIENTATION, 1);
}

macro DoCmdBottom
{
	ChangeTraits(parse_str('/T=',mparm_str), TRAIT_ORIENTATION, 2);
}

macro DoCmdFloating
{
	ChangeTraits(parse_str('/T=',mparm_str), TRAIT_ORIENTATION, 5);
}

macro DoCmdRoving
{
	ChangeTraits(parse_str('/T=',mparm_str), TRAIT_ORIENTATION, 6);
}

macro DoCmdBigIcon
{
	ChangeTraits(parse_str('/T=',mparm_str), TRAIT_ICONSIZE, 1);
}

macro DoCmdSmallIcon
{
	ChangeTraits(parse_str('/T=',mparm_str), TRAIT_ICONSIZE, 3);
}

macro DoCmdShowTbox
{
	messagebox(frame_handle,'docmdshowtbox','toolbox sysmenu cmd',MB_OK);
}

macro DoCmdHide
{
	ChangeTraits(parse_str('/T=',mparm_str),TRAIT_VISIBLE,1);
}

macro DoCmdShow
{
	ChangeTraits(parse_str('/T=',mparm_str),TRAIT_VISIBLE,2);
}

macro DoCmdEdit
{
	rm('tbmgr^tbmgr /TBOXNAME='+parse_str('/T=',mparm_str));
}

macro DoCmdTbMgr
{
	rm('tbmgr^tbmgr');
}

macro DoCmdCheckmarks
{
	// this may not be necessary:
	//SetCheckmarks(parse_str('/T=',mparm_str), parse_int('/MNU=',mparm_str));
}


void ChangeTraits(str boxid, int Trait, int newTrait)
{

	int actwinid = window_id;
	int trefresh = refresh;
	int tmpinsmode = insert_mode;

	int oldTrait, rdrec, nada;

	str szTraits;
	int iBoxShown, iBoxStyle, iUseIcon;
  str szBoxShown, szBoxStyle, szUseIcon,szSo;

	insert_mode = TRUE;
	refresh = false;

	rdrec = GetDbRecord(
						wcmdmapname,'BOXLIST.DB','BOXID',boxid,
											0,0, '!@gTraitRec@!',0,'');

	if ( rdrec == 1)
	{

			szBoxShown = parse_str('BOXSHOWN=',global_str('!@gTraitRec@!'));
			szBoxStyle = parse_str('BOXSTYLE=',global_str('!@gTraitRec@!'));
			szUseIcon  = parse_str('USEICON=', global_str('!@gTraitRec@!'));
      szSo  = parse_str('SO=', global_str('!@gTraitRec@!'));

			ClearCheckmarks(boxid,
				parse_int('BOXSTYLE=',global_str('!@gTraitRec@!')),
				parse_int('USEICON=', global_str('!@gTraitRec@!'))
			);

			switch(Trait)
			{
				case TRAIT_ICONSIZE :
					szUseIcon = str(newTrait);
					break;
				case TRAIT_ORIENTATION :
					szBoxStyle = str(newTrait);
					break;
				case TRAIT_VISIBLE :
					szBoxShown = str(newTrait);
					break;
				default:
					// leave it alone
					break;
			}
// BOXID=ClipboardBOXSHOWN=2BOXSTYLE=5USEICON=3
			set_global_str('!@gTraitRec@!',
												'BOXID='+boxid +
												'BOXSHOWN='+szBoxShown +
												'BOXSTYLE='+szBoxStyle +
                        'USEICON='+ szUseIcon +
                        'SO='+szSo );

      int recnum = 0, dbflags = _dbf_noDelWin | _dbf_Update;
      str tboxid[128] = boxid;
      nada = DbPutRecord(
									wcmdmapname,
									'BOXLIST.DB',
									'BOXID',
                  tboxid,
                  recnum,
                  dbflags,
                  '',
                  Global_Str('!@gTraitRec@!'));
	}
	else // rdrec is some error value
	{
		messagebox(frame_handle,'problem reading/writing '+wcmdmapname+'^BOXLIST.DB\r\nerror code'+str(rdrec),'toolbox manager error',mb_ok);
	}

	Val(iBoxShown,szBoxShown);
	Val(iBoxStyle,szBoxStyle);
	Val(iUseIcon,szUseIcon);

	BuildToolbox(boxid, FALSE, iUseIcon, iBoxStyle);
	//SetCheckMarks(boxid, iBoxStyle, iUseIcon);

	switch_win_id(actwinid);
	insert_mode = tmpinsmode;
	refresh = trefresh;
	SetToolbarUpdate( TRUE );
}



macro build_toolboxes
{

	int this_window = window_id;
	int s_refresh = refresh;
	refresh = false;


struct TtbSysMenuInfo tbPopupMenu;

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

	str mstr;
	int mcmd;
	int wcmd;
	int type;
	str keystr;
	int key;
	str keyname;
	int jx;
	int	v;
	int toolbox_handle;


	str tbname;
	str tbfont = "TIMES";
	str tbsCaption;

	int
		tbsHasCap,
		tbsStyle,
		tborientation,
		tbsuseicon,
		tb_w,tb_h,
		tbvisible;

	int tbmgrwcmd = 0;


	int tbidx;
	int tbhandle;
	int num_tbox;


	working;

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

	//ClearSysMenuInfo(tbPopupMenu);

	if ( !ToolhelpDelay )
	{
		ToolhelpDelay = 5;
	}

// any call to build_toolboxes should be preceded by Load_Wcmds
// to ensure that the any changes to icon names and wcmds
// are the latest.


	num_tbox = parse_int('/#=',global_str('!TOOLBOXES'));

	// for each toolbox defined within the system:
	//		1. destroy existing toolbox window
	//		2. destroy the tb handle
	//
	if ( num_tbox )
	{

		SaveFloatTB();

		RecordCurrentTB();  // save existing list of toolboxes
		KillAllToolboxes();

	}

	// setup db access to the ToolBox database
	return_int = 0;


	rm('MEWSYS^SETCONFIG /DB=' + wcmdmapname + '/T=BOXLIST.DB');



	int tbwinid = window_id; // toolbox.db is current window

	error_level = 0;
	if ( !return_int )
	{
		display_message(
			'Unable to access the data file',
			'ERROR: SetConfig',
			0
		);
	}
	else
	{
		down;
		goto_col(1);
		tbidx = 0;
		while( !at_eof && (cur_char != '|12'))
		{
			tbidx++;

			mstr = get_line;

			tbname = parse_str('BOXID=',mstr);

			if(tbname  != "")
			{
				tbvisible = parse_int('BOXSHOWN=',mstr) - 1;

				// create only if toolbox is visible and
				//
				if (tbvisible  )
				{

					tbsStyle = parse_int('BOXSTYLE=',mstr);
					tbsCaption = tbname; // always, regardless of being displayed or not
					tbsHasCap = FALSE;
					tborientation = tbsStyle;

					switch ( tbsStyle )
					{
						case  1 :
							tbsStyle = TBS_TOPHORIZONTAL;
							break;
						case  2 :
							tbsStyle = TBS_BOTTOMHORIZONTAL;
							break;
						case  3 :
							tbsStyle = TBS_LEFTVERTICAL;
							break;
						case  4 :
							tbsStyle = TBS_RIGHTVERTICAL;
							break;
						case  5 :
							tbsHasCap = TRUE;
							tbsStyle = TBS_FLOATING;
							break;
						case  6 :
							tbsHasCap = TRUE;
							tbsStyle = TBS_ROVING;
							break;
						default:
							tbsStyle = TBS_TOPHORIZONTAL;
							break;
					}

					tbsuseicon = parse_int('USEICON=',mstr);

					if ( tbsuseicon != tb_icon_small )
					{
						tb_w = 32;
						tb_h = 32;
					}
					else
					{
						tb_w = 22;
						tb_h = 22;
					}


					GetPopupWcmds(tbPopupMenu, tbname);     // passed as reference!

					// tbmgrwcmd = GetAvailableWcmd(tbidx);
					// set_global_int('!TBWCMD_'+str(tbidx),tbmgrwcmd);
					toolbox_handle =  ToolBoxCreate(
																		frame_handle,
																		tbsCaption,
																		(!tbsHasCap) | tbsStyle,
																		tb_w, tb_h, client_handle,
																		&tbPopupMenu          // <-- sysmenu link
														);

					if ( !toolbox_handle )
					{
						RM('MEERROR^MESSAGEBOX '+
								'/T=ERROR: ToolBox Manager'+
								'/M=Unable to create the '+caps(tbname)+ ' toolbox.');
						// set_global_int("!TBHANDLE_"+str(tbidx), 0 );
					}
					else
					{



						ToolboxSetPopupDelay(ToolHelpDelay * 100)
						if ( tbPopupmenu.wTbmgrWcmd )
						{
							// r1: macro_to_wcmd(tbmgrwcmd, 'tbmgr^tbmgr /TBOXNAME='+tbname,0);
							// r2: Wcmd_Add( 0, tbmgrwcmd, 0, 0, 0, 'tbmgr^tbmgr /TBOXNAME='+tbname, '' );
							// Wcmd_Add( 0, tbmgrwcmd, 0, 0, 0, 'tbmgr^tbmgr /TBOXNAME='+tbname, '' );
							AddPopupWcmds(tbPopupMenu, tbname, toolbox_handle);

						}

						ToolBoxSetFont( toolbox_handle, 400, 0, tbfont );

						// set_global_int("!TBHANDLE_"+str(tbidx), toolbox_handle );

						mark_pos; // save position in the toolbox.db file

						if (!search_fwd('%|12'+tbname,0))
						{
							int tbparent = GetParent(toolbox_handle);
							RM('MEERROR^MESSAGEBOX '+
									'/T=ERROR: ToolBox Manager'+
									'/M=Unable to find tools for toolbox '+caps(tbname));
							DestroyWindow( toolbox_handle );

              SendMessage(tbparent,WM_NEEDPARENTSIZE,0,0); // WM_NEEDPARENTSIZE

							// set_global_int("!TBHANDLE_"+str(tbidx), 0 );
							// tbidx--;
						}
						else
						{

							down;
							goto_col(1);
							while( !at_eof && (cur_char != '|12'))
							{
								str tool_line = get_line;

								if( parse_int("WCMD=",tool_line) != 0)
								{
									if(!AddToolToToolbox(tool_line, toolbox_handle, tbsuseicon))
									{
                  /*
										RM('MEERROR^MESSAGEBOX '+
												'/T=ERROR: Toolbox Manager'+
												'/M=Unable to add items to toolbox '+caps(tbname));
										// kill current toolbox -- handled is not saved
										DestroyWindow(toolbox_handle);
										// set_global_int("!TBHANDLE_"+str(tbidx), 0);
										// tbidx--;
										goto_mark; // restore to last record in boxlist
										down;
										goto_col(1);
										break; // out of while loop
                    */
									}
								}
								down; // next item
								goto_col(1);
							} // endwhile - processing tools
							if ( toolbox_handle )
							{
								AddTbHistory(
									toolbox_handle,
									tbPopupMenu,
									tbsuseicon,
                  tborientation,
                  mstr);
							}
							// TODO: restore floating toolbox position/state
							if ( ToolboxIsFloating(toolbox_handle)  )
							{
								RestoreFloatNfo(toolbox_handle, tbname);
							}
							if (tbvisible)
							{
								ToolBoxHide( toolbox_handle );
                if(parse_str("SO=", mstr) == "")
                  ToolboxShow(toolbox_handle);
							}
							else
							{
								ToolboxHide( toolbox_handle );
							}

						}   // endelse  - searching to toolset

						goto_mark; // restore to last record in boxlist
					}

					SetChkMrkBitmaps(tbname, tbPopupMenu);
					SetCheckMarks(tbname, tborientation, tbsuseicon);

// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

// if the WM_SETDRAW messages are going to be used, then
// kill this next line (wm_parentsize msg)
          SendMessage(frame_handle,WM_NEEDPARENTSIZE,0,0);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
				} // if visible then create
				down;
				goto_col(1);


			}
			else
			{
				down;
				goto_col(1);
			}
		}     // endwhile - processing toolboxes
		//set_global_int('!TOOLBOXES', tbidx);

		// remove any toolboxs in float.db that may have changed
		// from floating to fixed or vice-versa (adding)
		SaveFloatTB();         // <---- turn this back on???

		switch_win_id(tbwinid);
		if ( file_changed )
		{
			save_file;
		}
		// delete_window;
	}

big_exit:

// resize parent mdi client area when hiding (removing) a toolbox
  SendMessage(frame_handle,WM_NEEDPARENTSIZE,0,0);

	refresh = true;
	switch_win_id(this_window);
	refresh = s_refresh;
	error_level = 0;


 // Restore redraw
//  SendMessage( frame_handle, WM_SETREDRAW, 1, 0 );
//  SendMessage( client_handle, WM_SETREDRAW, 1, 0 );
//  RedrawWindow( client_handle, 0, 0, rdw_Invalidate );
//  RedrawWindow( frame_handle, 0, 0, rdw_Invalidate );
//   SendMessage(frame_handle,WM_USER+101,0,0); // WM_PARENTSIZE

}





int AddToolToToolbox(str tool_line, int hTb, int useicon)
{
	int result = False;
	int WM_Command_ID = parse_int("WCMD=", tool_line);
	Error_level = 0;
	if(WM_Command_ID != 0)
	{
		int hBitmapSource;
		int record_read;

		str wcmdrecx,tstr;
		int flags,k1,k2;

		if ( Wcmd_Find( 0, WM_Command_ID, flags, k1,k2, tstr, wcmdrecx ) )
		{
			str icon_name;
			str key_name;
			str cmd_name;
			str qhelp_text;
			str qhelp_link;

			if(useicon == tb_icon_small)
			{
				var_parse_str( "ICON2=", wcmdrecx, icon_name );
			}
			else
			{
				var_parse_str("ICON=", wcmdrecx, icon_name);
			}
			var_parse_str("NAME=", wcmdrecx, cmd_name);     // qhelp text + ...
			var_parse_str("/KL=", wcmdrecx, key_name);       // ... key text
			var_parse_str("H=", wcmdrecx,qhelp_link);        // help link
			qhelp_text = cmd_name;
			if ( key_name != '' )
			{
				qhelp_text = qhelp_text + ' - ' + key_name;
			}


			if( icon_name == '' )
			{
			use_text:
				// no icon defined, so check for ButtonText
//        str buttonText = parse_str("TBT=",wcmdrec);
				str buttonText = parse_str("TBT=",wcmdrecx);
				if ( buttonText == '' )
				{
					buttonText = cmd_name;
				}
				buttonText = copy(buttonText,1,20);
				int btl = svl(buttonText);
			 //	int iii;
			 //	for ( iii=0; iii < (btl>>2); iii++ )
			//	{
			//		buttonText = ' '+buttonText;
			//		buttonText = buttonText + ' ';
			//	}

				ToolBoxAddTextItem(
					hTb,                                      // handle to toolbox
					buttonText,                               // bitmap source = text
					WM_Command_ID,                            // WM_COMMAND id
					1,                                        // nXPOS
					qhelp_text,
					qhelp_link
				);

			}
			else
			{
				// fetch bitmap by searching resource list
        //hBitmapSource = FetchBitmap( MEWBTN_RT_RESNAME, icon_name );
        hBitmapSource = GetBitmapBkColor( icon_name, MEWBTN_RT_RESNAME );

				if ( hBitmapSource < 32 )
				{
					goto use_text;
				}

				ToolboxAddBitmapItem(
					hTb,
					hBitmapSource,                            // bitmap source = .bmp
					0,                                        // nXPOS
					WM_Command_ID,
					1,                                        // style
					qhelp_text,
					qhelp_link
				);

				DeleteObject( hBitmapSource );

			}

			if(!WcmdIsEnabled( 0, wm_command_id ))
			{
				ToolboxSetItemState(htb,wm_command_id,TF_BYCOMMAND,3,0);
			}
			result = True;
		}
		else
		{
			result = False;
		}
	}
	return (result);
}



void display_message(str msgstr, str title, int showxicon)
{
  messagebox(frame_handle,msgstr, title, mb_ok | showxicon);
}


int continue_message(str msgstr, str title)
{
	int response;
  response = messagebox(frame_handle,msgstr,title,mb_YesNo);

	switch ( response )
	{
    case 6: /* idOk */
			return (1);
		case 7: /* idNo */
			return (0);
		default:
      return (0);
	}
}



void SaveFloatNfo(int hTBHandle, int iconsize) // save individual float information
{
	str szTBPinfo;
	str boxid;

	if ( ToolboxIsFloating(hTBHandle) )
	{
  ++savefloatcount;

		struct TWindowPlacement FloatTBPlacement;
		FloatTBPlacement.length = 22;     // gotta do this or it DIES

		int actwinid = window_id;
		int trefresh = refresh;
		int tmpinsmode = insert_mode;
		insert_mode = TRUE;
		refresh = false;

    szTBPinfo +=  '/Z='+str(iconsize);

		ToolboxGetTitle(htbhandle,boxid);   // retrieve boxid (caption)

		GetWindowPlacement(htbhandle, &FloatTBPlacement );
		szTBPinfo = 'NAME='+boxid;
		szTBPinfo += 'Z='+str(iconsize);
		szTBPinfo +=  'FLOATBOX='+
									'/WP_F=' + Str(FloatTBPlacement.flags) +
									'/WP_SC=' + Str(FloatTBPlacement.showcmd) +
									'/WP_MNX=' + Str(FloatTBPlacement.ptMinPos_X) +
									'/WP_MNY=' + Str(FloatTBPlacement.ptMinPos_Y) +
									'/WP_MXX=' + Str(FloatTBPlacement.ptMaxPos_X) +
									'/WP_MXY=' + Str(FloatTBPlacement.ptMaxPos_Y) +
									'/WP_LT=' + Str(FloatTBPlacement.rcNormPos_left) +
									'/WP_TP=' + Str(FloatTBPlacement.rcNormPos_top) +
									'/WP_RT=' + Str(FloatTBPlacement.rcNormPos_right) +
									'/WP_BT=' + Str(FloatTBPlacement.rcNormPos_BOTTOM);

      int nada;
      str tboxid[80] = boxid;
      int dbflags = _dbf_noDelWin | _dbf_Update | _dbf_CreatePage,
          recnum = 0;

      set_global_str('!@gFloatRec@!',szTBPinfo);
      nada = DbPutRecord('MECONFIG',
                  'FLOAT.DB',
                  'NAME',
                  tboxid,
                  recnum,
                  dbflags,
                  '',
                  szTBPinfo
                  );


		switch_win_id(actwinid);
		insert_mode = tmpinsmode;
		refresh = trefresh;

	}
}



void SaveFloatTB()            // save all floating information
{
	int actwinid = window_id;
	int trefresh = refresh;

	int tmpwinid;
	int tmpinsmode = insert_mode;
	str floatfile;
	str szTBPinfo;
	int num_tbox, tbidx;
	int tbhandle;

	struct TWindowPlacement FloatTBPlacement;
	FloatTBPlacement.length = 22;     // gotta do this or it DIES

	refresh = false;
	insert_mode = TRUE;

	if ( LocateDBPage('MECONFIG',"FLOAT.DB",TRUE) )
	{
		// delete all records belonging to float.db
		//
		// after a LocateDBPage, the current line
		// in the db file is title line


		if ( read_only )
		{
			goto getouttahere;
		}


		down;       // move down to the start of the records


		goto_col(1);
		mark_pos;   // keep current position

		// delete lines until a another page title or eof is found
		while ( !at_eof && (cur_char != ''))
		{
			del_line;
		}
		goto_mark;  // return to line after page title
		cr;         // insert a line
		up;         // goto blank line
		// =====================

		num_tbox = parse_int('/#=',global_str('!TOOLBOXES'));
		tbidx = 0;

		for ( tbidx = 1; tbidx <= num_tbox; tbidx++ )
		{
			tbhandle = parse_int('/H=',global_str('!TOOLBOXES'+str(tbidx)));
			if ( tbhandle != 0 )
			{
				if ( ToolboxIsFloating(tbhandle) )
				{
					int iconsize = parse_int('/H=',global_str('!TOOLBOXES'+str(tbidx)));
					ToolboxGetTitle(tbhandle,szTBPinfo);   // retrieve boxid (caption)

					if (GetWindowPlacement(tbhandle, &FloatTBPlacement ))
					{

						szTBPinfo = 'NAME='+szTBPinfo;
						szTBPinfo += 'Z='+str(iconsize);
						szTBPinfo +=  'FLOATBOX='+
													'/WP_F=' + Str(FloatTBPlacement.flags) +
													'/WP_SC=' + Str(FloatTBPlacement.showcmd) +
													'/WP_MNX=' + Str(FloatTBPlacement.ptMinPos_X) +
													'/WP_MNY=' + Str(FloatTBPlacement.ptMinPos_Y) +
													'/WP_MXX=' + Str(FloatTBPlacement.ptMaxPos_X) +
													'/WP_MXY=' + Str(FloatTBPlacement.ptMaxPos_Y) +
													'/WP_LT=' + Str(FloatTBPlacement.rcNormPos_left) +
													'/WP_TP=' + Str(FloatTBPlacement.rcNormPos_top) +
													'/WP_RT=' + Str(FloatTBPlacement.rcNormPos_right) +
													'/WP_BT=' + Str(FloatTBPlacement.rcNormPos_BOTTOM);
						text(szTBPinfo);cr; // write record to float.db
					}
					else
					{
						display_message('unable to get floating toolbox information','error: savefloattb()',0);
					}
				}
			}
		}
		error_level = 0;
   // save_file;
   // delete_window;
getouttahere:
	}

	switch_win_id(actwinid);
	insert_mode = tmpinsmode;
	refresh = trefresh;

}



void RestoreFloatNfo(
			int hTBHandle = parse_int('/HWND=',mparm_str),
			str boxid = parse_str('/NAME=',mparm_str)
)
{
	str floatrec;

	// gFloatRec is aliased by !@gFloatRec@!
	int rdrec =
			GetDbRecord(
					'MECONFIG',       // db filename
					'FLOAT.DB',          // data page title
					'NAME',              // field name
					boxid,               // field value
					0,                   // No record # to return (overrides fv
					0,                   // No case sensitive search
					'!@gFloatRec@!',     // name of global variable to store record
					0,                   // do not remove DB file from memory
					''                   // no misc parameters
			);


	if ( rdrec == 1)
	{
		struct TWindowPlacement FloatTBPlacement;

			// Set the window placement
			FloatTBPlacement.flags = parse_int('/WP_F=', gFloatRec );
			FloatTBPlacement.showcmd = parse_int('/WP_SC=', gFloatRec );
			FloatTBPlacement.ptMinPos_X = parse_int('/WP_MNX=', gFloatRec );
			FloatTBPlacement.ptMinPos_Y = parse_int('/WP_MNY=', gFloatRec );
			FloatTBPlacement.ptMaxPos_X = parse_int('/WP_MXX=', gFloatRec );
			FloatTBPlacement.ptMaxPos_Y = parse_int('/WP_MXY=', gFloatRec );
			FloatTBPlacement.rcNormPos_left = parse_int('/WP_LT=', gFloatRec );
			FloatTBPlacement.rcNormPos_top = parse_int('/WP_TP=', gFloatRec );
			FloatTBPlacement.rcNormPos_right = parse_int('/WP_RT=', gFloatRec );
			FloatTBPlacement.rcNormPos_BOTTOM = parse_int('/WP_BT=', gFloatRec );
			FloatTBPlacement.length = 22;
			SetWindowPlacement( hTBHandle, &FloatTBPlacement );
			//ToolboxHide(hTBHandle);


		gFloatRec = '';
	}
	else
	{
		// display_message('unable to read record from float.db','testing',0);
	}
}



void RestoreFloatTB()
{
	int num_tbox, tbidx, tbhandle;
	str szCaption;

	num_tbox = parse_int('/#=',global_str('!TOOLBOXES'));
	tbidx = 0;

	for ( tbidx = 1; tbidx <= num_tbox; tbidx++ )
	{
		tbhandle = parse_int('/H=',global_str('!TOOLBOXES'+str(tbidx)));
		if ( tbhandle != 0 )
		{
			if ( ToolboxIsFloating(tbhandle) )
			{
				ToolboxGetTitle(tbhandle,szCaption);
				RestoreFloatNfo(tbhandle,szCaption);
			}
		}
	}
}


void KillAllToolboxes()
{
	int num_tbox = parse_int('/#=',global_str('!TOOLBOXES'));
	int tbhandle;
	for ( int tbidx = 1; tbidx <= num_tbox; tbidx++ )
	{
		tbhandle = parse_int('/H=',global_str('!TOOLBOXES'+str(tbidx)));
		if ( tbhandle != 0 )
		{
			DestroyWindow( tbhandle );                  // kill window
			//set_global_int('!TOOLBOXES'+str(tbidx),0);  // remove handle
			KillTbWcmd(tbhandle);
			//KillTBHistory(tbhandle);
		}
		set_global_str('!TOOLBOXES'+str(tbidx),'');
	}
	set_global_str('!TOOLBOXES','');

}

void UpdateToolboxes()
{
	int num_tbox = parse_int('/#=',global_str('!TOOLBOXES'));
  int tbhandle,jx;
	int ticount, wid, need_redraw;
  int need_childsize = FALSE;
  int tbvis;
  str tstr;

	for ( int tbidx = 1; tbidx <= num_tbox; tbidx++ )
	{
		need_redraw = 0;
    tstr = global_str('!TOOLBOXES'+str(tbidx));
    tbhandle = parse_int('/H=',tstr);
		if ( tbhandle != 0 )
		{
      tbvis = ToolBoxIsVisible(tbhandle);
      jx = xpos("/TBI=", tstr,1);
      if(jx)
      {
        tstr = parse_str( "SO=", copy(tstr,jx + 5, 255) );
        if(tstr != "")
        {
          if( !ProcessDisableString( tstr ))
          {
            if(!tbvis)
            {
              ToolBoxShow(tbhandle);
              need_childsize = TRUE;
            }
          }
          else
          {
            if(tbvis)
            {
              ToolBoxHide(tbhandle);
              need_childsize = TRUE;
              continue;
            }
          }
        }
      }
      if(!tbvis)
      {
        continue;
      }
			ticount = ToolBoxGetItemCount( tbhandle );

			while(--ticount >= 0)
			{
				wid = ToolBoxGetItemId( tbhandle, ticount );

				int oenabled = ToolboxGetItemState(tbhandle,ticount,TF_BYPOSITION,0);


				int nenabled = WcmdIsEnabled( 0, wid );
				if(nenabled)
				{
					nenabled = 1;
				}
				else
				{
					nenabled = 3;
				}

				if(nenabled != oenabled)
				{
					ToolboxSetItemState(tbhandle,ticount,TF_BYPOSITION,nenabled,0);
					need_redraw = 1;
				}

			}

			if ( need_redraw )
			{
				RedrawWindow( tbhandle, 0, 0, RDW_INVALIDATE );
			}
		}
	}
	if ( BriefMode ) {
		Rm( "BRIEF^BrSetCurWindow" );
	}
  if(need_childsize)
  {
     SendMessage(frame_handle,WM_NEEDPARENTSIZE,0,0);
  }
}  // UpdateToolboxes

void KillToolbox(tbhandle)
{
	DestroyWindow(tbhandle);
	KillTbWcmd(tbhandle);
	KillTBHistory(tbhandle);
}



// SaveAllTBinfo: writes out window information for all active toolboxes
// will write the info into the CURRENT window
// assumed to be called by EXIT^STATUS
//
void SaveAllTBinfo()
{
	int trefresh = refresh;

	int tmpwinid;
	int tmpinsmode = insert_mode;
	str floatfile;
	str szTBPinfo;
	int num_tbox, tbidx;
	int tbhandle;

	int iconsize;
	int orientation;

	struct TWindowPlacement FloatTBPlacement;
	FloatTBPlacement.length = 22;     // gotta do this or it DIES

	refresh = false;
	insert_mode = TRUE;


	num_tbox = parse_int('/#=',global_str('!TOOLBOXES'));
	tbidx = 0;

	for ( tbidx = 1; tbidx <= num_tbox; tbidx++ )
	{
		tbhandle = parse_int('/H=',global_str('!TOOLBOXES'+str(tbidx)));
		iconsize = parse_int('/Z=',global_str('!TOOLBOXES'+str(tbidx)));
		orientation = parse_int('/O=',global_str('!TOOLBOXES'+str(tbidx)));

		if ( tbhandle != 0 )
		{
			// We want ALL toolboxes for this session
			// if ( ToolboxIsFloating(tbhandle) )
			{

				ToolboxGetTitle(tbhandle,szTBPinfo);   // retrieve boxid (caption)

				if (GetWindowPlacement(tbhandle, &FloatTBPlacement ))
				{

					szTBPinfo = '/TB='+szTBPinfo;
					szTBPinfo +=  '/Z='+str(iconsize);
					szTBPinfo +=  '/O='+str(orientation);
					szTBPinfo +=
												'/WP_F=' + Str(FloatTBPlacement.flags) +
												'/WP_SC=' + Str(FloatTBPlacement.showcmd) +
												'/WP_MNX=' + Str(FloatTBPlacement.ptMinPos_X) +
												'/WP_MNY=' + Str(FloatTBPlacement.ptMinPos_Y) +
												'/WP_MXX=' + Str(FloatTBPlacement.ptMaxPos_X) +
												'/WP_MXY=' + Str(FloatTBPlacement.ptMaxPos_Y) +
												'/WP_LT=' + Str(FloatTBPlacement.rcNormPos_left) +
												'/WP_TP=' + Str(FloatTBPlacement.rcNormPos_top) +
												'/WP_RT=' + Str(FloatTBPlacement.rcNormPos_right) +
												'/WP_BT=' + Str(FloatTBPlacement.rcNormPos_BOTTOM);
					text(szTBPinfo);cr; // write record to float.db
				}
				else // this may need to be expanded or blown off
				{
					display_message('unable to get floating toolbox information','error: savefloattb()',0);
				}
			}
		}
	}
	error_level = 0;
	insert_mode = tmpinsmode;
	refresh = trefresh;
}


// given a handle to the created toolbox and
// the positioning information
// do the SetWindowPlacement
void RestoreTBpos(
			int hTBHandle = parse_int('/HWND=',mparm_str),
			str positionRec = parse_str('/POSINFO=',mparm_str)
)
{
		int 		rdrec;
		int     tbvisible;
		str 		toolbox_record;
		str			boxid;
		struct	TWindowPlacement FloatTBPlacement;

			// Set the window placement
			FloatTBPlacement.flags = parse_int('/WP_F=', positionRec );
			FloatTBPlacement.showcmd = parse_int('/WP_SC=', positionRec );
			FloatTBPlacement.ptMinPos_X = parse_int('/WP_MNX=', positionRec );
			FloatTBPlacement.ptMinPos_Y = parse_int('/WP_MNY=', positionRec );
			FloatTBPlacement.ptMaxPos_X = parse_int('/WP_MXX=', positionRec );
			FloatTBPlacement.ptMaxPos_Y = parse_int('/WP_MXY=', positionRec );
			FloatTBPlacement.rcNormPos_left = parse_int('/WP_LT=', positionRec );
			FloatTBPlacement.rcNormPos_top = parse_int('/WP_TP=', positionRec );
			FloatTBPlacement.rcNormPos_right = parse_int('/WP_RT=', positionRec );
			FloatTBPlacement.rcNormPos_BOTTOM = parse_int('/WP_BT=', positionRec );
			FloatTBPlacement.length = 22;
			SetWindowPlacement( hTBHandle, &FloatTBPlacement );
}




int BuildToolBox(str tbtobuild, int ignoreBS, int iconsize, int orientation)
{

	int this_window = window_id;
	int s_refresh = refresh;
	refresh = false;

	str mstr;
	int mcmd;
	int wcmd;
	int type;
	str keystr;
	int key;
	str keyname;
	int jx;
	int	v;
	int toolbox_handle=0;


	str tbname;
	str tbfont = "TIMES";
	str tbsCaption;

	int
		tbsHasCap,
		tbsStyle,
		tbsuseicon,
		tb_w,tb_h,
		tbvisible;

	int tbmgrwcmd = 0;


	int tbidx;
	int tbhandle;
	int num_tbox;

	struct TtbSysMenuInfo tbPopupMenu;

	working;

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


	if ( !ToolhelpDelay )
	{
		ToolhelpDelay = 5;
	}

// any call to build_toolboxes should be preceded by Load_Wcmds
// to ensure that the any changes to icon names and wcmds
// are the latest.


	num_tbox = parse_int('/#=',global_str('!TOOLBOXES'));

	// if toolbox already exists
	//    1. destroy existing toolbox window
	//		2. destroy the tb handle
	//
	if ( num_tbox )
	{

		tbhandle = FindTBWindow(tbtobuild);
		if ( tbhandle )
		{

			SaveFloatNfo(tbhandle,iconsize); // always save floating information regardless
															// of RESTORE setting
			DestroyWindow(tbhandle);
			KillTbWcmd(tbhandle);
			KillTBHistory(tbhandle);
		}

	}

	// ClearSysMenuInfo(tbPopupMenu);

	// setup db access to the ToolBox database
	return_int = 0;


	rm('MEWSYS^SETCONFIG /DB=' + wcmdmapname + '/T=BOXLIST.DB');



	int tbwinid = window_id; // toolbox.db is current window

	error_level = 0;
	if ( !return_int )
	{
		display_message(
			'Unable to access the data file',
			'ERROR: SetConfig',
			0
		);
	}
	else
	{
		down;
		goto_col(1);
		tbidx = 0;
		// find specified toolbox definition
		while( !at_eof && (cur_char != '|12'))
		{
			tbidx++;

			mstr = get_line;

			tbname = parse_str('BOXID=',mstr);

			if(tbname  == tbtobuild)
			{

				tbvisible = parse_int('BOXSHOWN=',mstr) - 1;
				tbvisible = (tbvisible || ignoreBS);
																// create regardless of tbvisible
																// if ignoreBS is true (ie restoring session)
				if( tbvisible ) // create only is toolbox is visible
				{


					tbsStyle = parse_int('BOXSTYLE=',mstr);
					tbsCaption = tbname; // always, regardless of being displayed or not
					tbsHasCap = FALSE;
					if ( ignoreBS )
					{
						tbsStyle = orientation;
					}
					else
					{
						orientation = tbsStyle;
					}
					switch ( tbsStyle )
					{
						case  1 :
							tbsStyle = TBS_TOPHORIZONTAL;
							break;
						case  2 :
							tbsStyle = TBS_BOTTOMHORIZONTAL;
							break;
						case  3 :
							tbsStyle = TBS_LEFTVERTICAL;
							break;
						case  4 :
							tbsStyle = TBS_RIGHTVERTICAL;
							break;
						case  5 :
							tbsHasCap = TRUE;
							tbsStyle = TBS_FLOATING;
							break;
						case  6 :
							tbsHasCap = TRUE;
							tbsStyle = TBS_ROVING;
							break;
						default:
							tbsStyle = TBS_TOPHORIZONTAL;
							break;
					}

					tbsuseicon = parse_int('USEICON=',mstr);
					if ( ignoreBS )
					{
						tbsuseicon = iconsize;
					}
					else
					{
						iconsize = tbsuseicon;
					}
					if ( tbsuseicon != tb_icon_small )
					{
						tb_w = 32;
						tb_h = 32;
					}
					else
					{
						tb_w = 22;
						tb_h = 22;
					}
					// ClearSysMenuInfo(tbPopupMenu);
					GetPopupWcmds(tbPopupMenu, tbname);     // passed as reference!

					// tbmgrwcmd = GetAvailableWcmd(0);
					// set_global_int('!TBWCMD_'+str(tbidx),tbmgrwcmd);
					toolbox_handle =  ToolBoxCreate(
																		frame_handle,
																		tbsCaption,
																		(!tbsHasCap) | tbsStyle,
																		tb_w, tb_h, client_handle,
																		&tbPopupMenu          // <-- sysmenu link
														);
					if ( !toolbox_handle )
					{
						RM('MEERROR^MESSAGEBOX '+
								'/T=ERROR: ToolBox Manager'+
								'/M=Unable to create the '+caps(tbname)+ ' toolbox.');
						// set_global_int("!TBHANDLE_"+str(tbidx), 0 );
					}
					else
					{
						ToolboxSetPopupDelay(ToolHelpDelay * 100)
						if ( tbPopupMenu.wTbmgrWcmd )
						{
							// r1: macro_to_wcmd(tbmgrwcmd, 'tbmgr^tbmgr /TBOXNAME='+tbname,0);
							// r2: Wcmd_Add( 0, tbmgrwcmd, 0, 0, 0, 'tbmgr^tbmgr /TBOXNAME='+tbname, '' );
							// Wcmd_Add( 0, tbmgrwcmd, 0, 0, 0, 'tbmgr^tbmgr /TBOXNAME='+tbname, '' );
							AddPopupWcmds(tbPopupMenu, tbname, toolbox_handle); // struct passed by reference
						}

						ToolBoxSetFont( toolbox_handle, 400, 0, tbfont );

						// set_global_int("!TBHANDLE_"+str(tbidx), toolbox_handle );

						mark_pos; // save position in the toolbox.db file

						if (!search_fwd('%|12'+tbname,0))
						{
							int tbparent = GetParent(toolbox_handle);
							RM('MEERROR^MESSAGEBOX '+
									'/T=ERROR: ToolBox Manager'+
									'/M=Unable to find tools for toolbox '+caps(tbname));
							DestroyWindow( toolbox_handle );

              SendMessage(tbparent,WM_NEEDPARENTSIZE,0,0);

							//set_global_int("!TBHANDLE_"+str(tbidx), 0 );
							//tbidx--;
						}
						else
						{                   //  add tool items to toolbox
							down;
							goto_col(1);
							while( !at_eof && (cur_char != '|12'))
							{
								str tool_line = get_line;
								if( parse_int("WCMD=",tool_line) != 0)
								{
									if(!AddToolToToolbox(tool_line, toolbox_handle, tbsuseicon))
									{
                    /*
										RM('MEERROR^MESSAGEBOX '+
												'/T=ERROR: Toolbox Manager'+
												'/M=Unable to add items to toolbox '+caps(tbname));
										// kill current toolbox -- handled is not saved
										DestroyWindow(toolbox_handle);
										//set_global_int("!TBHANDLE_"+str(tbidx), 0);
										//tbidx--;
										goto_mark; // restore to last record in boxlist
										down;
										goto_col(1);
										break; // out of while loop
                    */
									}
								}
								down; // next item
								goto_col(1);
							} // endwhile - processing tools
							if ( toolbox_handle )
							{
                AddTbHistory( toolbox_handle, tbPopupMenu, iconsize, orientation,mstr);
							}
							// restore floating toolbox position/state
							//
							if ( ToolboxIsFloating(toolbox_handle) &&
									 !ignoreBS )
							{
								RestoreFloatNfo(toolbox_handle, tbname);
							}
							if (tbvisible)
							{
								ToolBoxHide( toolbox_handle );
                if( parse_str("SO=", mstr) == "")
                  ToolboxShow(toolbox_handle);
							}
							else
							{
								ToolboxHide( toolbox_handle );
							}

						SetChkMrkBitmaps(tbname, tbPopupMenu);
						SetCheckMarks(tbname, orientation, iconsize);

						}   // endelse  - searching to toolset

						goto_mark; // restore to last record in boxlist
					}
						down;
						goto_col(1);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

// if the WM_SETDRAW messages are going to be used, then
// kill this next line (wm_parentsize msg)
          SendMessage(frame_handle,WM_NEEDPARENTSIZE,0,0);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

				}
				break; // the while loop *TESTING*
			}
			else
			{
				down;
				goto_col(1);
			}
		}     // endwhile - processing toolboxes

		//set_global_int('!TOOLBOXES', tbidx);

		// remove any toolboxs in float.db that may have changed
		// from floating to fixed or vice-versa (adding)
		// SaveFloatTB();


		switch_win_id(tbwinid);
		if ( file_changed )
		{
			save_file;
		}
		// delete_window;
	}

big_exit:

// resize parent mdi client area when hiding (removing) a toolbox
  SendMessage(frame_handle,WM_NEEDPARENTSIZE,0,0);

	switch_win_id(this_window);
	refresh = s_refresh;
	error_level = 0;

	return (toolbox_handle);
}




#UNDEF GDR_CASESENSITIVE 1

int FindTBWindow(str tbtofind) // search by name
{
	str tbname;
	int hresult=0;
	int ntb = parse_int('/#=',global_str('!TOOLBOXES'));
	if ( ntb )
	{
		for ( int i = 1; i <= ntb; i++ )
		{
			ToolboxGetTitle(parse_int('/H=',global_str('!TOOLBOXES'+str(i))),tbname);
			if ( tbname == tbtofind )
			{
				hresult = parse_int('/H=',global_str('!TOOLBOXES'+str(i)));
				break; // the for loop, i == index of toolbox handle
			}
		}
	}
	return (hresult);
}

void AddTbHistory(int tbhandle, struct TtbSysMenuInfo tbwcmds, int iconsize, int orientation, str tbinfo)
{
	str structHolder;

	struct_to_str(structHolder, tbwcmds);
	RETURN_STR =  '/H='+str(tbhandle)+
								'/W='+structHolder+
								'/Z='+str(iconsize)+
                '/O='+str(orientation) +
                '/TBI=' + tbinfo;
	rm('HISTORY_LIST /M=1/HISTORY=!TOOLBOXES');
}

str GetTbHistory(int tbhandle)
{
	str result = '';
	int num = parse_int('/#=',global_str('!TOOLBOXES'));
	return_int = 0;
	for ( int i = 1; i <= num; i++ )
	{
		if ( parse_int('/H=',global_str('!TOOLBOXES'+str(i))) == tbhandle )
		{
			return_int = i;
			break;
		}
	}
	if ( return_int )
	{
		result = global_str('!TOOLBOXES'+str(return_int));
	}
	return (result);
}

void KillTbHistory(int tbhandle)
{
	int num = parse_int('/#=',global_str('!TOOLBOXES'));
	for ( int i = 1; i <= num; i++ )
	{
		if ( parse_int('/H=',global_str('!TOOLBOXES'+str(i))) == tbhandle )
		{
			set_global_str('!TOOLBOXES'+str(i),'');
			return_int = i;
			RM('DELETEITEM /G=!TOOLBOXES/#='+str(num)+'/T=0');
			num--;
			if ( return_int )
			{
				set_global_str('!TOOLBOXES','/#='+str(num));
			}
			else
			{
				set_global_str('!TOOLBOXES','');
			}
			break;
		}
	}
}

void KillTbWCmd( int TbHandle ) {

	int Num = Parse_Int( "/#=", Global_Str( "!Toolboxes" ) );
	int Jx;

	struct TTbSysMenuInfo TbWCmds;

	str GloVarVal;

	for ( Jx = 1; Jx <= Num; ++Jx ) {
		GloVarVal = Global_Str( "!Toolboxes" + Str( Jx ) );
		if ( Parse_Int( "/H=", GloVarVal ) == TbHandle ) {
			GloVarVal = Parse_Str( "/W=", GloVarVal );
			Str_To_Struct( TbWCmds, GloVarVal );

			ReleaseWcmd( TbWCmds.wTBmgrLeft );
			ReleaseWcmd( TbwCMds.wTBmgrRight );
			ReleaseWcmd( TbwCMds.wTBmgrTop );
			ReleaseWcmd( TbwCMds.wTBmgrBottom );
			ReleaseWcmd( TbwCMds.wTBmgrFloating );
			ReleaseWcmd( TbwCMds.wTBmgrRoving );
			ReleaseWcmd( TbwCMds.wTBmgrBigIcon );
			ReleaseWcmd( TbwCMds.wTBmgrSmallIcon );
			ReleaseWcmd( TbwCMds.wTBmgrShowTbox );
			ReleaseWcmd( TbwCMds.wTBmgrHide );
			ReleaseWcmd( TbwCMds.wTBmgrEdit );
			ReleaseWcmd( TbwCMds.wTbmgrWcmd );
			ReleaseWcmd( TbwCMds.wTbmgrCheckmarks );
		}
	}
}  // KillTbWCmd

void RecordCurrentTB()
{
	str listOfTB = '';
	str title;
	int num = parse_int('/#=',global_str('!TOOLBOXES'));
	listOfTB = global_str('!TOOLBOXES');
	for ( int i = 1; i <= num; i++ )
	{
		ToolboxGetTitle(parse_int('/H=',global_str('!TOOLBOXES'+str(i))),title);
		listOfTB += '/'+str(i)+'='+title;
	}
	set_global_str('!@LISTOFTB@!',listOfTB);

	// looks like :  "/#=3/1=Main/2=Search/3=Clipboard"
}

void AddPopupWcmds(struct TtbSysMenuInfo ts, str tbname, int hTBWindow)
{
	int htbsysmenu= 0;

// Wcmd_Add( 0, tbmgrwcmd, 0, 0, 0, 'tbmgr^tbmgr /TBOXNAME='+tbname, '' );
	Wcmd_Add( 0, ts.wTBmgrLeft,      0, 0, 0, 'tbmgr^DoCmdLeft /T='+tbname, '');
	Wcmd_Add( 0, ts.wTBmgrRight,     0, 0, 0, 'tbmgr^DoCmdRight /T='+tbname, '');
	Wcmd_Add( 0, ts.wTBmgrTop,       0, 0, 0, 'tbmgr^DoCmdTop /T='+tbname, '');
	Wcmd_Add( 0, ts.wTBmgrBottom,    0, 0, 0, 'tbmgr^DoCmdBottom /T='+tbname, '');
	Wcmd_Add( 0, ts.wTBmgrFloating,  0, 0, 0, 'tbmgr^DoCmdFloating /T='+tbname, '');
	Wcmd_Add( 0, ts.wTBmgrRoving,    0, 0, 0, 'tbmgr^DoCmdRoving /T='+tbname, '');
	Wcmd_Add( 0, ts.wTBmgrBigIcon,   0, 0, 0, 'tbmgr^DoCmdBigIcon /T='+tbname, '');
	Wcmd_Add( 0, ts.wTBmgrSmallIcon, 0, 0, 0, 'tbmgr^DoCmdSmallIcon /T='+tbname, '');
	Wcmd_Add( 0, ts.wTBmgrShowTbox,  0, 0, 0, 'tbmgr^DoCmdShowTbox /T='+tbname, '');
	Wcmd_Add( 0, ts.wTBmgrHide,      0, 0, 0, 'tbmgr^DoCmdHide /T='+tbname, '');
	//Wcmd_Add( 0, ts.wTBmgrEdit,      0, 0, 0, 'tbmgr^tbmgr /TBOXNAME='+tbname, '');
	Wcmd_Add( 0, ts.wTBmgrEdit,      0, 0, 0, 'tbmgr^DoCmdEdit /T='+tbname, '');
	Wcmd_Add( 0, ts.wTbmgrWcmd,      0, 0, 0, 'tbmgr^DoCmdTbMgr /T='+tbname, '');

	htbsysmenu = ToolboxGetMenu(hTBWindow);

	Wcmd_Add( 0, ts.wTbmgrCheckmarks,0, 0, 0,
						'tbmgr^DoCmdCheckmarks /T='+tbname + '/MNU='+ str(htbsysmenu),
						 '');
}

void GetPopupWcmds(struct TtbSysMenuInfo ts, str tbname)
{
	// checks toolbox global variables for existing wcmds and uses those,
	// otherwise, will return a new wcmd that is available.

	// int currentWcmd = parse_int('/W=',global_str('!TOOLBOXES'+str(tbidx)));

	struct TtbSysMenuInfo tbwcmds;
	str glovarVal;
	int tbidx = 0;

	tbidx = FindTBWindow(tbname);
	glovarVal = parse_str('/W=',global_str('!TOOLBOXES'+str(tbidx)));
	if ( glovarVal == '' )
	{
		ClearSysMenuInfo(tbwcmds);
	}
	else
		str_to_struct(tbwcmds,glovarVal);

	ts.wTBmgrLeft       = GetAvailableWcmd(tbwcmds.wTBmgrLeft, 0);
	ts.wTBmgrRight      = GetAvailableWcmd(tbwcmds.wTBmgrRight,
																							ts.wTBmgrLeft);
	ts.wTBmgrTop        = GetAvailableWcmd(tbwcmds.wTBmgrTop,
																							ts.wTBmgrRight);
	ts.wTBmgrBottom     = GetAvailableWcmd(tbwcmds.wTBmgrBottom,
																							ts.wTBmgrTop);
	ts.wTBmgrFloating   = GetAvailableWcmd(tbwcmds.wTBmgrFloating,
																							ts.wTBmgrBottom);
	ts.wTBmgrRoving   = GetAvailableWcmd(tbwcmds.wTBmgrRoving,
																							ts.wTBmgrFloating);
	ts.wTBmgrBigIcon    = GetAvailableWcmd(tbwcmds.wTBmgrBigIcon,
																							ts.wTBmgrRoving);
	ts.wTBmgrSmallIcon  = GetAvailableWcmd(tbwcmds.wTBmgrSmallIcon,
																							ts.wTBmgrBigIcon);
	ts.wTBmgrShowTbox   = GetAvailableWcmd(tbwcmds.wTBmgrShowTbox,
																							ts.wTBmgrSmallIcon);
	ts.wTBmgrHide       = GetAvailableWcmd(tbwcmds.wTBmgrHide,
																							ts.wTBmgrShowTbox);
	ts.wTBmgrEdit       = GetAvailableWcmd(tbwcmds.wTBmgrEdit,
																							ts.wTBmgrHide);
	ts.wTbmgrWcmd       = GetAvailableWcmd(tbwcmds.wTBmgrWcmd,
																							ts.wTBmgrEdit);
	ts.wTbmgrCheckmarks = GetAvailableWcmd(tbwcmds.wTBmgrCheckMarks,
																							ts.wTBmgrWcmd);
}

void ClearSysMenuInfo(struct TtbSysMenuInfo tbwcmds)
{
	tbwcmds.wTBmgrLeft = 0;
	tbwcmds.wTBmgrRight = 0;
	tbwcmds.wTBmgrTop = 0;
	tbwcmds.wTBmgrBottom = 0;
	tbwcmds.wTBmgrFloating = 0;
	tbwcmds.wTBmgrRoving = 0;
	tbwcmds.wTBmgrBigIcon = 0;
	tbwcmds.wTBmgrSmallIcon = 0;
	tbwcmds.wTBmgrShowTbox = 0;
	tbwcmds.wTBmgrHide = 0;
	tbwcmds.wTBmgrEdit = 0;
	tbwcmds.wTbmgrWcmd = 0;
	tbwcmds.wTbmgrCheckmarks = 0;
}

void GetCheckmarks(str tbname, int &iOrientation, int &iIconsize)
{
	str szOrientation = FindTbmgrParm(tbname, '/O=');
	str szIconsize    = FindTbmgrParm(tbname, '/Z=');

	Val(iOrientation,szOrientation);
	Val(iIconsize,   szIconsize);

}

void SetCheckmarks(str tbname, int iOrientation, int iIconsize)
{
	int htb = FindTBWindow(tbname);
	int hpu = ToolboxGetMenu(htb);


	struct TtbSysMenuInfo ts;
	str glovarVal;
	int tbidx = 0;

	tbidx = FindTBWindow(tbname);
	glovarVal = FindTBMgrParm(tbname,'/W=');

	if ( glovarVal == '' )
	{
		ClearSysMenuInfo(ts);
	}
	else
		str_to_struct(ts,glovarVal);


	switch ( iOrientation )
	{
		case 1 :
			CheckMenuItem(hpu, ts.wTBmgrTop, MF_BYCOMMAND | MF_CHECKED);
			break;
		case 2 :
			CheckMenuItem(hpu, ts.wTBmgrBottom, MF_BYCOMMAND | MF_CHECKED);
			break;
		case 3 :
			CheckMenuItem(hpu, ts.wTBmgrLeft, MF_BYCOMMAND | MF_CHECKED);
			break;
		case 4 :
			CheckMenuItem(hpu, ts.wTBmgrRight, MF_BYCOMMAND | MF_CHECKED);
			break;
		case 5 :
			CheckMenuItem(hpu, ts.wTBmgrFloating, MF_BYCOMMAND | MF_CHECKED);
			break;
		case 6 :
			CheckMenuItem(hpu, ts.wTBmgrRoving, MF_BYCOMMAND | MF_CHECKED);
		default:
			break;
	}
	switch ( iIconsize )
	{
		case 1 :
			CheckMenuItem(hpu, ts.wTBmgrBigIcon, MF_BYCOMMAND | MF_CHECKED);
			break;
		case 3 :
			CheckMenuItem(hpu, ts.wTBmgrSmallIcon, MF_BYCOMMAND | MF_CHECKED);
			break;
		default:
			break;
	}
}

void ClearCheckmarks(str tbname, int iOrientation, int iIconsize)
{
	int htb = FindTBWindow(tbname);
	int hpu = ToolboxGetMenu(htb);

	struct TtbSysMenuInfo ts;
	str glovarVal;
	//int tbidx = 0;

	//tbidx = FindTBWindow(tbname);
	glovarVal = FindTBMgrParm(tbname,'/W=');

	if ( glovarVal == '' )
	{
		ClearSysMenuInfo(ts);
	}
	else
		str_to_struct(ts,glovarVal);


	switch ( iOrientation )
	{
		case 1 :
			CheckMenuItem(hpu, ts.wTBmgrTop, MF_BYCOMMAND | MF_UNCHECKED);
			 break;
		case 2 :
			CheckMenuItem(hpu, ts.wTBmgrBottom, MF_BYCOMMAND | MF_UNCHECKED);
			break;
		case 3 :
			CheckMenuItem(hpu, ts.wTBmgrLeft, MF_BYCOMMAND | MF_UNCHECKED);
			break;
		case 4 :
			CheckMenuItem(hpu, ts.wTBmgrRight, MF_BYCOMMAND | MF_UNCHECKED);
			break;
		case 5 :
			CheckMenuItem(hpu, ts.wTBmgrFloating, MF_BYCOMMAND | MF_UNCHECKED);
			break;
		case 6 :
			CheckMenuItem(hpu, ts.wTBmgrRoving, MF_BYCOMMAND | MF_UNCHECKED);
		default:
			break;
	}
	switch ( iIconsize )
	{
		case 1 :
			CheckMenuItem(hpu, ts.wTBmgrBigIcon, MF_BYCOMMAND | MF_UNCHECKED);
			break;
		case 3 :
			CheckMenuItem(hpu, ts.wTBmgrSmallIcon, MF_BYCOMMAND | MF_UNCHECKED);
			break;
		default:
			break;
	}

}

void SetChkMrkBitmaps(str tbname, struct TtbSysMenuInfo ts)
{
//  int htb = FindTBWindow(tbname);
//  int hpu = ToolboxGetMenu(htb);
//
//  int dwCheckSize = GetMenuCheckMarkDimensions();
//
//  // we need equivalent loword and hiword functions:
//  int nBx = LOWORD(dwCheckSize);
//  int nBy = HIWORD(dwCheckSize);
//
//  int hDC = GetDC(htb);
//  int hSourceDC = CreateCompatibleDC(hDC);
//
//  // we need the instance handle of application here:
//  int hPenBitmap = LoadBitmap(ghInstance, 'CHKMRK1');
//
//  SelectObject(hSourceDC, hPenBitmap);
//
//  // need cmacw 'sizeof' function
//  // use proper cmacw syntax for &
//  GetObject(hPenBitmap, sizeof(BITMAP), (LPSTR)&bm);
//
//  int hDestDC = CreateCompatibleDC(hDC);
//  int hMemBitmap = CreateCompatibleBitmap(hDestDC, nBx, nBy);
//  SelectObject(hDestDC, hMemBitmap);
//  StretchBlt(hDestDC, 0, 0, nBx, nBy, hSourceDC, 0, 0,
//            bm.bmWidth, bm.bmHeight, SRCCOPY);
//
//  // this needs to be prototyped:
//  // for each menu item:
//  SetMenuItemBitmaps(hMenu, ITEM_ID, MF_BYCOMMAND, NULL, hMemBitmap);
//
//  ReleaseDC(htb,hDC);
//  DeleteDC(hSourceDC);
//  DeleteDC(hDestDC);
//  DeleteObject(hPenBitmap);

}