
macro_file fprompt;
#include windows.sh
#include commdlg.sh
#include metools.sh
#include fprompt.sh
#include mewhelp.sh
#include mewlib.sh
#include dialog.sh
#include mail.sh
#include exit.sh
#include mew.sh
#include mew_btn.sh
// #include msglog.sh
#include mew_dlgs.sh
#include shellapi.sh

#DEFINE FILEMGR_HELPLINK "FILE MANAGER OPERATIONS"
#DEFINE win32x_file user_path + "MEW32X.INI"
#define HKEY_CURRENT_USER           0x80000001

#DEFINE _FN_ID        1152
#DEFINE _FL_ID        1120
#DEFINE _FP_DIR_LIST_ID 1121
#DEFINE _FP_OK        1
#DEFINE _FP_CANCEL    2
#DEFINE _FP_DIR_ID    1088
#DEFINE _FP_EXT_ID    1136
#DEFINE _FP_DRIVES_ID 1137
#DEFINE _FP_HELP_ID   1038
#DEFINE _FP_RO_ID     1040
#DEFINE _FP_OEM_ID    1041
#DEFINE _FP_FT        5000
#DEFINE _FP_FT_TITLE  1081
#DEFINE _FP_SEL_ALL   5020
#DEFINE _FP_SEL_NONE  5021
#DEFINE _FP_WORK_ID     5300
#DEFINE _FP_WORK_CHANGE 5350
#DEFINE _FP_WORK_VIEW   5351
#DEFINE _FP_FILE_ID     5352
#DEFINE _FP_OP_COPY     6001
#DEFINE _FP_OP_MOVE     6002
#DEFINE _FP_OP_RENAME   6003
#DEFINE _FP_OP_DELETE   6004
#DEFINE _FP_OP_SEND     6005
#DEFINE _FP_OP_CREATE_DIR 6006
#DEFINE _FP_OP_ATTRIBUTE 6007

#DEFINE WM_FPVALIDATEDIR 0x420
#DEFINE WM_FPUPDATE      0x421
#DEFINE WM_FPUPDATE2     0x422



#DEFINE _FA_ReadOnly      0x01
#DEFINE _FA_Hidden        0x02
#DEFINE _FA_System        0x04
#DEFINE _FA_VolumeID      0x08
#DEFINE _FA_Directory     0x10
#DEFINE _FA_Archive       0x20

#define _LN_PLACEHOLDER "_MEWLONGNAMEPLACEHOLDER_.TP_"

global
{
	str fprompt_file_info "!FPROMPT_FILE_INFO";
	str file_seperator "!file_seperator";
	int fpNeedDirList "!FPNeedDirList";
	int fpNeedFileList "!FPNeedFileList";
}


struct fileprompt_rec
{
	asciiz filespec[max_line_length],
         filetitle[260],
				 customfilter[1024],
				 template[20];

}


int FileNameClassic( str &fn, str &title,
										str &history, str &help,
										int &flags  ) trans2
{
  str filters[max_line_length], tstr2, tstr3, ext, ext2;


	struct TOpenFileName oprec;
	struct fileprompt_rec fnr;

	int result,
			tw  = window_id,
			tr = refresh,
			filterindex = 0,
			filtercount = 1,
			no_spec = 0,
			jx,jy;

	refresh = FALSE;

	if(UseLongNames /* &&
		((GetVersion & 0x0000FF00) == 0x005F00 ) */ )
	{
		file_seperator = ';';

	}
	else
	{
		file_seperator = ' ';
	}


	if ((fn == "") || (caps(fn) == "?NO-FILE?")) {
		no_spec = 1;
		fn = fprompt_last_path;
		if (fn == "") {
			fn = "*.*";
		}
	}
	if(Get_Path(fn) == "")
	{
		fn=Get_Path(fprompt_last_path) + fn;
	}

	ext2 = lower(get_extension( fn ));
	if(jx = xpos(";", ext2, 1))
	{
		ext2 = copy(ext2,1,jx - 1 );
	}
	else
	if(jx = xpos(" ", ext2, 1))
	{
		ext2 = copy(ext2,1,jx - 1 );
	}


	// Build filters

	filters = 'All files (*.*)|0*.*|0';
	set_global_str( "!FP_FILTERS_1", "*.*" );

	if( LocateDbPage( "MECONFIG","EXT.DB", FALSE ) )
	{
		down;
		while( !at_eof && (cur_char != '|12'))
		{
			tstr2 = lower(parse_str( "EXT=", get_line ));
      if( shorten_str(lower(tstr2)) != "default")
			{
				++filtercount;
				tstr3 = "";
				jx = 0;
				jy = 1;
				tstr2 = tstr2 + " ";
				while( jx < svl(tstr2) )
				{
					++jx;
					if( xpos(str_char(tstr2,jx), " ;," ,1))
					{
						ext = copy(tstr2,jy,jx - jy);
						if ( ext == ext2 )
						{
							filterindex = filtercount;
						}
						tstr3 += "*." + ext + ";";
						jy = jx + 1;
					}
				}
				tstr3 = shorten_str(tstr3);
				if(copy(tstr3, svl(tstr3), 1) == ";")
					tstr3 = copy(tstr3, 1, svl(tstr3) - 1);

				set_global_str( "!FP_FILTERS_" + str(filtercount), lower(tstr3) );
				tstr2 = parse_str("LS=", get_line );
				if((caps(tstr2) != "NONE") && (svl(tstr2) != 0))
				{
					filters += tstr2 + " (" + tstr3 + ')|0' + tstr3 + '|0';
				}
				else
				{
					filters += tstr3 + '|0'  + tstr3 + '|0';
				}
			}
			down;
		}
	}

	set_global_int("!FP_FILTER_COUNT", filtercount );

	if ( !filterindex && (truncate_path(fn) == "*.*") )
	{
		filterindex = 1;
	}
	filters += '|0|0';

	switch_win_id(tw);

	title += '|0';

	fnr.filespec = "";
	tstr2 = GetShortName(RemoveTrailingSlash(get_path(fn))) + '|0';

	fn = Truncate_Path(fn);
	fnr.filetitle = fn;
	if( xpos("*",fn,1) || xpos("?",fn,1))
	{

	}
	else
	{
		fn = "*." + get_extension(fn);
	}
	fnr.customfilter = 'Custom(' + fn + ')|0' + fn + '|0|0';


	oprec.hWndOwner = frame_handle;
	oprec.HInstance = app_handle;
	oprec.lpstrFilter = &filters + 4;
	oprec.lpstrCustomFilter = &fnr.customfilter;
	oprec.nMaxCustFilter = 1023;
	oprec.nFilterIndex = filterindex;
	oprec.lpstrFile = &fnr.filespec;
	oprec.nMaxFile = max_line_length - 1;
	oprec.lpstrFileTitle = &fnr.filetitle;
  oprec.nMaxFileTitle = 259;
	oprec.lpstrInitialDir = &tstr2 + 4;
	oprec.lpstrTitle = &title + 4;
  oprec.Flags = ofn_EnableTemplate |
								ofn_ShowHelp | ofn_NoChangeDir;
  if( UseLongNames )
  {
    //oprec.Flags |= ofn_NoValidate;
    oprec.Flags |= 0x0300000;  // For LFN support under Win95
  }


	if ( flags & _FP_FLAG_TAG_FILES  )
	{
		oprec.Flags |= ofn_AllowMultiSelect;
    if(UseLongNames)
    {
      fnr.template = 'FPROMPT_TAG_WIDE';
    }
    else
    {
      fnr.template = 'FILEPROMPT_TAG';
    }
	}
	else
	{
    if(UseLongNames)
    {
      fnr.template = 'FPROMPT_WIDE';
    }
    else
    {
      fnr.template = 'FILEPROMPT';
    }
	}


	oprec.nFileOffset = 0;
	oprec.nFileExtension = 0;
	oprec.lpstrDefExt = 0;
	oprec.lCustData = 0;
	oprec.lpfnHook = 0;
	oprec.lpTemplateName = &fnr.template;

	fprompt_work_dir = fexpand("");

	if(!no_spec)
		fnr.filespec = fnr.filetitle;
	// make_message(fnr.filespec);

	result = 0xff & HookFilePromptWithMacro ( &oprec, "FilePromptHook /HIS=" +
							history + "/FLAGS=" + str(flags) +
							"/H=" + help);

	if(fprompt_work_dir != fexpand("")) {
		fprompt_work_dir = RemoveTrailingSlash( fprompt_work_dir );
		Change_Dir( fprompt_work_dir );
	}

	fprompt_work_dir = "";
//  result = Hook_File_Prompt( &oprec, "");

	filters = "";

	if(oprec.nFilterIndex == 0)
	{
		int zcount = 0;
		for ( jx = 0; jx < 1023; jx ++ )
		{
			if(fnr.customfilter[jx] == char(0) )
				break;
		}
		++jx;
		for ( jx = length(fnr.customfilter) + 1; jx < 127; jx++ )
		{
			if(fnr.customfilter[jx] == char(0) )
			{
				if(fnr.customfilter[jx+1] == char(0))
					break;
				filters += " ";
			}
			else
			{
				filters = filters + fnr.customfilter[jx];
			}
		}
	}
	else
	{
		filters = global_str("!FP_FILTERS_" + str(oprec.nfilterindex));
	}

	for ( jx = 1; jx <= filtercount; jx++ )
	{
		set_global_str("!FP_FILTERS_" + str(jx), "" );
	}
	set_global_int("!FP_FILTER_COUNT", 0 );

	return_str = RemoveTrailingSlash(fprompt_last_path);

	fprompt_last_path = return_str;

	rm("HISTORY_LIST /M=1/HISTORY=FPATH_HISTORY");
	fprompt_last_path = AddTrailingSlash(fprompt_last_path) + filters;


	flags &= 0x00ff;
	if(result)
	{
		if ( flags & _FP_FLAG_TAG_FILES  )
		{
			filters = parse_str("/FN=", fprompt_file_info );
			FixFileList(filters, true);
			fnr.filespec = filters;

			jx = xpos(file_seperator, fnr.filespec,1);
			if(jx)
			{
				tstr2 = RemoveTrailingSlash(get_path(fprompt_last_path));
				fnr.filespec = tstr2 + file_seperator + fnr.filespec;

				flags |= _FP_FLAG_TAGS;
				create_window;
				result = window_id;
				window_attr = 0x81;
				tstr2 = AddTrailingSlash(tstr2);
				jx = xpos(file_seperator, fnr.filespec,1);
				jy = jx + 1;
				while(jy <= length(fnr.filespec))
				{
					jx = xpos( file_seperator,fnr.filespec, jy );

					if(!jx)
						jx = length(fnr.filespec) + 1;
					put_line( tstr2 + copy(fnr.filespec,jy,jx - jy) );
					down;
					jy = jx + 1;
				}
				tof;
				switch_win_id(tw);
			}
			else
			{
				if( caps(truncate_path(fnr.filespec)) == _LN_PLACEHOLDER )
				{
					fnr.filespec = parse_str("/FN=", fprompt_file_info );
				}
				filters = fnr.filespec;
				FixFileList( filters, 8 );
				fnr.filespec = filters;
				if(get_path(fnr.filespec) == "")
					fnr.filespec = AddTrailingSlash(get_path(fprompt_last_path)) + fnr.filespec;
			}
		}

		fn = fnr.filespec;
		if(!(flags & _FP_FLAG_TAGS) )
		{

      tstr2 = Get_Path(fn);
      if( fexpand(tstr2) != tstr2 )
      {
        tstr3 = fexpand("");
        Change_Dir( RemoveTrailingSlash(Get_Path(fprompt_last_path)));

        Filters = Fexpand(AddTrailingSlash(Fexpand( tstr2 )) + Truncate_Path(parse_str("/FN=",fprompt_file_info)));
        Change_Dir( tstr3 );

        if(file_exists( filters ) == 1)
        {
          fn = filters;
        }
        else
        {
          fn = Fexpand(AddTrailingSlash(Fexpand( tstr2 )) + Truncate_Path(parse_str("/FN=",fprompt_file_info)));
          if(file_exists(filters) != 1)
          {
            fn = filters;
          }
        }
      }

      if( !file_exists( fn ) )
      {
        if(flags & _FP_FLAG_DEF_DIR)
        {
          fn = parse_str("/FN=",fprompt_file_info);
          FixFileList( fn, 1 );
        }
        else
        {
          fn = AddTrailingSlash(Get_Path(fn)) + Truncate_Path(parse_str("/FN=",fprompt_file_info));
        }
      }
		}

		jx =parse_int("/RO=", fprompt_file_info);
		if(jx != 2)
		{
			flags |= _FP_FLAG_RO_VALID;
			if(jx == 1)
				flags |= _FP_FLAG_RET_RO;
		}

		if ( parse_int("/CD=", fprompt_file_info) )
		{
			flags |= _FP_FLAG_RET_CD;
			tstr2 = RemoveTrailingSlash(fexpand(get_path( fnr.filespec )));
			change_dir( tstr2 );
		}
		if(!(flags & _FP_FLAG_TAGS) )
    {
      if(fprompt_mode & _FPM_LASTPATH)
      {
        fprompt_last_path = AddTrailingSlash( Get_Path( fn ) ) + Truncate_path( fprompt_last_path);
      }
      if(fprompt_mode & _FPM_LASTMASK)
      {
        fprompt_last_path = AddTrailingSlash( Get_Path( fprompt_last_path ) ) +
               "*." + Get_Extension( fn );
      }
    }
	}

  fprompt_file_info = "";
	rm("MewActivate");

	refresh = tr;
	switch_win_id( tw );
	return(result);
}



