
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

#DEFINE FILEMGR_HELPLINK "FILE MANAGER OPERATIONS"

#DEFINE _FN_ID        1152
#DEFINE _FL_ID        1120
#DEFINE _FP_DIR_LIST_ID 1121
#DEFINE _FP_OK        1
#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_CD_ID     5010
#DEFINE _FP_FT        5000
#DEFINE _FP_FT_DEF    5001
#DEFINE _FP_FT_DOS    5002
#DEFINE _FP_FT_UNIX   5003
#DEFINE _FP_FT_BINARY 5004
#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



global
{
	str fprompt_file_info "!FPROMPT_FILE_INFO";
  int fprompt_accept "!FPROMPT_ACCEPT";
}


struct fileprompt_rec
{
  asciiz filespec[2048],
         filetitle[128],
         customfilter[128],
         template[20];

}


void StripPath( str &fn )
{
  int jx = 1,kx = 0;
  jx = xpos( ":", fn, 1 );
  while(jx = xpos( "\\", fn, jx + 1 ))
  {
    kx = jx;
  }
  fn = copy(fn, kx + 1, 255 );
}

int FileNamePrompt( str &fn, str title[80],
										str history[20], str help[80],
                    int &flags  ) trans2
{
  str filters[1024], tstr2[128], tstr3[128], ext[3], ext2[3];


  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 ((fn == "") || (caps(fn) == "?NO-FILE?")) {
    no_spec = 1;
  //  fn = global_str( history   + parse_str("/#=", global_str(history)));
    fn = fprompt_last_path;
    if (fn == "") {
      fn = "*.*";
		}
	}

  ext2 = lower(get_extension( fn ));
  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( tstr2 != "default ")
      {
        ++filtercount;
        tstr3 = "";
        jx = 0;
        jy = 1;
        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);
        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 = get_path(fn);
	if((svl(tstr2) > 3) && (str_char(tstr2, svl(tstr2)) == "\\"))
	{
		tstr2 = copy(tstr2, 1, svl(tstr2) - 1);
	}

	tstr2  += '|0';

  StripPath(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 = 127;
  oprec.nFilterIndex = filterindex;
  oprec.lpstrFile = &fnr.filespec;
  oprec.nMaxFile = 2047;
  oprec.lpstrFileTitle = &fnr.filetitle;
  oprec.nMaxFileTitle = 127;
  oprec.lpstrInitialDir = &tstr2 + 4;
  oprec.lpstrTitle = &title + 4;
  oprec.Flags = ofn_EnableTemplate | ofn_ShowHelp | ofn_NoChangeDir;


  if ( flags & _FP_FLAG_TAG_FILES  )
  {
    oprec.Flags |= ofn_AllowMultiSelect;
    fnr.template = 'FILEPROMPT_TAG';
  }
  else
  {
    fnr.template = 'FILEPROMPT';
  }
  if (flags & _FP_FLAG_ACCEPT_WILD) {
// file name validation chokes on multiple wildcard specs
//    oprec.Flags |= ofn_NoValidate;
  }


  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);

  fprompt_accept = 0;

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


  if(fprompt_work_dir != fexpand("")) {
    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 < 128; 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 = fprompt_last_path;
  if((length(return_str) > 3) && (copy(return_str,length(return_str), 1 ) == "\\"))
    return_str = copy(return_str,1,length(return_str) - 1);

  fprompt_last_path = return_str;

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


  flags &= 0x00ff;
  result = result | fprompt_accept;
  if(fprompt_accept)
  {
    fnr.filespec = parse_str("/FN=",fprompt_file_info);
    fprompt_accept = 0;
    if(xpos(" ",fnr.filespec,1))
    {
      tstr2 = get_path(fprompt_last_path);
      if((copy(tstr2,svl(tstr2), 1) == "\\") && (svl(tstr2) > 3))
      {
        tstr2=copy(tstr2,1,svl(tstr2) - 1 );
      }
      fnr.filespec = tstr2 + " " + fnr.filespec;
    }
    else
    {
      fnr.filespec = get_path(fprompt_last_path) + fnr.filespec;
    }

  }

  if(result)
  {
    if ( flags & _FP_FLAG_TAG_FILES  )
    {
      if(jx = xpos(' ',fnr.filespec, 1 ))
      {
        flags |= _FP_FLAG_TAGS;
        create_window;
        result = window_id;
        window_attr = 0x81;
        // make_window_visible (1);
        tstr2 = fexpand(copy( fnr.filespec, 1, jx - 1 ));
        if(copy(tstr2, svl(tstr2), 1) != "\\")
        {
          tstr2 += "\\";
        }
        jy = jx + 1;
        while(jy <= length(fnr.filespec))
        {
          jx = xpos( " ",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);
      }
    }

    fn = fnr.filespec;

    if(!(flags & _FP_FLAG_TAGS) )
    {

      if( !file_exists( fn ) && (flags & _FP_FLAG_DEF_DIR) )
      {
        fn = 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 = fexpand(get_path( fnr.filespec ));
      if(svl(tstr2) > 3)
      {
        if(copy(tstr2,svl(tstr2),1) == "\\" )
        {
          tstr2 = copy(tstr2,1,svl(tstr2) - 1 );
        }
      }
      change_dir( tstr2 );
    }
  }
	fprompt_file_info = "";


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

/*
void ftest()
{
  int flags = 0 | _FP_FLAG_NOINCREMENT;
  str fn = "";

  FileNamePrompt( fn, "",
                      "", "",
                      flags  );


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


void _FPUpdate( int dlg )
{
	str file_str[128] = "12345678.123",
      tstr[128];
  GetDlgItemText( dlg, _FP_DIR_ID, tstr, 127 );
  fprompt_last_path = tstr;
  int jx = SendDlgItemMessage( dlg, _FL_ID, lb_getcaretindex, 0, 0);
  if( SendDlgItemMessage(dlg, _FL_ID, lb_getsel, jx, 0 ) > 0)
  {
    jx = SendDlgItemMessage( dlg, _FL_ID, lb_gettext, jx, &file_str + 4);

    file_str = copy(file_str,1,jx);
    if(copy(tstr,svl(tstr),1) != "\\")
      tstr += "\\";
    file_str = tstr + file_str;
    if(first_file( file_str ) == 0)
    {
      file_str = lower(last_file_name);
      SetDlgItemText( dlg, 5100, file_str );
      call calc_time_date;
      SetDlgItemText( dlg, 5101, tstr );
      SetDlgItemText( dlg, 5102, str( last_file_size ) + " bytes" );
      if (!global_int("!FP_SPECIAL_FLAG")) {
        SendDlgItemMessage( dlg, _FP_RO_ID, bm_setcheck,last_file_attr & 1, 0 );
      }
      tstr = "";
      if(last_file_attr & 1)
        tstr += "R";
      if(last_file_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 = last_file_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 = last_file_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 FPValidateDir( int dlg )
{
  int result = 2;
  str fn[128];

  GetDlgItemText( dlg, _FP_DIR_ID, fn, 127 );
  if( fn != fprompt_last_path )
  {
    if((svl(fn) > 3) && (str_char(fn,svl(fn)) == "\\"))
    {
      fn = copy(fn, 1, svl(fn) - 1 );
    }
    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, fprompt_last_path );
        return(0);
      }
    }
  //  fprompt_last_path = fn;
    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[128],fstr[2048],pstr[128],tstr[128], mstr[128];
  int ix = 1,jx, fcount = 0;
  int delete_ro = 1;
  int do_overwrite = 1;
  int cancel = 0;
  int result = 0;

  GetDlgItemText( w, fid, fstr, 127 );
  if(op != _FO_DELETE)
  {
    GetDlgItemText( w, tid, tstr, 127 );
    if( op != _FO_RENAME )
      if(copy(tstr, svl(tstr), 1) != "\\")
        tstr = tstr + "\\";
  }

  GetDlgItemText( w, pid, pstr, 127 );
  if(copy(pstr, svl(pstr), 1) != "\\")
    pstr = 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;
                }
                if(!first_file(nstr))
                {
                  do
                  {
                    mstr = "Deleting " + last_file_name;
                    SetDlgItemText( w, id, mstr );
                    if(last_file_attr & 0x01)
                    {
                      call get_readonly;
                      if(!delete_ro)
                        goto next_del;
                      set_file_attr( get_path(nstr) + last_file_name,
                       last_file_attr & 0xFE );
                    }
                    Del_File( get_path(nstr) + last_file_name );
                    if(error_level)
                    {
                      break;
                    }
                    ++fcount;
                   next_del:
                  } while(( next_file == 0 ) && (!cancel));
                }
              }
            }
            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;
                }
                if(!first_file(nstr))
                {
                  do
                  {
                    mstr = "Moving " + last_file_name;
                    SetDlgItemText( w, id, mstr );

                    if(file_exists( tstr + last_file_name))
                    {
                      call get_overwrite;
                      if(!do_overwrite)
                        goto next_move;
                    }

                    if( caps(copy(nstr,1,2)) == caps(copy(tstr,1,2)))
                    {
                      if(!rename_file( get_path(nstr) + last_file_name,
                                      tstr + last_file_name))
                      {
                         ++fcount;
                         goto next_move;
                      }
                    }

                    error_level = Copy_File( get_path(nstr) + last_file_name,
                      tstr + last_file_name, FALSE );
                    if(!error_level)
                    {
                      if(last_file_attr & 0x01)
                      {
                        call get_readonly;
                        if(!delete_ro)
                          goto next_move;
                        set_file_attr( get_path(nstr) + last_file_name,
                         last_file_attr & 0xFE );
                      }

                      Del_File( get_path(nstr) + last_file_name );
                      if(error_level)
                      {
                        break;
                      }
                      ++fcount;
                    }
                    else
                    {
                      error_level += 3000;
                    }
                   next_move:
                  } while(( next_file == 0 ) && (!cancel) && (!error_level));
                }

              }
            }
            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;
                }
                if(!first_file(nstr))
                {
                  do
                  {
                    mstr = "Copying " + last_file_name;
                    SetDlgItemText( w, id, mstr );

                    if(file_exists( tstr + last_file_name))
                    {
                      call get_overwrite;
                      if(!do_overwrite)
                        goto next_copy;
                    }
                    error_level = Copy_File( get_path(nstr) + last_file_name,
                      tstr + last_file_name, FALSE );
                    if(!error_level)
                    {
                      ++fcount;
                    }
                    else
                    {
                      error_level += 3000;
                    }
                   next_copy:
                  } while(( next_file == 0 ) && (!cancel) && (!error_level));
                }
              }
            }
            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;
                  }
                  if(!first_file(nstr))
                  {
                    do
                    {
                      mstr = "Setting attribute for " + last_file_name;
                      SetDlgItemText( w, id, mstr );

                      Set_File_Attr( get_path(nstr) + last_file_name,
                                    (last_file_attr & attr_and) | attr_or);
                      if(!error_level)
                      {
                        ++fcount;
                      }
                    } while(( next_file == 0 ) && (!cancel) && (!error_level));
                  }
                }
              }
              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(" ", fstr, ix );
  if(jx == 0)
  {
    jx = svl(fstr) + 1;
  }
  nstr = copy(fstr, ix, jx - 1);
  fstr = copy(fstr, jx + 1, 2048);
  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, last_file_name + " 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, last_file_name + " 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[2048] ) trans2
{
  int result;
  int dlg2;
  int browse_button = false;
  int multiple_files = false;
  int yoff, yoff2 = 4;
  int jx;

  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(" ", 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, fstr , DLG_PosOffset, DLG_PosOffset | DLG_Units | 10, 50, 0, 1000, 0, "/ML=255" );
    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
      {
        if( first_file(fstr) == 0)
        {
          DlgSetInt( dlg2, 1050, (last_file_attr & _FA_READONLY) != 0);
          DlgSetInt( dlg2, 1051, (last_file_attr & _FA_HIDDEN) != 0);
          DlgSetInt( dlg2, 1052, (last_file_attr & _FA_ARCHIVE) != 0);
          DlgSetInt( dlg2, 1053, (last_file_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=255" );
    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=255" );
  }

  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;
}



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) */


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

// 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, 2048);
    call FIX_IT;
  }
  t_str2 = t_str;
  call FIX_IT;

  t_str3 = remove_space(t_str3);

  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;
    }
  }

  t_str3 = t_str3 + t_str2 + " ";
  RET;
}