int FileNameExplorer( str &fn, str &title,
										str &history, str &help,
										int &flags  ) trans2
{
  str filters[max_line_length], tstr2, tstr3, ext, ext2;
	str filespec[max_line_length];

  int ttimer = system_timer;

	int result,
			tw  = window_id,
			tr = refresh,
			win32x_win = 0,
			filterindex = 0,
			filtercount = 1,
			no_spec = 0,
			jx,jy;

	if(UseLongNames)
	{
		file_seperator = ';';
	}
	else
	{
		file_seperator = ' ';
	}

	refresh = FALSE;
	working;
	if ((fn == "") || (caps(fn) == "?NO-FILE?")) {
		no_spec = 1;
		fn = fprompt_last_path;
		if (fn == "") {
			fn = "*.*";
		}
	}
	if(Get_Path(fn) == "")
	{
		fn=Get_Path(fprompt_last_path) + fn;
	}

	ext2 = lower(get_extension( fn ));
	if(jx = xpos(";", ext2, 1))
	{
		ext2 = copy(ext2,1,jx - 1 );
	}
	else
	if(jx = xpos(" ", ext2, 1))
	{
		ext2 = copy(ext2,1,jx - 1 );
	}

	WritePrivateProfileString2("FileHistory", 0, 0, win32x_file );
	WritePrivateProfileString2("Files", 0, 0, win32x_file );

  if (( flags & _FP_FLAG_SETFT ) && File_Type_Override)
  {
    WritePrivateProfileString("Files", "FileType", str(File_Type_Override), win32x_file );
  }
  else
  {
    WritePrivateProfileString("Files", "FileType", "0", win32x_file );
  }
  if ( flags & _FP_FLAG_FTO_ND )
  {
    WritePrivateProfileString("Files", "FileTypeNoDefault", "1", win32x_file );
  }
  else
  {
    WritePrivateProfileString("Files", "FileTypeNoDefault", "0", win32x_file );
  }


	// Build filters

	filters="All files (*.*)|*.*|";
	int win32x_line = c_line;

	set_global_str( "!FP_FILTERS_1", "*.*" );

	if( LocateDbPage( "MECONFIG","EXT.DB", FALSE ) )
	{
		down;
		while( !at_eof && (cur_char != '|12'))
		{
			tstr2 = lower(parse_str( "EXT=", get_line ));
      if( shorten_str(lower(tstr2)) != "default")
			{
				++filtercount;
				tstr3 = "";
				jx = 0;
				jy = 1;
				tstr2 = tstr2 + " ";
				while( jx < svl(tstr2) )
				{
					++jx;
					if( xpos(str_char(tstr2,jx), " ;," ,1))
					{
						ext = copy(tstr2,jy,jx - jy);
						if ( ext == ext2 )
						{
							filterindex = filtercount;
						}
						tstr3 += "*." + ext + ";";
						jy = jx + 1;
					}
				}
				tstr3 = shorten_str(tstr3);
				if(copy(tstr3, svl(tstr3), 1) == ";")
					tstr3 = copy(tstr3, 1, svl(tstr3) - 1);

				set_global_str( "!FP_FILTERS_" + str(filtercount), lower(tstr3) );
				tstr2 = parse_str("LS=", get_line );
				if((caps(tstr2) != "NONE") && (svl(tstr2) != 0))
				{
					filters += tstr2 + " (" + tstr3 + ")|" + tstr3 + "|";
				}
				else
				{
					filters  += tstr3 + "|"  + tstr3 + "|";
				}
			}
			down;
		}
	}

	set_global_int("!FP_FILTER_COUNT", filtercount );

	if ( !filterindex && (truncate_path(fn) == "*.*") )
	{
		filterindex = 1;
	}

	WritePrivateProfileString("Filters", "Count", str(filtercount), win32x_file );
	WritePrivateProfileString("Filters", "Index", str(filterindex), win32x_file );
  WritePrivateProfileString("Filters", "Filters", filters + "|", win32x_file );

	int historycount =  parse_int( '/#=' , global_str(history));
	WritePrivateProfileString("FileHistory", "Count", str(historycount), win32x_file );
	jy = 0;
	for(jx=historycount;jx>0;jx--)
	{
		++jy;
		WritePrivateProfileString("FileHistory", str(jy), Global_Str( history + str(jx)), win32x_file );
		down;
	}

	WritePrivateProfileString("Open", "Title", title, win32x_file );

	tstr2 = RemoveTrailingSlash(get_path(fn));

  if( file_exists(tstr2) != 2)
  {
    fn = fexpand(truncate_path(fn));
    tstr2 = fexpand("");
  }
  WritePrivateProfileString("Open", "Filespec", fn, win32x_file );



	fn = Truncate_Path(fn);
	WritePrivateProfileString("Open", "Filetitle", title, win32x_file );
	if( xpos("*",fn,1) || xpos("?",fn,1))
	{
	}
	else
	{
		fn = "*." + get_extension(fn);
	}
  WritePrivateProfileString("Filters", "Customfilter", "Custom(" + fn + ")|" + fn + "|", win32x_file );

  WritePrivateProfileString("Open", "Explorer", "1", win32x_file );
	if ( flags & _FP_FLAG_TAG_FILES  )
	{
		WritePrivateProfileString("Open", "Multiselect", "1", win32x_file );
	}
	else
	{
		WritePrivateProfileString("Open", "Multiselect", "0", win32x_file );
	}

	WritePrivateProfileString("Open", "Workingdir",GetLongName(fexpand("")) , win32x_file );
	WritePrivateProfileString("Open", "Initialdir",tstr2 , win32x_file );
	WritePrivateProfileString("Open", "SaveAs",str((Flags & _FP_FLAG_SAVEAS) != 0) , win32x_file );


	struct tmsg msg;
	Mew32Message( WM_MEW_OPENFILE32, frame_handle, 0);
	working;
 //	EnableWindow(frame_handle, false );
  SetOpenFile32Count(0);
  int tact = activateflags;
  activateflags = 0;
  While(getmessage( &msg, 0, 0, 0 ))
	{
    if(GetOpenFile32Count)
    {
      break;
    }
		if ((msg.message == WM_MEW_OPENFILE32) && (msg.hwnd == frame_handle))
		{
			break;
		}
		else
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
    if(GetOpenFile32Count)
    {
      break;
    }
	}
  SetOpenFile32Count(0);
  activateflags = tact;
  working;
  ttimer = system_timer;
	GetPrivateProfileString( "Open", "Workingdir", "", filespec, max_line_length , win32x_file );
	if(fexpand(filespec) != fexpand(""))
	{
		fprompt_work_dir = RemoveTrailingSlash( fprompt_work_dir );
		Change_Dir( RemoveTrailingSlash(filespec) );
	}

	filters = "";
  FilterIndex = GetPrivateProfileInt("Filters", "Index", 0, win32x_file );

  if(FilterIndex == 0)
	{
    GetPrivateProfileString("Filters", "CustomFilter", "", filters, 260, win32x_file );
    jx = xpos("(", filters,1);
    jy = xpos(")", filters, jx );
    filters = copy(filters, jx + 1, (jy - jx) - 1 );
	}
	else
	{
    filters = global_str("!FP_FILTERS_" + str(filterindex));
	}

	for ( jx = 1; jx <= filtercount; jx++ )
	{
		set_global_str("!FP_FILTERS_" + str(jx), "" );
	}
	set_global_int("!FP_FILTER_COUNT", 0 );



	result = GetPrivateProfileInt("Files", "Result", 0, win32x_file );
	int filecount = GetPrivateProfileInt( "Files", "Count", 0, win32x_file );

  jx = GetPrivateProfileInt( "Files","Readonly",0,win32x_file);
  if( jx != 2)
	{
		flags |= _FP_FLAG_RO_VALID;
		if(jx == 1)
    {
			flags |= _FP_FLAG_RET_RO;
    }
	}


	if(result)
	{
		if(filecount > 1 )
		{
			flags |= _FP_FLAG_TAGS;
			create_window;
			result = window_id;
			window_attr = 0x81;
			GetPrivateProfileString("Files", "1", "", tstr2, 260, win32x_file );
			tstr2 = AddTrailingSlash(tstr2);
      for ( jx = 2; jx <= filecount; jx++ )
			{
				GetPrivateProfileString( "Files", str(jx), "", filespec, 260, win32x_file );
        if(jx == 2)
        {
          fn = tstr2 + filespec;
        }
				put_line( tstr2 + filespec );
        down;
			}
			tof;
			switch_win_id(tw);
		}
		else
		{
			GetPrivateProfileString( "Files", "1", "", filespec, max_line_length, win32x_file );
			fn = filespec;
      if(!(Flags & _FP_FLAG_SAVEAS))
      {
        if( !file_exists( fn ) /* && (flags & _FP_FLAG_DEF_DIR) */ )
        {
          GetPrivateProfileString( "Files", "FileTitle", "", filespec, max_line_length, win32x_file );
          fn = filespec;
        }
      }
		}

    fprompt_last_path = Get_Path(fn) + filters;

		if(!(flags & _FP_FLAG_TAGS) )
    {
      if(fprompt_mode & _FPM_LASTPATH)
      {
        fprompt_last_path = AddTrailingSlash( Get_Path( fn ) ) + Truncate_path( fprompt_last_path);
      }
      if(fprompt_mode & _FPM_LASTMASK)
      {
        fprompt_last_path = AddTrailingSlash( Get_Path( fprompt_last_path ) ) +
               "*." + Get_Extension( fn );
      }
    }

	  if (flags & (_FP_FLAG_FTO | _FP_FLAG_FTO_ND))
		{
	    File_Type_Override = GetPrivateProfileInt("Files", "Filetype", 0, win32x_file );
	    File_Type_BRL = GetPrivateProfileInt("Files", "RecordLength", 0, win32x_file );
		}
	  if (flags & _FP_FLAG_OEM)
		{
	    Oem_Type_Override = GetPrivateProfileInt("Files", "OEMmode", 0, win32x_file );
	    if ( Oem_Type_Override == 2 )
	    {
	      Oem_Type_Override = 0;
	    }
	    else
	    {
	      Oem_Type_Override = Oem_Type_Override + 1;
	    }
		}
	}
	fprompt_file_info = "";

	rm("MewActivate");

	refresh = tr;
 	switch_win_id( tw );
	return(result);
}


int FixFileList( str &fn, int remove_quote )
{
	int res = 0;
	int jx = 1;
	int prev_ofs = 1;
	str tstr;

	while(jx <= svl(fn))
	{
		if(str_char(fn,jx) == '"')
		{
			if(remove_quote & 3)
			{
				fn = str_del(fn,jx,1);
			}
			else
			{
				++jx;
			}
			jx = xpos('"', fn, jx );
			if(!jx)
				break;
			if ( remove_quote & 3)
			{
				fn = str_del(fn,jx,1);
				--jx;
			}
		}
		else
		{
			if(!(remove_quote & 8))
			{
				if(str_char(fn,jx) == ' ')
				{
					if( file_seperator != ' ' )
						fn = str_ins( file_seperator, str_del(fn,jx,1), jx );
					res = TRUE;
					call handle_name;
				}
				else
				if ( str_char(fn,jx) == ';' )
				{
					if( file_seperator != ';' )
						fn = str_ins( file_seperator, str_del(fn,jx,1), jx );
					res = TRUE;
					call handle_name;
				}
			}
		}
		++jx;
	}
	call handle_name;
	return(res);

handle_name:
	if(remove_quote & 2)
	{
		if(prev_ofs < jx)
		{
			tstr = GetShortName( copy(fn, prev_ofs, jx - prev_ofs ) );
			fn = str_ins( tstr, str_del(fn, prev_ofs, jx - prev_ofs),prev_ofs );
			jx = prev_ofs + jx;
			prev_ofs = jx + 1;
		}
	}
	ret;
}


int FileNamePrompt( str &fn, str title[80],
										str history[20], str help[80],
										int &flags  ) trans2
{
	if(( Fprompt_Mode & _FPM_EXPLORER ) &&
		((GetVersion & 0x0000FF00) == 0x005F00 ))
	{
		return(FileNameExplorer( fn, title, history, help, flags ));
	}
	else
	{
		return(FileNameClassic( fn, title, history, help, flags ));
	}
}



/*
void ftest()
{
  int flags = _FP_FLAG_FTO | _FP_FLAG_OEM;
  str fn = "";

  FileNamePrompt( fn, "Open New File",
                      "FILE_HISTORY", "",
                      flags  );


	make_message( // fprompt_last_path + " " +
	fn);
}
 */

str GetDlgStr( int dlg, int id )
{
	str tstr[max_line_length];
	GetDlgItemText(dlg, id, tstr, max_line_length - 1);
	return(tstr);
}


void _FPUpdate( int dlg )
{

  str file_str = "12345678.123",
      tstr;
  struct WIN32_FIND_DATA new_fd;
  struct DOS_FIND_DATA old_fd;
  int find_handle;

  //GetDlgItemText( dlg, _FP_DIR_ID, tstr, 254 );
  tstr = fexpand("");
	fprompt_last_path = tstr;
 // make_message(tstr + " " + str(svl(tstr)));
	int jx = SendDlgItemMessage( dlg, _FL_ID, lb_getcaretindex, 0, 0);
	if( SendDlgItemMessage(dlg, _FL_ID, lb_getsel, jx, 0 ) > 0)
	{
    pad_str( file_str, 254, "\x0");
		jx = SendDlgItemMessageStr( dlg, _FL_ID, lb_gettext, jx, file_str);
		FixFileList( file_str, TRUE );
		//file_str = copy(file_str,1,jx);
		tstr = AddTrailingSlash(tstr);
		file_str = tstr + file_str;
  	find_handle = FindFirstFile(file_str, &new_fd, &old_fd );
  	if(find_handle)
		{
			FindClose(find_handle);
      if(UseLongNames)
      {
        file_str = new_fd.cFileName;
      }
      else
      {
        file_str = lower(old_fd.name);
      }
			SetDlgItemText( dlg, 5100, file_str );
			call calc_time_date;
			SetDlgItemText( dlg, 5101, tstr );

      str size_str;
      if(old_fd.size >= 0x100000)
      {
        size_str = str(old_fd.size / 0x100000) + " meg";
      }
      else if(old_fd.size >= 1024)
      {
        size_str = str(old_fd.size / 1024) + "k";
      }
      else
      {
        size_str = str(old_fd.size) + " bytes";
      }

      SetDlgItemText( dlg, 5102, size_str );
			if (!global_int("!FP_SPECIAL_FLAG")) {
				SendDlgItemMessage( dlg, _FP_RO_ID, bm_setcheck,old_fd.attr & 1, 0 );
			}
			tstr = "";
			if(old_fd.attr & 1)
				tstr += "R";
			if(old_fd.attr & 0x20)
				tstr += "A";
			SetDlgItemText( dlg, 5103, tstr );
		}
		else
		{
			call clear_fields;
		}
	}
	else
	{
		call clear_fields;
	}

	return();

clear_fields:
			SetDlgItemText( dlg, 5100, "" );
			SetDlgItemText( dlg, 5101, "" );
			SetDlgItemText( dlg, 5102, "" );
			if (!global_int("!FP_SPECIAL_FLAG")) {
				SendDlgItemMessage( dlg, _FP_RO_ID, bm_setcheck,2, 0 );
			}
			SetDlgItemText( dlg, 5103, "" );
	ret;

int  j1, j2, j3 ;
str sTime[2];
calc_time_date:
		jx = old_fd.time & $FFFF;
		j1 = jx >> 11;
		j2 = (jx >> 5) & $3F;
// this code supports all time formats
		tstr = Make_Time_Str( j1, j2, 0 );
		j3 = 6;
		GetProfileString("intl","sTime", ":",sTime,2);
		if (xpos(sTime,tstr,1) == 2) {
			j3 = 5;
		}
		tstr = Str_Del(tstr,j3,3);

		jx = old_fd.time >> 16;
		j1 = (jx >> 9) + 1980;
		j2 = (jx >> 5) & $0F;
		j3 = (jx & 31);
		tstr = Make_Date_Str( j1, j2, j3 ) + ' ' + tstr;
		ret;

}

global
{
	int no_file_update "!NO_FILE_UPDATE";
	int fp_dir_changed "!FP_DIR_CHANGED";
	int fp_dir_closeup "!FP_DIR_CLOSEUP";
}


str FPGetFileSpec( struct topenfilename oprec )
{
	int t = oprec.lpstrfiletitle;
	str s = "";
	int b;

	do
	{
		b=memb(t);
		if(!b)
		{
			break;
		}
		s+=char(b);
		++t;
	} while(true);

	return(s);
}

void FCFixPath( str &f1 )
{
	f1 = RemoveTrailingSlash(fexpand(f1));
}

int FPValidateDir( int dlg )
{
	int result = 2;
	str fn[128],fn2 = fexpand("");
	int jx,jy,jz,
			use_in_path = 0;


	jx = GetDlgItem(dlg,_FP_DIR_ID);
	jz = SendMessage(jx, cb_getcursel, 0, 0);
	if((jz >= 0) && (jz != 0xffff))
	{
		use_in_path = TRUE;
		jy = parse_int('/#=', global_str("FPATH_HISTORY")) -	jz;

		fn = global_str( "FPATH_HISTORY" + str(jy));
	}
	else
	{
		GetDlgItemText( dlg, _FP_DIR_ID, fn, 127 );
	}
	if(!xpos("..\\", fn, 1))
	{
		fp_dir_changed = FALSE;
		FCFixPath( fn );
		FCFixPath( fn2 );
		fn = GetShortName( fn );
		fn2 = GetShortName(fn2);

		if( fn != fn2 )
		{
			if(svl(fn) > 3)
			{
				if( file_exists(fn) != 2)
				{
				/*  if(GetFocus() != GetDlgItem(dlg, _FP_DIR_ID ))
						SetFocus( GetDlgItem(dlg, _FP_DIR_ID ));
				*/
					SetDlgItemText(dlg, _FP_DIR_ID, fexpand("") );
					return(0);
				}
			}
		//  fprompt_last_path = fn;
			if(!use_in_path)
				SetDlgItemText(dlg, _FP_DIR_ID, fn );
			result = 1;
		}
	}
	return(result);
}


#DEFINE _FO_COPY   1
#DEFINE _FO_DELETE 2
#DEFINE _FO_MOVE   3
#DEFINE _FO_RENAME 4
#DEFINE _FO_SEND 5
#DEFINE _FO_CREATE_DIR 6
#DEFINE _FO_ATTRIBUTE 7

#DEFINE _FO_BTNWIDTH 14