global
{
  int FileOkMessage;
  int FPLastFocus;
}


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

  int dlg2;


  switch ( wparam )
  {
    case _FP_OK :
        {
          if(SendDlgItemMessage( dlg, _FP_EXT_ID, CB_GETDROPPEDSTATE, 0, 0 ))
          {
            SendDlgItemMessage( dlg, _FP_EXT_ID, CB_SHOWDROPDOWN, 0, 0 );
            return(1);
          }


          str fnx[128];

          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 );
          remove_space(fnx);

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

            int kx,ix,jx, filtercount = global_int("!FP_FILTER_COUNT");
            str fnx2[128];
            fnx2 = fnx;
            StripPath(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
            {
              if ((flags & _FP_FLAG_ACCEPT_WILD) && (n == 2)) {
                result = 2;
              }
              else
              {
                result = 1;
              }
            }
          }
          else if(!xpos(" ", fnx, 1))
          {
            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);
            }
         /*    else if  ((flags & _FP_FLAG_ACCEPT_WILD) && (n == 2)) {
                result = 2;
            } */
              PostMessage( dlg, WM_FPUPDATE2, 0,0 );
          }
          else
          {
            PostMessage( dlg, WM_FPUPDATE, 0,0 );

          }
          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, GetDlgStr( dlg, _FP_DIR_ID ) );
    SendDlgItemMessage( dlg, _FL_ID, lb_resetcontent,0,0);
    SetFocus( GetDlgItem(dlg, _FN_ID) );
    PostMessage( dlg, WM_COMMAND, 1, 0 );
  }

  return(result);
}