void FileOperation( int w   = parse_int( "/DLGHANDLE=", mparm_str),
										int id  = parse_int("/ID=", mparm_str),
										int op  = parse_int("/OP=", mparm_str),
										int fid = parse_int("/FID=", mparm_str),
										int pid = parse_int("/PID=", mparm_str),
										int tid = parse_int("/TID=", mparm_str)
									 ) trans2
{
  str nstr[260],fstr[max_line_length],pstr[260],tstr[260], mstr[260];
	int ix = 1,jx, fcount = 0;
	int delete_ro = 1;
	int do_overwrite = 1;
	int cancel = 0;
	int result = 0;
  struct WIN32_FIND_DATA new_fd;
  struct DOS_FIND_DATA old_fd;
  int find_handle;


	GetDlgItemText( w, fid, fstr, max_line_length );
	FixFileList(fstr, TRUE );
	if(op != _FO_DELETE)
	{
		GetDlgItemText( w, tid, tstr, 127 );
		if( op != _FO_RENAME )
			tstr = AddTrailingSlash(tstr);
	}

	GetDlgItemText( w, pid, pstr, 127 );
	pstr = AddTrailingSlash(pstr );


	switch ( op )
	{
		case _FO_CREATE_DIR :
						error_level = MKDir( fstr );
						if(error_level != 0)
						{
							error_level += 3000;
							rm("MEERROR");
							error_level = 0;
						}
						else
						{
							result = 1;
						}
						break;

		case _FO_DELETE :
						while(!error_level && (0 < svl(fstr)))
						{
							working;
							call next_name;
							if(nstr != "")
							{
								if(get_path(nstr) == "")
								{
									nstr = pstr + nstr;
								}
  							find_handle = FindFirstFile(nstr, &new_fd, &old_fd );
  							if(find_handle)
								{
									do
									{
										mstr = "Deleting " + new_fd.cFileName;
										SetDlgItemText( w, id, mstr );
										if(old_fd.attr & 0x01)
										{
											call get_readonly;
											if(!delete_ro)
												goto next_del;
											set_file_attr( get_path(nstr) + new_fd.cFileName,
											 old_fd.attr & 0xFE );
										}
										Del_File( AddTrailingSlash(get_path(nstr)) + new_fd.cFileName );
										if(error_level)
										{
											break;
										}
										++fcount;
									 next_del:
									} while((FindNextFile( find_handle, &new_fd, &old_fd ) ) && (!cancel));
									FindClose(find_handle);
								}
							}
						}
						if(error_level)
						{
							rm("MEERROR");
							error_level = 0;
						}
            mstr = str(fcount) + " file(s) deleted.";
						SetDlgItemText( w, id, mstr );
						result = (fcount > 0);
						break;

		case _FO_MOVE :
						while(!error_level && (0 < svl(fstr)))
						{
							working;
							call next_name;
							if(nstr != "")
							{
								if(get_path(nstr) == "")
								{
									nstr = pstr + nstr;
								}
  							find_handle = FindFirstFile(nstr, &new_fd, &old_fd );
  							if(find_handle)
								{
									do
									{
										mstr = "Moving " + new_fd.cFileName;
										SetDlgItemText( w, id, mstr );

										if(file_exists( AddTrailingSlash(tstr) + new_fd.cFileName))
										{
											call get_overwrite;
											if(!do_overwrite)
												goto next_move;
										}

										if( (caps(copy(nstr,1,2)) == caps(copy(tstr,1,2))) && (copy(nstr,1,1) != "\\"))
										{
											if(!rename_file( AddTrailingSlash(get_path(nstr)) + new_fd.cFileName,
																			tstr + new_fd.cFileName))
											{
												 ++fcount;
												 goto next_move;
											}
										}

										error_level = Copy_File( AddTrailingSlash(get_path(nstr)) + new_fd.cFileName,
											tstr + new_fd.cFileName, FALSE );
										if(!error_level)
										{
											if(old_fd.attr & 0x01)
											{
												call get_readonly;
												if(!delete_ro)
													goto next_move;
												set_file_attr( get_path(nstr) + new_fd.cFileName,
												 old_fd.attr & 0xFE );
											}

											Del_File( get_path(nstr) + new_fd.cFileName );
											if(error_level)
											{
												break;
											}
											++fcount;
										}
										else
										{
											error_level += 3000;
										}
									 next_move:
									} while(( FindNextFile( find_handle, &new_fd, &old_fd ) ) && (!cancel) && (!error_level));
									FindClose(find_handle);
								}

							}
						}
						if(error_level)
						{
							rm("MEERROR");
							error_level = 0;
						}
						mstr = str(fcount) + " file(s) moved.";
						SetDlgItemText( w, id, mstr );
						result = (fcount > 0);
						break;

		case _FO_COPY :
						while(!error_level && (0 < svl(fstr)))
						{
							working;
							call next_name;
							if(nstr != "")
							{
								if(get_path(nstr) == "")
								{
									nstr = pstr + nstr;
								}
  							find_handle = FindFirstFile(nstr, &new_fd, &old_fd );
  							if(find_handle)
								{
									do
									{
										mstr = "Copying " + new_fd.cFileName;
										SetDlgItemText( w, id, mstr );

										if(file_exists( tstr + new_fd.cFileName))
										{
											call get_overwrite;
											if(!do_overwrite)
												goto next_copy;
										}
										error_level = Copy_File( get_path(nstr) + new_fd.cFileName,
											tstr + new_fd.cFileName, FALSE );
										if(!error_level)
										{
											++fcount;
										}
										else
										{
											error_level += 3000;
										}
									 next_copy:
									} while(( FindNextFile( find_handle, &new_fd, &old_fd ) ) && (!cancel) && (!error_level));
									FindClose(find_handle);
								}
							}
						}
						if(error_level)
						{
							rm("MEERROR");
							error_level = 0;
						}
						mstr = str(fcount) + " file(s) copied.";
						SetDlgItemText( w, id, mstr );
						result = (fcount > 0);
						break;


		case _FO_ATTRIBUTE :
						{
							int attr_and = 0xffc0;
							int attr_or  = 0;
							int j;

							j = IsDlgButtonChecked( w, 1050 );
							switch ( j )
							{
								case 1 :
										attr_or |= _FA_READONLY;
										break;

								case 2 :
										attr_and |= _FA_READONLY;
							}

							j = IsDlgButtonChecked( w, 1051 );
							switch ( j )
							{
								case 1 :
										attr_or |= _FA_HIDDEN;
										break;

								case 2 :
										attr_and |= _FA_HIDDEN;
							}

							j = IsDlgButtonChecked( w, 1052 );
							switch ( j )
							{
								case 1 :
										attr_or |= _FA_ARCHIVE;
										break;

								case 2 :
										attr_and |= _FA_ARCHIVE;
							}

							j = IsDlgButtonChecked( w, 1053 );
							switch ( j )
							{
								case 1 :
										attr_or |= _FA_SYSTEM;
										break;

								case 2 :
										attr_and |= _FA_SYSTEM;
							}



							while(!error_level && (0 < svl(fstr)))
							{
								working;
								call next_name;
								if(nstr != "")
								{
									if(get_path(nstr) == "")
									{
										nstr = pstr + nstr;
									}
  								find_handle = FindFirstFile(nstr, &new_fd, &old_fd );
  								if(find_handle)
									{
										do
										{
											mstr = "Setting attribute for " + new_fd.cFileName;
											SetDlgItemText( w, id, mstr );

											Set_File_Attr( get_path(nstr) + new_fd.cFileName,
																		(old_fd.attr & attr_and) | attr_or);
											if(!error_level)
											{
												++fcount;
											}
										} while(( FindNextFile( find_handle, &new_fd, &old_fd )) && (!cancel) && (!error_level));
										FindClose(find_handle);
									}
								}
							}
							if(error_level)
							{
								rm("MEERROR");
								error_level = 0;
							}
							mstr = str(fcount) + " file attribute(s) changed.";
							SetDlgItemText( w, id, mstr );
							result = (fcount > 0);
							break;
						}

		case _FO_RENAME :
						if(get_path(fstr) == "")
							fstr = pstr + fstr;

						if((fstr != "") && (tstr != ""))
						{
							error_level = rename_file( fstr, tstr );
							if(error_level)
							{
								result = 0;
								error_level += 3000;
								rm("MEERROR");
								error_level = 0;
							}
							else
							{
								result = 1;
							}
						}
						else
						{
							error_level += 3002;
							rm("MEERROR");
							error_level = 0;
							result = 0;
						}
						break;
	}

	return_int = result;
	return();

next_name:
	jx =  xpos(file_seperator, fstr, ix );

	if(jx == 0)
	{
		jx = svl(fstr) + 1;
	}
	nstr = copy(fstr, ix, jx - 1);
	fstr = copy(fstr, jx + 1, max_line_length);
	ix = 1;
	ret;

get_readonly:
	if(delete_ro != 10)
	{
		int dlgro;

		DlgCreate(dlgro);
		DlgAddCtrl( dlgro, DLG_Icon, "IC_QUESTION", 1, 1, 0,0,2010,0, "" );
		DlgAddCtrl( dlgro, DLG_Static, new_fd.cFileName + " is marked read-only.", 8, 1, 0, 0, 2000, 0, "" );
		DlgAddCtrl( dlgro, DLG_Static, "Delete anyway?", 8, 2, 0, 0, 2001, 0, "" );
		DlgAddCtrl( dlgro, DLG_PushButton, "&Yes", 1, 5, DLG_StanBtnWidth, 0, 100, DLGF_DefButton, "/R=1" );
		DlgAddCtrl( dlgro, DLG_PushButton, "yes to &All", DLG_PosOffset + DLG_StanBtnWidth + 2, DLG_PosOffset, DLG_StanBtnWidth, 0, 101, 0, "/R=10" );
		DlgAddCtrl( dlgro, DLG_PushButton, "&No", DLG_PosOffset + DLG_StanBtnWidth + 2, DLG_PosOffset, DLG_StanBtnWidth, 0, 102, 0, "/R=11" );
		DlgAddCtrl( dlgro, DLG_PushButton, "Cancel", DLG_PosOffset + DLG_StanBtnWidth + 2, DLG_PosOffset, DLG_StanBtnWidth, 0, 103, 0, "/R=0" );
		DlgAddCtrl( dlgro, DLG_PushButton, "&Help", DLG_PosOffset + DLG_StanBtnWidth + 2, DLG_PosOffset, DLG_StanBtnWidth, 0, 104, 0, "/R=2" );

		delete_ro = DlgExecute( dlgro, 100, "Confirm",  "", "", 0 );
		DlgKill( dlgro );
		cancel = (delete_ro == 0);
		if(delete_ro == 11)
		{
			delete_ro = 0;
		}
	}
	ret;


get_overwrite:
	if(do_overwrite != 10)
	{
		int dlgro;

		DlgCreate(dlgro);
		DlgAddCtrl( dlgro, DLG_Icon, "IC_QUESTION", 1, 1, 0,0,2010,0, "" );
		DlgAddCtrl( dlgro, DLG_Static, new_fd.cFileName + " already exists.", 8, 1, 0, 0, 2000, 0, "" );
		DlgAddCtrl( dlgro, DLG_Static, "Overwrite file?", 8, 2, 0, 0, 2001, 0, "" );
		DlgAddCtrl( dlgro, DLG_PushButton, "&Yes", 1, 5, DLG_StanBtnWidth, 0, 100, DLGF_DefButton, "/R=1" );
		DlgAddCtrl( dlgro, DLG_PushButton, "yes to &All", DLG_PosOffset + DLG_StanBtnWidth + 2, DLG_PosOffset, DLG_StanBtnWidth, 0, 101, 0, "/R=10" );
		DlgAddCtrl( dlgro, DLG_PushButton, "&No", DLG_PosOffset + DLG_StanBtnWidth + 2, DLG_PosOffset, DLG_StanBtnWidth, 0, 102, 0, "/R=11" );
		DlgAddCtrl( dlgro, DLG_PushButton, "Cancel", DLG_PosOffset + DLG_StanBtnWidth + 2, DLG_PosOffset, DLG_StanBtnWidth, 0, 103, 0, "/R=0" );
		DlgAddCtrl( dlgro, DLG_PushButton, "&Help", DLG_PosOffset + DLG_StanBtnWidth + 2, DLG_PosOffset, DLG_StanBtnWidth, 0, 104, 0, "/R=2" );

		do_overwrite = DlgExecute( dlgro, 100, "Confirm",  "", "", 0 );
		DlgKill( dlgro );
		cancel = (do_overwrite == 0);
		if(do_overwrite == 11)
		{
			do_overwrite = 0;
		}
	}
	ret;

}

void FileBrowse( int w = parse_int( "/DLGHANDLE=", mparm_str),
								 int id = parse_int("/ID=", mparm_str)) trans2
{
	int flags = 0;
	str fn[128] = "";

	GetDlgItemText( w, id, fn, 127 );
	if(SelectDirectory( w, fn, "Select Directory","", 0 ))
	{
		SetDlgItemText( w, id, fn );
	}
	return_int = 0;
}
int FileOpDlg( int parent, int op, str fstr[max_line_length] ) trans2
{
	int result;
	int dlg2;
	int browse_button = false;
	int multiple_files = false;
	int yoff, yoff2 = 4;
	int jx;
  struct WIN32_FIND_DATA new_fd;
  struct DOS_FIND_DATA old_fd;
  int find_handle;

	str t1[40],
			t2[10],
			t3[10],
			help_str[40];

	switch ( op )
	{
		case _FO_COPY :
						t1 = "Copy File(s)";
						t2 = "&Copy:";
						t3 = "&To:";
						help_str = FILEMGR_HELPLINK;
						browse_button = TRUE;
						break;

		case _FO_DELETE :
						t1 = "Delete File(s)";
						t2 = "&Delete:";
						t3 = "";
						help_str = FILEMGR_HELPLINK;
						yoff2 = 2;
						break;

		case _FO_MOVE :
						t1 = "Move File(s)";
						t2 = "&Move:";
						t3 = "&To:";
						help_str = FILEMGR_HELPLINK;
						browse_button = TRUE;
						break;

		case _FO_RENAME :
						t1 = "Rename File(s)";
						t2 = "&Rename:";
						t3 = "&To:";
						help_str = FILEMGR_HELPLINK;
						break;

		case _FO_CREATE_DIR :
						t1 = "Create Directory";
						t2 = "&Directory name:";
						t3 = "";
						help_str = FILEMGR_HELPLINK;
						break;

		case _FO_ATTRIBUTE :
						t1 = "Attributes";
						t2 = "&File(s):";
						t3 = "";
						help_str = FILEMGR_HELPLINK;
						break;

		default:
						return(0);
	}

	if( xpos(file_seperator, fstr, 1) || xpos("*", fstr,1) || xpos("?", fstr,1))
		multiple_files = TRUE;

	DlgCreate(dlg2);

	DlgAddCtrl( dlg2, DLG_Static,  fexpand(""), 2, 1, 0, 0, 2005, 0, "" );

	if(t3 == "")
	{

		DlgAddCtrl( dlg2, DLG_Static, t2, 2, DLG_PosOffset | DLG_Units | (Dlg_Units_Line_Half - 3), 0, 0, 2000, 0, "" );
		DlgAddCtrl( dlg2, DLG_Text, "" , DLG_PosOffset, DLG_PosOffset | DLG_Units | 10, 50, 0, 1000, 0, "/ML=" + str(max_line_length) );
		DlgSetStr( dlg2, 1000, fstr );
		yoff = 6 * DLG_Units_Per_Line + DLG_Units_HLine;
		if(op == _FO_ATTRIBUTE)
		{
			if( multiple_files )
			{
				jx = DLG_3State;
			}
			else
			{
				jx = DLG_CheckBox;
			}

			DlgAddCtrl( dlg2, DLG_GroupBox, "&Attributes", 2,
					DLG_PosOffset | DLG_Units | (DLG_Units_Line_Half - 2), 50, 3, 2050, 0, "" );
			DlgAddCtrl( dlg2, jx, "Read-only", 4, DLG_PosOffset | 1, 0, 0, 1050, 0, "" );
			DlgAddCtrl( dlg2, jx, "Hidden", 30, DLG_PosOffset, 0, 0, 1051, 0, "" );
			DlgAddCtrl( dlg2, jx, "Archive", 4, DLG_PosOffset | 1, 0, 0, 1052, 0, "" );
			DlgAddCtrl( dlg2, jx, "System", 30, DLG_PosOffset, 0, 0, 1053, 0, "" );
			yoff = 8 * DLG_Units_Per_Line;

			if( multiple_files )
			{
				DlgSetInt( dlg2, 1050, 2 );
				DlgSetInt( dlg2, 1051, 2 );
				DlgSetInt( dlg2, 1052, 2 );
				DlgSetInt( dlg2, 1053, 2 );
			}
			else
			{

  			find_handle = FindFirstFile(fstr, &new_fd, &old_fd );
  			if(find_handle)
				{
					FindClose(find_handle);
					DlgSetInt( dlg2, 1050, (old_fd.attr & _FA_READONLY) != 0);
					DlgSetInt( dlg2, 1051, (old_fd.attr & _FA_HIDDEN) != 0);
					DlgSetInt( dlg2, 1052, (old_fd.attr & _FA_ARCHIVE) != 0);
					DlgSetInt( dlg2, 1053, (old_fd.attr & _FA_SYSTEM) != 0);
				}
			}


		}
	}
	else
	{
		DlgAddCtrl( dlg2, DLG_Static, t2, 2, DLG_PosOffset | DLG_Units |(Dlg_Units_Line_Half - 3), 0, 0, 2000, 0, "" );
		DlgAddCtrl( dlg2, DLG_Text, fstr , DLG_PosOffset, DLG_PosOffset | DLG_Units | 10, 50, 0, 1000, 0, "/ML=" + str(max_line_length) );
		DlgSetStr( dlg2, 1000, fstr );
		yoff = 8 * DLG_Units_Per_Line;
		DlgAddCtrl( dlg2, DLG_Static, t3, 2, DLG_PosOffset | DLG_Units | (DLG_Units_Line_Half + 2), 0, 0, 2001, 0, "" );
		DlgAddCtrl( dlg2, DLG_Text, "" , DLG_PosOffset, DLG_PosOffset | DLG_Units | (DLG_Units_Per_Line - 2) , 50, 0, 1001, 0, "/ML=" + str(max_line_length) );
	}

	DlgAddCtrl( dlg2, DLG_BlackFrame, "", 2,
		DLG_Units | ( yoff - DLG_Units_HLine), 50, 2, 2004, 0, "");

	DlgAddCtrl( dlg2, DLG_Static, "", 3,
		DLG_Units | ( yoff - DLG_Units_HLine), 48, 2, 2010, 0, "");

	DlgAddCtrl( dlg2, DLG_PushButton, "OK", 55, DLG_Units | DLG_Units_HLine, _FO_BTNWIDTH, 0, 100, DLGF_DefButton,
			"/R=1/M=FileOperation /OP=" + str(op) + "/ID=2010/PID=2005/FID=1000/TID=1001" );

	DlgAddCtrl( dlg2, DLG_PushButton, "Cancel", DLG_PosOffset, DLG_PosOffset | DLG_Units | DLG_Units_Line_Half + 1, _FO_BTNWIDTH, 0, 101, 0, "/R=0" );
	if(browse_button)
	{
		DlgAddCtrl( dlg2, DLG_PushButton, "&Browse...", DLG_PosOffset, DLG_PosOffset | DLG_Units +
					(DLG_Units_Per_Line + DLG_Units_Per_Line + DLG_Units_HLine), _FO_BTNWIDTH, 0, 103, 0, "/R=10/M=FileBrowse /ID=1001" );
	}
	DlgAddCtrl( dlg2, DLG_PushButton, "&Help", DLG_PosOffset, DLG_Units | (yoff + DLG_Units_HLine) , _FO_BTNWIDTH, 0, 102, 0, "/R=2" );
	result = DlgExecute( dlg2, 1000, t1, help_str, "", 0 );
	DlgKill( dlg2 );

	return(result);
}

void FPSetDefBtn( int w, int id )
	trans2 no_break
{
	int tid,tl;

	tid = 1;
	call style_off;

	tid = 2;
	call style_off;

	tid = _FP_HELP_id;
	call style_off;

	tid = _FP_SEL_ALL;
	call style_off;

	tid = _FP_SEL_NONE;
	call style_off;

	tid = _FP_WORK_VIEW;
	call style_off;

	tid = _FP_WORK_CHANGE;
	call style_off;

	// Update the default push button's control ID.
	SendMessage(w, DM_SETDEFID, id, 0);

	// Set the new style.
	SendDlgItemMessage(w, id, BM_SETSTYLE, BS_DEFPUSHBUTTON, TRUE);
	return();

style_off:
	tl = GetWindowLong( GetDlgItem( w, tid ), GWL_STYLE );
	if((tl & BS_DEFPUSHBUTTON) && (tid != id))
	{
		SendDlgItemMessage(w, tid, BM_SETSTYLE, BS_PUSHBUTTON, TRUE);
	}
	ret;
}



#ifdef _old
void FPFixFileName(dlg)
	trans2
{
/* compensates for the common dialog box's inability to deal with
 file names entered that are longer than 8 characters (minus the
 extension) */
	return();

	str t_str[max_line_length] = GetDlgStr(dlg, _FN_ID),
      t_path, t_name, t_ext,
			t_str2,
			t_str3[max_line_length] = "";
	int t_int;

	FixFileList( t_str, 3 );

	if(xpos("*",t_str,1) || xpos("?",t_str,1))
	{
		return();
	}

// this stuff handles multiple filespecs separated by spaces
	/*
	while (t_int = xpos(" " , t_str, 1)) {
		t_str2 = copy(t_str, 1, t_int - 1);
		t_str = copy(t_str, t_int + 1, max_line_length);
		call FIX_IT;
	}
	*/

// this stuff handles multiple filespecs separated by spaces

	while (t_int = xpos(file_seperator , t_str, 1)) {
		t_str2 = copy(t_str, 1, t_int - 1);
		t_str = copy(t_str, t_int + 1, max_line_length);
		call FIX_IT;
	}


	t_str2 = t_str;
	call FIX_IT;

	//t_str3 = remove_space(t_str3);
	if(copy(t_str3, svl(t_str3),1) == file_seperator)
		t_str3 = copy(t_str3,1,svl(t_str3) - 1);

	SetDlgItemText(dlg, _FN_ID, t_str3);
	RETURN();

FIX_IT:
	if (xpos(".",t_str2,1)) {
		t_path = get_path(t_str2);
		t_name = truncate_path(truncate_extension(t_str2));
		t_ext = get_extension(t_str2);
		t_str2 = "";
		if (svl(t_path)) {
			t_str2 = t_path;
		}
		t_str2 = t_str2 + t_name;
		if (svl(t_ext)) {
			t_str2 = t_str2 + "." + t_ext;
		}
		if(xpos(" ", t_str2,1))
		{
			t_str = '"' + t_str2 + '"';
		}
	}

  t_str3 = t_str3 + t_str2 + file_seperator;
	RET;
}
#endif

global
{
	int FileOkMessage;
	int LbSelchange;
	int FPLastFocus;
}


int FPromptOperation( int dlg, int wparam, int lparam, str parms, struct topenfilename oprec )
	trans2
{
	int result = 0, r = 0, fl,
			flags = parse_int("/FLAGS=",parms);

	int dlg2;


	switch ( wparam )
	{
		case _FP_OK :
				{
					str fnx[max_line_length];

					fpNeedDirList = 1;
					FPNeedFileList = 1;
					if(SendDlgItemMessage( dlg, _FP_EXT_ID, CB_GETDROPPEDSTATE, 0, 0 ))
					{
						SendDlgItemMessage( dlg, _FP_EXT_ID, CB_SHOWDROPDOWN, 0, 0 );
						return(1);
					}

					if(fp_dir_changed)
					{
						if( FPValidateDir( dlg ) == 1 )
						{
							SetDlgItemText( dlg, _FN_ID, GetDlgStr(dlg,_FP_DIR_ID));
							PostMessage(GetDlgItem( dlg, _FP_DIR_ID), CB_SETEDITSEL, 0, make_long(0,-1) );
							return(0);
						}
					}


					// Handle loading a file when only a partial, but valid,
					// filename has been entered
					if(FPLastFocus == _FN_ID)
					{
						int jx = LB_ERR;
          	if (parse_int("/FLAGS=", parms) & _FP_FLAG_TAG_FILES)
						{
							if(SendDlgItemMessage(dlg, _FL_ID, lb_getselcount, 0, 0 ) == 1)
							{
								jx = SendDlgItemMessage( dlg, _FL_ID, lb_getcaretindex, 0, 0);
							}
						}
						else
						{
							jx = SendDlgItemMessage(dlg, _FL_ID, lb_getcursel, 0, 0 );
						}
						//messagebox(0, str(jx), 'JX=', mb_ok);
						if(jx != LB_ERR)
						{
							if( SendDlgItemMessage(dlg, _FL_ID, lb_getsel, jx, 0 ) > 0)
							{
								SendDlgItemMessageStr(dlg, _FL_ID, lb_gettext, jx, fnx );
								SetDlgItemText( dlg, _FN_ID, fnx);
							}
						}
					}



			 /*
					FPFixFileName(dlg);
					int n = FPValidateDir( dlg );
					if( n == 1 )
					{
						// GetDlgItemText( dlg, _FP_DIR_ID, fnx, 127 );

						fprompt_last_path = GetDlgStr( dlg, _FP_DIR_ID );
						SetDlgItemText( dlg, _FN_ID, fprompt_last_path );
						break;
					}
					if( n == 0)
					{
						result = 1;
						setfocus( GetDlgItem( dlg, _FP_DIR_ID ));
						break;
					}
				 */

					GetDlgItemText( dlg, _FN_ID, fnx, 127 );
					fl = FixFileList(fnx, false );

					if(xpos("*",fnx,1) || xpos("?",fnx,1))
					{

						int kx,ix,jx, filtercount = global_int("!FP_FILTER_COUNT");
						str fnx2[128];

						FixFileList(fnx, TRUE );

						fnx2 = fnx;
						fnx = Truncate_Path(fnx);

						fnx=lower(fnx);

						ix = 0;
						for ( jx=1;jx<=filtercount;jx++ )
						{
							if(fnx==global_str("!FP_FILTERS_" + str(jx)))
							{
								ix = jx;
								break;
							}
						}


						fnx = 'Custom(' + fnx + ')|0' + fnx + '|0|0';
						for(kx = 0;kx<svl(fnx);kx++)
						{
							memb( oprec.lpstrCustomFilter+kx, ascii(str_char(fnx,kx+1)));
						}

						result = 1;

						SendDlgItemMessage(dlg,_FP_EXT_ID, CB_DELETESTRING, 0, 0 );
						SendDlgItemMessageStr(dlg,_FP_EXT_ID, CB_INSERTSTRING, 0, fnx );

						fnx2 = get_path(fnx2);
						SetDlgItemText( dlg,_FN_ID, fnx2 );

						SendDlgItemMessage(dlg,_FP_EXT_ID, CB_SETCURSEL, ix, 0 );

						PostMessage( dlg, WM_COMMAND, _FP_EXT_ID, Make_Long(GetDlgItem(dlg,_FP_EXT_ID),CBN_SELCHANGE));
						if( svl(fnx2) )
						{
							result = 0;
						}
						else
						{
							result = 1;
						}
					}
					else if(fl)
					{
						if(SendDlgItemMessage(dlg, _FL_ID, lb_getsel,
								SendDlgItemMessage( dlg, _FL_ID, lb_getcaretindex, 0, 0), 0 ) > 0)
							{
								set_global_int("!FP_SPECIAL_FLAG",1);
								SendMessage( dlg, WM_COMMAND, _FL_ID, Make_Long(GetDlgItem(dlg, _FL_ID),LBN_SELCHANGE));
								set_global_int("!FP_SPECIAL_FLAG",0);
						}
						PostMessage( dlg, WM_FPUPDATE2, 0,0 );
					}
					else
					{
					 //	FPFixFileName(dlg);
						PostMessage( dlg, WM_FPUPDATE, 0,0 );
					}
					if(xpos( '"', fnx, 1 ) )
					{
						fprompt_file_info = "/FN=" + fnx;
						SetDlgItemText( dlg, _FN_ID, _LN_PLACEHOLDER );
					}
					break;
				}

		case _FP_SEL_ALL :
		case _FP_SEL_NONE :
				{
					int jx, jz, jy;

					working;
					no_file_update = TRUE;
					SendMessage(GetDlgItem(dlg,_FN_ID), WM_SETREDRAW, 0, 0 );

					jz = GetDlgItem(dlg,_FL_ID);
					SendMessage(jz, WM_SETREDRAW, 0, 0 );
					jx = SendMessage( jz,LB_GETCOUNT,0,0);
					for ( jy = 0; jy < jx; jy++ )
					{
						SendMessage( jz, LB_SETSEL, (wparam == _FP_SEL_ALL),jy);
						SendMessage( dlg, WM_COMMAND, _FL_ID, Make_Long(jz,LBN_SELCHANGE));
					}
					SendMessage(jz, WM_SETREDRAW, 1, 0 );
					RedrawWindow( jz, 0,0, rdw_Invalidate OR rdw_UpdateNow );

					jz = GetDlgItem(dlg,_FN_ID);
					SendMessage(jz, WM_SETREDRAW, 1, 0 );
					RedrawWindow( jz, 0,0, rdw_Invalidate OR rdw_UpdateNow );
					no_file_update = FALSE;
					update_status_line;
					FpSetDefBtn(dlg, 1 );
					break;
				}


		case _FP_OP_COPY :
					 r = FileOpDlg( dlg, _FO_COPY, GetDlgStr( dlg, _FN_ID) );
					 break;

		case _FP_OP_MOVE :
					 r = FileOpDlg( dlg, _FO_MOVE, GetDlgStr( dlg, _FN_ID) );
					 break;

		case _FP_OP_DELETE :
					 r = FileOpDlg( dlg, _FO_DELETE, GetDlgStr( dlg, _FN_ID) );
					 break;

		case _FP_OP_RENAME :
					 r = FileOpDlg( dlg, _FO_RENAME, GetDlgStr( dlg, _FN_ID) );
					 break;

		case _FP_OP_ATTRIBUTE :
					 r = FileOpDlg( dlg, _FO_ATTRIBUTE, GetDlgStr( dlg, _FN_ID) );
					 break;

		case _FP_OP_SEND :
					 if(!MapiEnabled())
					 {
						 MailSendFile( GetDlgStr( dlg, _FN_ID) );
					 }
					 break;

		case _FP_OP_CREATE_DIR :
					 r = FileOpDlg( dlg, _FO_CREATE_DIR, "" );
					 break;

	}
	if(r)
	{
		SetDlgItemText( dlg, _FN_ID, getshortname( fexpand("")) );
		SendDlgItemMessage( dlg, _FL_ID, lb_resetcontent,0,0);
		SetFocus( GetDlgItem(dlg, _FN_ID) );
		PostMessage( dlg, WM_COMMAND, 1, 0 );
	}

	return(result);
}