void FPFilePopup(dlg)
  trans2
{
  struct trect tr;

  GetWindowRect(GetDlgItem(dlg, _FP_FILE_ID), &tr );
  // ClientToscreen( window_handle, &tp );
  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, tr.right, tr.top,0,dlg,0 );
    destroymenu( menu );
  }

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

{

  int jx, jy, jz, result = 0;

//  if ( message == FileOkMessage )
//  {
//    beep;
//    result = FPromptOperation( dlg, _FP_OK, lparam, "/FLAGS=" + parse_str("/FLAGS=", mparm_str), oprec );
//  }
//  else
  {
    switch ( message )
    {
      case WM_INITDIALOG :
        {
          FileOkMessage = RegisterWindowMessage( FileOkString );
          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 != "")
            {
              SendDlgItemMessageStr( dlg, _FN_ID, cb_addstring, 0, mstr );
            }
          }

          GetDlgItemText( dlg, _FP_DIR_ID, mstr, 127 );
          fprompt_last_path = mstr;

          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 );
            }
          }


          jx = parse_int("/FLAGS=", mparm_str);
          if ((jx & (_FP_FLAG_FTO | _FP_FLAG_FTO_ND)) == 0)
          {
            SHowWindow( GetDlgItem( dlg, _FP_FT ),  SW_HIDE );
            SHowWindow( GetDlgItem( dlg, _FP_FT_DEF ),  SW_HIDE );
            SHowWindow( GetDlgItem( dlg, _FP_FT_DOS ),  SW_HIDE );
            SHowWindow( GetDlgItem( dlg, _FP_FT_UNIX ),  SW_HIDE );
            SHowWindow( GetDlgItem( dlg, _FP_FT_BINARY ),  SW_HIDE );
          }

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

          if (!(jx & _FP_FLAG_CD))
          {
            SHowWindow( GetDlgItem( dlg, _FP_CD_ID ),  SW_HIDE );
          }

          if (( jx & _FP_FLAG_SETFT ) && file_type_override)
          {
            SendDlgItemMessage( dlg, _FP_FT + file_type_override, bm_setcheck, 1, 0 );
          }
          else
          {
            SendDlgItemMessage( dlg, _FP_FT_DEF , bm_setcheck,1, 0 );
          }
          SetDlgItemText(dlg, _FP_WORK_ID, fprompt_work_dir );
          SendDlgItemMessage( dlg, _FP_RO_ID, bm_setcheck,2, 0 );
         /*
          if (!(jx & _FP_FLAG_TAG_FILES))
          {
            jy = GetDlgItem(dlg, _FL_ID );
            SetWindowLong( jy, gwl_Style,
                       GetWindowLong( jy, gwl_Style) & 0xFFFFF7F7 );

          }
          */
          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;
          break;
        }

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

      case WM_FPVALIDATEDIR :
        if( FPValidateDir( dlg ) == 1 )
        {
          PostMessage( dlg, wm_command, _FP_OK, 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, EM_SETSEL, 0, make_long(0,-1) );
        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_OK :

              if ( FPLastFocus == _FP_DIR_LIST_ID )
              {
                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 );
            if (result == 2) {
  // we will only get here if wildcards are allowed.
              PostMessage(dlg, WM_COMMAND, ID_ABORT, ID_OK);
              fprompt_accept = 1;
              result = 1;
            }
            break;

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

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

          case _FP_WORK_CHANGE :
            {
              fprompt_work_dir = GetDlgStr( dlg, _FP_DIR_ID );
              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_setfocus :
                  FPLastFocus = wparam;
                  break;
              }
              break;

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

                case cbn_killfocus :
                  //make_message(str(FPLastFocus));

              //  case cbn_closeup :
                case cbn_selchange :
                case cbn_selendok :
                  PostMessage( dlg, WM_FPVALIDATEDIR, 0, 0 );
                  break;
              }
              break;

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

                   case cbn_selchange :
                    FpSetDefBtn(dlg, 1 );
                    break;
               //  case cbn_closeup :
               //   PostMessage( dlg,WM_FPUPDATE,0,0 );
               //   break;
              }
              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 );
                      remove_space(fn);
                      if(!xpos(" ", fn, 1))
                      {
                        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))) {
                  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 :
        {
          FileOkMessage = 0;
  // for running an exit macro related to extra controls
          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);
          }

          fprompt_file_info = "/FN=" + GetDlgStr( dlg, _FN_ID);

          jx = parse_int("/FLAGS=", mparm_str);
          if ((jx & (_FP_FLAG_FTO | _FP_FLAG_FTO_ND)))
          {
            if(IsDlgButtonChecked( dlg, _FP_FT_DEF  ))
              file_type_override = 0;
            else if(IsDlgButtonChecked( dlg, _FP_FT_DOS  ))
              file_type_override = 1;
            else if(IsDlgButtonChecked( dlg, _FP_FT_UNIX  ))
              file_type_override = 2;
            else if(IsDlgButtonChecked( dlg, _FP_FT_BINARY  ))
              file_type_override = 3;
          }

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

          if ((jx & _FP_FLAG_CD))
          {
            fprompt_file_info += "/CD=" + str(IsDlgButtonChecked(dlg, _FP_CD_ID ));
          }
          HelpLink_String = "";

          fprompt_last_path = GetDlgStr(dlg, _FP_DIR_ID);

          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;

}


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

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 = get_path(fn);
	if((svl(tstr2) > 3) && (str_char(tstr2, svl(tstr2)) == "\\"))
	{
		tstr2 = copy(tstr2, 1, svl(tstr2) - 1);
	}

	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          = 2047;
  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 = fn;
  if((svl(tstr2) > 3) && (copy(tstr2,svl(tstr2),1) == "\\"))
  {
    tstr2 = copy(tstr2,1,svl(tstr2)-1);
  }
  if(flags & _DS_FLAG_CD )
  {
    change_dir( tstr2 );
    fprompt_last_path = 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 :
			{

        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;

        DirDlgFirstUp = TRUE;
        HelpLink_String = parse_str ("/H=", mparm_str);
        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 :
        case 1 :
          {
            str fnx[128];

            int n = FPValidateDir( dlg );
          /*  if( n == 1 )
            {
              GetDlgItemText( dlg, _FP_DIR_ID, fnx, 127 );
              fprompt_last_path = fnx;
              SetDlgItemText( dlg, _FN_ID, fprompt_last_path );
              break;
            } */
            if( n == 0)
            {
              result = 1;
              setfocus( GetDlgItem( dlg, _FP_DIR_ID ));
              break;
            }
          }
          break;

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

        break;

        /*
    case WM_FPVALIDATEDIR :
      if( FPValidateDir( dlg ) == 1 )
      {
        PostMessage( dlg, wm_command, 1, 0 );
      }
      result = 1;
      break;
          */
		case WM_DESTROY :
			{
        str tstr;
        GetDlgItemText( dlg, _FP_DIR_ID, tstr, 254 );
        tstr = fexpand(tstr);
        if(copy(tstr,svl(tstr),1) != "\\")
        {
          tstr += "\\";
        }
        DirSelectReturn = tstr;

        HelpLink_String = "";
				break;
			}
	}
  return( result );
}

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

  SelectDirectory( frame_handle, fn, "Test Dir","", _DS_FLAG_CD );
  make_message( fn + " " + DirSelectReturn );
}
*/