void FPFilePopup(dlg, x,y)
	trans2
{
	struct trect tr;

	if(!x && !y)
	{
		GetWindowRect(GetDlgItem(dlg, _FP_FILE_ID), &tr );
		x=tr.right;
		y=tr.top;
	}
	int menu = CreatePopupMenu;
	if(Menu)
	{
		AppendMenu( menu, MF_STRING, _FP_OP_COPY    , "&Copy...");
		AppendMenu( menu, MF_STRING, _FP_OP_MOVE    , "&Move...");
		AppendMenu( menu, MF_STRING, _FP_OP_RENAME  , "&Rename...");
		AppendMenu( menu, MF_STRING, _FP_OP_DELETE  , "&Delete...");
		AppendMenu( menu, MF_STRING, _FP_OP_ATTRIBUTE  , "&Attributes...");
		if( !MapiEnabled() )
		{
			AppendMenu( menu, MF_STRING, _FP_OP_SEND    , "&Send...");
		}
		else
		{
			AppendMenu( menu, MF_STRING | MF_GRAYED, _FP_OP_SEND    , "&Send...");
		}
		AppendMenu( menu, MF_SEPARATOR , -1 , "");
		AppendMenu( menu, MF_STRING , _FP_OP_CREATE_DIR  , "Cr&eate directory...");

		TrackPopupMenu( menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y,0,dlg,0 );
		destroymenu( menu );
	}

}

void FPFixDirList( int win, int dlg )
{
	if(UseLongNames)
	{
		int dc = GetDc(win);
		Selectobject( dc, SendMessage(win, wm_getfont, 0, 0) );

		str tstr,tstr2;
		int count = SendMessage( win, lb_getcount, 0, 0);
		int freached = 0;
		int w,width = 0;
		str ds = Caps(RemoveTrailingSlash(Fexpand(""))), dy = "";
		int ti = SendMessage(win, lb_getcursel, 0,0);
		int tt = SendMessage(win, lb_gettopindex, 0,0);
		int jx;

		for(jx = 0; jx < count; jx++)
		{
			SendMessageStr( win,lb_gettext, jx, tstr );
			if(!freached)
			{
				dy = RemoveTrailingSlash(fexpand( AddTrailingSlash(dy) + tstr ));
				if(caps(dy) == ds)
				{
					freached = TRUE;
				}
				tstr2 = Truncate_Path( dy );
				if(tstr2 == "")
					tstr2 = dy;
			}
			else
			{
				tstr2 = Truncate_Path( RemoveTrailingSlash(fexpand( AddTrailingSlash(dy) + tstr )));
			}
			if(tstr2 != tstr)
			{
				SendMessage( win,lb_deletestring, jx, 0 );
				SendMessageStr( win,lb_insertstring, jx, tstr2 );
			}
			w = (GetTextExtent( dc,tstr2,svl(tstr2) ) & 0xffff) + 10;
			if(w > width)
				width = w;
		}

		ReleaseDC(win, dc );
		SendMessage( win,lb_setcursel, ti, 0 );
		SendMessage( win,lb_settopindex, tt, 0 );
		SendMessage( win,lb_sethorizontalext, width, 0 );

		{
			struct trect tr;
			jx = GetDlgItem( dlg, _FP_DIR_ID );
			GetClientRect( jx, &tr );
			tstr = RemoveTrailingSlash(Fexpand(""));
			dc = GetDc( jx );
			ZShortenPath ( tstr, 255, dc, SendMessage(win, wm_getfont, 0, 0), (tr.right - tr.left) )
      releasedc(jx,dc);
			SetWindowText( jx, tstr );
		}
	}
	fpNeedDirList = 0;

}

void FPReFixDirItem( int win, int dlg, int item )
{
	if(UseLongNames)
	{
		str tstr,tstr2;
		int count = SendMessage( win, lb_getcount, 0, 0);
    int freached = 0, old_freached = 0;
		int w,width = 0;
		str ds = Caps(RemoveTrailingSlash(Fexpand(""))), dy = "";
		int ti = SendMessage(win, lb_getcursel, 0,0);
		int tt = SendMessage(win, lb_gettopindex, 0,0);
		int jx;

		for(jx = 0; jx < count; jx++)
		{
			if(!freached)
			{
        SendMessageStr( win,lb_gettext, jx, tstr );
				dy = RemoveTrailingSlash(fexpand( AddTrailingSlash(dy) + tstr ));
				if(caps(dy) == ds)
				{
					freached = TRUE;
				}
				tstr2 = Truncate_Path( GetShortName(dy) );
				if(tstr2 == "")
					tstr2 = dy;
			}
			else
      if(jx == item)
			{
        SendMessageStr( win,lb_gettext, jx, tstr );
				tstr2 = Truncate_Path( GetShortName(RemoveTrailingSlash(fexpand( AddTrailingSlash(dy) + tstr ))));
			}
      if(jx <= item)
			{
        if((jx == item) || (!old_freached))
        {
          if(tstr2 != tstr)
          {
            SendMessage( win,lb_deletestring, jx, 0 );
            SendMessageStr( win,lb_insertstring, jx, tstr2 );
          }
				}
			}
      else
      {
        break;
      }
      old_freached = freached;
		}

		SendMessage( win,lb_setcursel, ti, 0 );
		SendMessage( win,lb_settopindex, tt, 0 );
	}
}


void FPFixFileList( int win, int dlg )
{
	if(UseLongNames)
	{
		str tstr,tstr2;
		int dc = GetDc(win);
		int count = SendMessage( win,lb_getcount, 0, 0);
		int w,width = 0;
		str ds = AddTrailingSlash(Fexpand(""));
		int ti = SendMessage( win, lb_getcursel, 0,0);
		int tt = SendMessage( win, lb_gettopindex, 0,0);
		int jx;
    int drivetype = GetDriveType( ascii( caps(copy(ds,1,1))) - 65);
		Selectobject( dc, SendMessage(win, wm_getfont, 0, 0) );

		for(jx = 0; jx < count; jx++)
		{
			SendMessageStr( win,lb_gettext, jx, tstr );
      if(xpos("~", tstr,1) || xpos(" ", tstr,1) || (drivetype == DRIVE_REMOTE))
		 	{
				tstr2 = Truncate_Path(GetLongName(tstr));
				if(xpos(" ", tstr2,1))
				{
					tstr2 = '"' + tstr2 + '"';
				}
				if(tstr2 != tstr)
				{
					SendMessage( win,lb_deletestring, jx, 0 );
					SendMessageStr( win,lb_insertstring, jx, tstr2 );
				}
			}
			else
			{
				tstr2 = tstr;
			}
			w = (GetTextExtent( dc,tstr2,svl(tstr2) ) & 0xffff) + 10;
			if(w > width)
				width = w;
		}

		ReleaseDC(win, dc );

		SendMessage( win,lb_setcursel, ti, 0 );
		SendMessage( win,lb_settopindex, tt, 0 );
		SendMessage( win,lb_sethorizontalext, width, 0 );

	}
	fpNeedFileList = 0;

}


int DirListProc(   int &retval,
										int window,
										int message,
										int wparam,
                    int lparam,
                    str parms )
{
  int result = 0;
	switch ( message )
	{
		case WM_PAINT :
				if(fpNeedDirList)
				{
					FPFixDirList( window,GetParent(window));
				}
				break;

	}
	return(result);
}

int FileListProc(   int &retval,
										int window,
										int message,
										int wparam,
                    int lparam,
                    str parms )
{
  int result = 0;
	switch ( message )
	{
		case WM_PAINT :
				if(fpNeedFileList)
				{
					FPFixFileList( window,GetParent(window));
				}
				break;

	 case WM_RBUTTONDOWN :
			{
				int cc = SendMessage( window, lb_getselcount, 0, 0 );
				if( (cc != LB_ERR) && (cc > 1) )
				{
				}
				else
				{
					SendMessage( window, WM_LBUTTONDOWN, 0, lparam );
					SendMessage( window, WM_LBUTTONUP, 0, lparam );
				}

				ClientToScreen( window,&lparam );
				fpFilePopup( GetParent(window), lparam & 0xffff, lparam >> 16 );
				result = 1;
				break;
			}
	}
	return(result);
}


int FilePromptHook( int dlg,
										int message,
										int wparam,
										int lparam,
										struct topenfilename oprec )
	trans2 no_break

{

	int jx, jy, jz, result = 0;
		switch ( message )
		{
			case WM_INITDIALOG :
				{
					struct TRECT tr;
					int th, tp;

				//	FileOkMessage = RegisterWindowMessage( FileOkString );
			  //  LbSelChange   = RegisterWindowMessage( LbSelChString );

					if(UseLongNames)
					{
						th = GetDlgItem( dlg, _FP_DIR_LIST_ID );
          	SubClass_With_Macro( th, "DirListProc","" );
					}
					th = GetDlgItem( dlg, _FL_ID );
          SubClass_With_Macro( th, "FileListProc","" );
			    if(( GetVersion AND 0x0000FF00 ) == 0x00005F00)
					{

						th = GetDlgItem( dlg, 5301 );

						GetWindowRect( th, &tr );
						tp = (tr.top << 16) | tr.left;
						ScreenToClient( dlg, &tp );
						GetClientRect( th, &tr );

				 		DestroyWindow( th );

	    			CreateWindowEx(0x000020000 | WS_EX_TRANSPARENT, "STATIC", "",
	              ws_child | ws_visible | ss_simple,
	              tp & 0xffff, tp >> 16, tr.right , tr.bottom, dlg, 5301, app_handle, 0 );

						th = GetDlgItem( dlg, 5333 );

						GetWindowRect( th, &tr );
						tp = (tr.top << 16) | tr.left;
						ScreenToClient( dlg, &tp );
						GetClientRect( th, &tr );

				 		DestroyWindow( th );

	    			CreateWindowEx(0x000020000 | WS_EX_TRANSPARENT, "STATIC", "",
	              ws_child | ws_visible | ss_simple,
	              tp & 0xffff, tp >> 16, tr.right , tr.bottom, dlg, 5333, app_handle, 0 );
					}
					/*
					BringWindowToTop( GetDlgItem(dlg, 5100 ) );
					BringWindowToTop( GetDlgItem(dlg, 5101 ) );
					BringWindowToTop( GetDlgItem(dlg, 5102 ) );
					BringWindowToTop( GetDlgItem(dlg, 5103 ) );
						*/
					str history_str[20] = parse_str("/HIS=", mparm_str),
							mstr;
					int ic;

					for( ic = parse_int('/#=', global_str(history_str)); ic >= 0; ic--)
					{
						mstr = global_str( history_str + str(ic) );
						if( mstr != "")
						{
              if(xpos(" ", mstr, 1))
              {
                mstr = '"' + mstr + '"';
              }
              SendDlgItemMessageStr( dlg, _FN_ID, CB_ADDSTRING, 0, mstr );
						}
					}

          fprompt_last_path = fexpand("");

					call set_dir_history;

          int flags = parse_int("/FLAGS=", mparm_str);


          if ((flags & (_FP_FLAG_FTO | _FP_FLAG_FTO_ND)) == 0)
					{
            //messagebox(0, hex_str(flags), "FLAGS=", mb_ok);
            ShowWindow( GetDlgItem( dlg, _FP_FT ),  SW_HIDE );
            ShowWindow( GetDlgItem( dlg, _FP_FT_TITLE ),  SW_HIDE );
					}
          else
          {
            if ((flags & _FP_FLAG_FTO_ND) == 0)
            {
              mstr = "Default";
              SendDlgItemMessageStr( dlg, _FP_FT, CB_ADDSTRING, 0, mstr);
            }
          }

          mstr = "Dos";
          SendDlgItemMessageStr( dlg, _FP_FT, CB_ADDSTRING, 0, mstr);
          mstr = "Unix";
          SendDlgItemMessageStr( dlg, _FP_FT, CB_ADDSTRING, 0, mstr);
          mstr = "Binary";
          SendDlgItemMessageStr( dlg, _FP_FT, CB_ADDSTRING, 0, mstr);


         if (!(flags & _FP_FLAG_RO))
         {
            SHowWindow( GetDlgItem( dlg, _FP_RO_ID ),  SW_HIDE );
         }

          if (!(flags & _FP_FLAG_OEM))
					{
            SHowWindow( GetDlgItem( dlg, _FP_OEM_ID ),  SW_HIDE );
					}

          if (( flags & _FP_FLAG_SETFT ) && File_Type_Override)
					{
            int ft = File_Type_Override;
            if ( flags & _FP_FLAG_FTO_ND)
            {
              --ft;
            }
            SendDlgItemMessage( dlg, _FP_FT, CB_SETCURSEL, ft, 0 );

					}
					else
					{
            SendDlgItemMessage( dlg, _FP_FT, CB_SETCURSEL, 0, 0 );
					}



					// If a binary record length override field is available, then
					// add a spin button
					th = GetDlgItem(dlg, 5005);
					if(th)
					{
						GetWindowRect( th, &tr );
						tp = (tr.top << 16) | tr.right + 2;
						ScreenToClient( dlg, &tp );
						GetClientRect( th, &tr );

						int spinwin = CreateWindow("mewspin", "1,99,50",
											WS_VISIBLE | WS_CHILD | (MSS_VERTICAL | MSS_TEXTHASRANGE | MSS_INVERTRANGE),
											tp & 0x0ffff, tp >> 16 + 1, 12, tr.bottom - tr.top,
											dlg, 5007, app_handle, 0);

            SubClass_With_Macro( th, "DlgSpinProc",
                "/SPINW=" + str(spinwin) +
                "/MIN=0" +
                "/MAX=" + str(max_line_length) );

						MSHAssociateSet( spinwin, th );

						call set_bin_rec;
					}
          if ((flags & _FP_FLAG_SETOEM) && Oem_Type_Override)
          {
            SendDlgItemMessage ( dlg, _FP_OEM_ID, BM_SETCHECK, Oem_Type_Override - 1, 0);
          }
          else
          {
            SendDlgItemMessage ( dlg, _FP_OEM_ID, BM_SETCHECK, 2, 0);
          }
          SetDlgItemText     ( dlg, _FP_WORK_ID, Fprompt_Work_Dir );
          SendDlgItemMessage ( dlg, _FP_RO_ID, BM_SETCHECK, 2, 0 );
					no_file_update = FALSE;

	// this allows you to run a macro for such purposes as adding or modifying controls in the dialog box
					mstr = parse_str("/INITMAC=", global_str("FT_EXTRA_PARMS"));
					if (svl(mstr)) {
						RM(mstr + " /HDLG=" + str(dlg));
	// allows defining of control id's for extra controls
						set_global_int("FP_EXTRA_CTRL_COUNT", return_int);
					} else {
						set_global_int("FP_EXTRA_CTRL_COUNT",0);
					}


					result = 0;

					FPFixDirList(GetDlgItem( dlg, _FP_DIR_LIST_ID ), dlg );
					FPFixFileList( GetDlgItem( dlg, _FL_ID ),dlg );
					break;
				}

			case WM_ACTIVATE :
				{
					if ( wparam )
					{
						HelpLink_String = parse_str ("/H=", mparm_str);
					}
					else
					{
						helplink_string = "";
					}
					break;
				}

			case WM_FPVALIDATEDIR :
				PostMessage( dlg, wm_command, _FP_OK, 0 );
				if( FPValidateDir( dlg ) == 1 )
				{
					jx = GetDlgItem(dlg,_FP_DIR_ID);
					jz = SendMessage(jx, cb_getcursel, 0, 0);
					if((jz >= 0) && (jz != 0xffff))
					{
						jy = parse_int('/#=', global_str("FPATH_HISTORY")) -	jz;

						SetDlgItemText( dlg, _FN_ID,
							GetShortName(global_str( "FPATH_HISTORY" + str(jy))));
					}
					else
					{
          //SetFocus(GetDlgItem(dlg,_FN_ID));
						SetDlgItemText( dlg, _FN_ID, GetDlgStr(dlg,_FP_DIR_ID));
					}
          if (parse_int("/FLAGS=", mparm_str) & _FP_FLAG_TAG_FILES)
          {
            SendDlgItemMessage(dlg, _FL_ID, LB_SETSEL, 0, 0x0000FFFF );
          }
          else
          {
            SendDlgItemMessage(dlg, _FL_ID, LB_SETCURSEL, -1, 0 );
          }
				}
				result = 1;
				break;

			case WM_FPUPDATE2 :
				PostMessage(dlg, WM_FPUPDATE,0,0);
				break;

			case WM_FPUPDATE :
				FpSetDefBtn(dlg, 1 );
				SetFocus( GetDlgItem(dlg,_FN_ID));
        SendDlgItemMessage(dlg, _FN_ID, CB_SETEDITSEL, 0, make_long(0,-1) );
				break;

			case WM_VKEYTOITEM :
				result = -1;
				if(wparam == VK_DELETE)
					if( (lparam & 0xffff) == GetDlgItem(dlg, _FL_ID))
					{
						postmessage( dlg, wm_command, _FP_OP_DELETE, 0 );
						result = -2;
					}
				break;

			case WM_COMMAND :
				switch ( wparam )
				{
					case _FP_SEL_ALL :
					case _FP_SEL_NONE :
					case _FP_OP_COPY :
					case _FP_OP_MOVE :
					case _FP_OP_RENAME :
					case _FP_OP_DELETE :
					case _FP_OP_SEND :
					case _FP_OP_CREATE_DIR :
					case _FP_OP_ATTRIBUTE :

						call clear_pulldowns;
						result = FPromptOperation( dlg, wparam, lparam, "/FLAGS=" + parse_str("/FLAGS=", mparm_str), oprec );
						break;

          case _FP_CANCEL :
              fprompt_last_path = fexpand("");
              break;

					case _FP_OK :
							fpNeedDirList = 1;
							FPNeedFileList = 1;
							if ( FPLastFocus == _FP_DIR_LIST_ID )
							{
								if(GetWinFlags() & 0x04000)
								{
									FPReFixDirItem( GetDlgItem( dlg, _FP_DIR_LIST_ID ),dlg,
										SendDlgItemMessage(dlg, _FP_DIR_LIST_ID, lb_getcursel, 0,0));
								}
								PostMessage(Dlg, WM_NEXTDLGCTL,
														GetDlgItem(Dlg, 1121), MAKE_LONG(1,0));
								break;
							}

						if(lparam != 0)
							call clear_pulldowns;

						result = FPromptOperation( dlg, wparam, lparam, "/FLAGS=" + parse_str("/FLAGS=", mparm_str), oprec );
						break;

					case _FP_FILE_ID :
						{
							FPFilePopup(dlg,0,0);
							break;
						}

					case _FP_WORK_VIEW :
						{
							fprompt_last_path = "";
							SetDlgItemText( dlg, _FP_DIR_ID, GetDlgStr( dlg, _FP_WORK_ID ) );
							PostMessage( dlg, WM_FPVALIDATEDIR, 0, 0 );
							FpSetDefBtn(dlg, 1 );
							SetFocus( GetDlgItem(dlg,_FN_ID));
							break;
						}

					case _FP_WORK_CHANGE :
						{
							fprompt_work_dir = Fexpand("");
							SetDlgItemText( dlg, _FP_WORK_ID, fprompt_work_dir );
							FpSetDefBtn(dlg, 1 );
							SetFocus( GetDlgItem(dlg,_FN_ID));
							break;
						}

					case _FP_HELP_ID :
						MewHelp_Context (); // mewhelp(parse_str("/H=",mparm_str));
						break;

					case _FL_ID :
							call clear_pulldowns;

							if((lparam >> 16) == LBN_SetFocus)
								FPLastFocus = wparam;

							if(!no_file_update)
							{
								if((lparam >> 16) == LBN_SELCHANGE)
								{
									_FPUpdate( dlg );
									FpSetDefBtn(dlg, 1 );
								}
							}
							break;

					case _FP_DIR_LIST_ID :
							{

								switch ( lparam >> 16 )
								{
									case lbn_dblclk :
									{
										FPNeedDirList = 1;
										FPNeedFileList = 1;
										if(GetWinFlags() & 0x04000)
										{
											FPReFixDirItem( GetDlgItem( dlg, _FP_DIR_LIST_ID ),dlg,
												SendDlgItemMessage(dlg, _FP_DIR_LIST_ID, lb_getcursel, 0,0));
										}
										break;
									}

									case lbn_setfocus :
										FPLastFocus = wparam;
										break;
								}
							}
							break;

					case _FP_DIR_ID :
							switch ( lparam >> 16 )
							{
								case cbn_setfocus :
									FPLastFocus = wparam;
									break;

								case cbn_killfocus :
									fp_dir_closeup = false;
									break;

								case cbn_selchange :
									fp_dir_changed = TRUE;
									if(fp_dir_closeup)
									{
										fp_dir_closeup = false;
										FPNeedDirList = 1;
										FPNeedFileList = 1;
										PostMessage( dlg, WM_FPVALIDATEDIR, 0, 0 );
									}
                  break;

							  case cbn_closeup :
									{
										if(fp_dir_changed)
										{
											FPNeedDirList = 1;
											FPNeedFileList = 1;
											PostMessage( dlg, WM_FPVALIDATEDIR, 0, 0 );
										}
										else
										{
											fp_dir_closeup = TRUE;
										}
									}
									break;

								case cbn_editchange :
									fp_dir_changed = TRUE;
									break;
							}
							break;

					case _FP_DRIVES_ID :
					case _FP_EXT_ID :
							switch ( lparam >> 16 )
							{
									case cbn_setfocus :
										FPLastFocus = wparam;
										break;

									 case cbn_selchange :
										FPNeedDirList = 1;
										FPNeedFileList = 1;
										FpSetDefBtn(dlg, 1 );
										break;

									 case cbn_closeup :
										FPNeedFileList = 1;
									 	break;
							}
							break;

					case _FP_FT :
							case cbn_selchange :
									call set_bin_rec;
									break;

					case _FN_ID :
							switch ( lparam >> 16 )
							{
								case cbn_setfocus :
									FPLastFocus = wparam;
									break;

								case cbn_EditChange :
									{
											int exact_find = false,
													flags = parse_int("/FLAGS=", mparm_str);

											if (flags & _FP_FLAG_NOINCREMENT) {
												break;
											}
											str fn[128];

											FpSetDefBtn(dlg, 1 );
											GetDlgItemText( dlg, _FN_ID, fn, 127 );
												if (flags & _FP_FLAG_TAG_FILES)
												{
													sendDlgItemMessage( dlg, _FL_ID, lb_setsel, false,
															SendDlgItemMessage(dlg, _FL_ID, lb_getcaretindex,0,0) );

													int index = SendDlgItemMessageStr( dlg, _FL_ID, lb_findstringexact, -1, fn);
													if(index < 0)
													{
														index = SendDlgItemMessageStr( dlg, _FL_ID, lb_findstring, -1, fn);
													}
													else
													{
														exact_find = true;
													}
													if(index >= 0)
													{
														sendDlgItemMessage( dlg, _FL_ID, lb_setcaretindex, index, true );
														sendDlgItemMessage( dlg, _FL_ID, lb_setsel, true, index );
													}
												}
												else
												{
													SendDlgItemMessage( dlg, _FL_ID, lb_setcursel, -1, 0 );

													int index = SendDlgItemMessageStr( dlg, _FL_ID, lb_findstringexact, -1, fn);
													if(index < 0)
													{
														index = SendDlgItemMessageStr( dlg, _FL_ID, lb_findstring, -1, fn);
													}
													else
													{
														exact_find = true;
													}
													if(index >= 0)
													{
														SendDlgItemMessage( dlg, _FL_ID, lb_setcursel, index, 0 );
													}
												}
												_FPUpdate( dlg );
											break;
									}
							}
							break;

					default :
	// this is to handle any extra controls added
						if (Global_Int("FP_EXTRA_CTRL_COUNT")) {
							int count;
							for (count = global_int("FP_EXTRA_CTRL_COUNT"); count > 0; --count) {
								if (wparam == global_int("FP_EXTRA_CTRL" + str(count))) {
									str mstr = parse_str("/CTRLMAC=", global_str("FT_EXTRA_PARMS"));
									if (svl(mstr)) {
										RM(mstr + " /HDLG=" + str(dlg) + "/CTRL=" + str(wparam));
									}
								}
							}
						}
						break;

				}
				break;

			case WM_DESTROY :
				{
					fp_Dir_Closeup = 0;
					fpNeedDirList = 0;
					FileOkMessage = 0;
	// for running an exit macro related to extra controls
					str mstr = parse_str("/EXITMAC=", global_str("FT_EXTRA_PARMS"));
					if (svl(mstr)) {
						RM(mstr + " /HDLG=" + str(dlg));
					}
					if (global_int("FP_EXTRA_CTRL_COUNT")) {
						int count;
						for (count = global_int("FP_EXTRA_CTRL_COUNT"); count > 0; --count) {
							set_global_int("FP_EXTRA_CTRL" + str(count),0);
						}
						set_global_int("FP_EXTRA_CTRL_COUNT",0);
					}

					if( caps(truncate_path(GetDlgStr( dlg, _FN_ID))) != _LN_PLACEHOLDER )
						fprompt_file_info = "/FN=" + GetDlgStr( dlg, _FN_ID);

					jx = parse_int("/FLAGS=", mparm_str);
          if (jx & (_FP_FLAG_FTO | _FP_FLAG_FTO_ND))
					{
            File_Type_Override = SendDlgItemMessage (dlg, _FP_FT, CB_GETCURSEL, 0, 0);
            if ( jx & _FP_FLAG_FTO_ND )
            {
              File_Type_Override++;
            }
						int er;
						File_Type_BRL = GetDlgItemInt( dlg, 5005, er, 0);
					}
          if (jx & _FP_FLAG_OEM)
					{
            Oem_Type_Override = IsDlgButtonChecked( dlg, _FP_OEM_ID);
            if ( Oem_Type_Override == 2 )
            {
              Oem_Type_Override = 0;
            }
            else
            {
              Oem_Type_Override = Oem_Type_Override + 1;
            }
					}


					if ((jx & _FP_FLAG_RO))
					{
						fprompt_file_info += "/RO=" + str(IsDlgButtonChecked(dlg, _FP_RO_ID ));
					}
					HelpLink_String = "";

         // make_message(fprompt_last_path);
          //fprompt_last_path = GetDlgStr(dlg, _FP_DIR_ID);
          //fprompt_last_path = fexpand("");


					break;
				}
		}
	return( result );

clear_pulldowns2:
	SendDlgItemMessage( dlg, _FP_EXT_ID, CB_SHOWDROPDOWN, 0, 0 );
	ret;

clear_pulldowns:
	SendDlgItemMessage( dlg, _FN_ID, CB_SHOWDROPDOWN, 0, 0);
	SendDlgItemMessage( dlg, _FP_DRIVES_ID, CB_SHOWDROPDOWN, 0, 0 );
	SendDlgItemMessage( dlg, _FP_DIR_ID, CB_SHOWDROPDOWN, 0, 0 );
	ret;

set_bin_rec:
	{
		int th = GetDlgItem( dlg, 5005 );
		if(th != 0)
		{
			int tx = SendDlgItemMessage(dlg, _FP_FT, CB_GETCOUNT, 0,0) ==
				(SendDlgItemMessage(dlg, _FP_FT, CB_GETCURSEL, 0, 0) + 1);
			EnableWindow( th, tx);
			EnableWindow( GetDlgItem(dlg,5006), tx);
			EnableWindow( GetDlgItem(dlg,5007), tx);
		}
	}
	ret;

set_dir_history:
	{
		struct trect tr;
		str mstr;
		int ic;
		int win = GetDlgItem( dlg, _FP_DIR_ID );
		int tf = SendMessage(win, wm_getfont, 0, 0);


		GetClientRect( win, &tr );
		int dc = GetDc( win );

		for( ic = parse_int('/#=', global_str("FPATH_HISTORY")); ic >= 0; ic--)
		{
			mstr = global_str( "FPATH_HISTORY" + str(ic) );
			if( mstr != "")
			{
				ZShortenPath ( mstr, 255, dc, tf , (tr.right - tr.left) )

        SendMessageStr( win, CB_ADDSTRING, 0, mstr );
			}
		}

    releasedc(win,dc);
		ret;
	}

}


global
{
	int DirDlgFirstUp   "!DIRDLGFIRSTUP";
	str DirSelectReturn "!DIRSELECTRETURN";
	int DirDlgIgnoreOK  "!DIRDLGIGNOREOK";
}

int SelectDirectory( int parent, str &fn, str title[80],
											 str help[80], int flags  )
	trans2
{
	str tstr2[128];

	str tfp = fprompt_last_path;


	struct TOpenFileName oprec;
	struct fileprompt_rec fnr;

	int result,
			jx,jy;


	tstr2 = RemoveTrailingSlash(get_path(fn));

	tstr2  += '|0';

	title += '|0';

	fnr.filespec = "JUNK";
	fnr.filetitle = "JUNK";

	oprec.hWndOwner         = frame_handle;
	oprec.HInstance         = app_handle;
	oprec.lpstrFilter       = 0;
	oprec.lpstrCustomFilter = 0;
	oprec.nMaxCustFilter    = 0;
	oprec.nFilterIndex      = 0;
	oprec.lpstrFile         = &fnr.filespec;
	oprec.nMaxFile          = max_line_length - 1;
	oprec.lpstrFileTitle    = &fnr.filetitle;
	oprec.nMaxFileTitle     = 127;
	oprec.lpstrInitialDir   = &tstr2 + 4;
	oprec.lpstrTitle        = &title + 4;
	oprec.Flags             = ofn_EnableTemplate | ofn_ShowHelp | ofn_NoChangeDir;


	fnr.template = 'SDIR_FPROMPT';

	oprec.nFileOffset       = 0;
	oprec.nFileExtension    = 0;
	oprec.lpstrDefExt       = 0;
	oprec.lCustData         = 0;
	oprec.lpfnHook          = 0;
	oprec.lpTemplateName    = &fnr.template;
	result = 0xff & HookFilePromptWithMacro ( &oprec, "DirectoryHook /FLAGS=" + str(flags) + "/H=" + help);
	flags &= 0x00ff;

	fn = DirSelectReturn;

	DirSelectReturn = "";
	fprompt_last_path = tfp;

	tstr2 = RemoveTrailingSlash(fn);
	if(flags & _DS_FLAG_CD )
	{
		change_dir( tstr2 );
		fprompt_last_path = AddTrailingSlash(tstr2) + "*.*";
	}
	return_str = tstr2;
	rm("HISTORY_LIST /M=1/HISTORY=FPATH_HISTORY");

	return(

	result);
}

int DirectoryHook( int dlg,
										int message,
										int wparam,
										int lparam,
										struct topenfilename oprec )
	trans2 no_break
{

	int jx, jy, jz, result = 0;

	switch ( message )
	{
		case WM_INITDIALOG :
			{
				if(UseLongNames)
				{
					int th = GetDlgItem( dlg, _FP_DIR_LIST_ID );
        	SubClass_With_Macro( th, "DirListProc","" );
				}
				SHowWindow( GetDlgItem( dlg, 1090 ),  SW_HIDE );
				SHowWindow( GetDlgItem( dlg, 1152 ),  SW_HIDE );
				SHowWindow( GetDlgItem( dlg, 1120 ),  SW_HIDE );
				SHowWindow( GetDlgItem( dlg, 1089 ),  SW_HIDE );
				SHowWindow( GetDlgItem( dlg, 1136 ),  SW_HIDE );
				SHowWindow( GetDlgItem( dlg, 1040 ),  SW_HIDE );
				SendMessage(Dlg, WM_NEXTDLGCTL,
										GetDlgItem(Dlg, 1121), MAKE_LONG(1,0));
				SendDlgItemMessage(Dlg, 1121, LB_SETCURSEL, 0, 0);

				int ic;
				str mstr[128];

				for( ic = parse_int('/#=', global_str("FPATH_HISTORY")); ic >= 0; ic--)
				{
					mstr = global_str( "FPATH_HISTORY" + str(ic) );
					if( mstr != "")
					{
						SendDlgItemMessageStr( dlg, _FP_DIR_ID, cb_addstring, 0, mstr );
					}
				}

        //GetDlgItemText( dlg, _FP_DIR_ID, mstr, 127 );
        //fprompt_last_path = mstr;
        fprompt_last_path = fexpand("");

				DirDlgFirstUp = TRUE;
				HelpLink_String = parse_str ("/H=", mparm_str);
				fpNeedDirList = TRUE;
				result = 0;
				break;
			}

		case WM_Paint :
				if (DirDlgFirstUp)
				{
						DirDlgFirstUp = FALSE;
						SendDlgItemMessage(Dlg, 1121, WM_KEYDOWN, 0x28, 0);
						SendDlgItemMessage(Dlg, 1121, WM_KEYUP, 0x28, 0);
				}
				break;

		case WM_COMMAND :
			switch(wparam)
			{
				case _FP_OK :
					{
						fpNeedDirList = TRUE;
						if(DirDlgIgnoreOk)
						{
							DirDlgIgnoreOk = 0;
							return(0);
						}

						if(fp_dir_changed)
						{
							if( FPValidateDir( dlg ) == 1 )
							{
								SetDlgItemText( dlg, _FN_ID, GetShortName(GetDlgStr(dlg,_FP_DIR_ID)));
								DirDlgIgnoreOk = TRUE;
								SendMessage( dlg, wm_command, 1, 0 );
							}
							else
							{
								return(1);
							}
						}

						str tstr;

						tstr = AddTrailingSlash(fexpand(""));
						DirSelectReturn = tstr;
						SetDlgItemText(dlg, _FN_ID, GetShortName(tstr + "xtest.xxx"));
					break;
					}

				case _FP_DIR_LIST_ID :
						{

							switch ( lparam >> 16 )
							{
								case lbn_dblclk :
								{
									FPNeedDirList = 1;
									FPNeedFileList = 1;
									if(GetWinFlags() & 0x04000)
									{
										FPReFixDirItem( GetDlgItem( dlg, _FP_DIR_LIST_ID ),dlg,
											SendDlgItemMessage(dlg, _FP_DIR_LIST_ID, lb_getcursel, 0,0));
									}
									break;
								}

								case lbn_setfocus :
									FPLastFocus = wparam;
									break;
							}
						}
						break;

				case _FP_DIR_ID :
						switch ( lparam >> 16 )
						{
							case cbn_selendok :
							case cbn_selchange :
							case cbn_killfocus :
								fpNeedDirList = TRUE;
								PostMessage( dlg, WM_FPVALIDATEDIR, 0, 0 );
								break;

							case cbn_editchange :
								fp_dir_changed = TRUE;
								break;
						}
						break;

			}
			break;

		case WM_FPVALIDATEDIR :
			if( FPValidateDir( dlg ) == 1 )
			{
				SetDlgItemText( dlg, _FN_ID, GetShortName(GetDlgStr(dlg,_FP_DIR_ID)));
				DirDlgIgnoreOk = TRUE;
				PostMessage( dlg, wm_command, 1, 0 );
			}
			result = 1;
			break;

		case WM_DESTROY :
			{

				fpNeedDirList = FALSE;
				DirDlgIgnoreOk = 0;
				HelpLink_String = "";
				break;
			}
	}
	return( result );
}

/*
void dirtest()
{
	int flags = 0;
	str fn = "";

	SelectDirectory( frame_handle, fn, "Test Dir","", 0 );
	make_message( fn + " " + DirSelectReturn );
}

*/