

def file_copy(path)
    if msystem("uname -s").index("CYGWIN")
        if msystem("cygpath -w -a #{adir_path}") == msystem("cygpath -w -a #{path}")
            message("source and distination is same directory")
            return nil
        end
    end
    
    if path[-1] == "/"[0] || marking(adir())
        if !File.exist?(path)
            strings = ["Yes", "No"]
            if select_string("#{path} does not exist. would you like to create this directory?", strings, 1) == 0
                FileUtils.mkdir_p(path)
            end
        end
        if File.directory?(path)
            copy_p(adir_path(), adir_mark(), path, true)
            reread(0)
            reread(1)
        end
    else
        copy_p(adir_path(), adir_mark(), path, true)
        reread(0)
        reread(1)
    end
end

def copy_cursor_or_mark_file()
    if is_one_dir()
        cmdline_c('%Q%r%o file_copy %D', -1, nil)
    else 
        if $option_afu_copy
            if marking(adir())
                file_copy sdir_path()
            else
                cmdline_c('%Q%r%o file_copy %D2', -1, nil)
            end
        else
            cmdline_c('%Q%r%o file_copy %D2', -1, nil)
        end
    end
end

def copy_cursor_or_mark_file2()
    cmdline_c('%Q%r%o file_copy %D', -1, nil)
end

def copy_cursor_or_mark_file3()
    cmdline_c('%Q%r%o file_copy %D2', -1, nil)
end

def copy_mark_or_cursor_file_to_tab()
    if tab_max() > 0
        select_str = []

        n = 0
        while n < tab_max()
            select_str.push(tab_path(n))

            n += 1
        end

        select_num = select_menu_mfiler("copy distination", select_str)

        if select_num != -1
            file_copy(select_str[select_num])
        end
    end
end

def copy_mark_or_cursor_file_to_jmenu()
    if $directory_menu.size > 0
        select_str = []
        select_dir = []

        $directory_menu.each() { |item|
            select_str.push(item[0])
            select_dir.push(item[2])
        }

        select_num = select_menu_mfiler("copy distination", select_str)

        if select_num != -1
            file_copy(select_dir[select_num])
        end
    end
end

def copy_mark_or_cursor_file_to_history()
    if $my_dir_history.size > 0
        select_str = []

        $my_dir_history.each() { |item|
            select_str.push(item)
        }

        select_num = select_menu_mfiler("copy distination", select_str)

        if select_num != -1
            file_copy(select_str[select_num])
        end
    end
end

if `uname -s`.chomp() == "FreeBSD" || `uname -s`.chomp() == "Darwin"
    CP_OPTION = "-Rp"
else                        # cygwin || Linux
    CP_OPTION = "-Rpd"
end

def copy_mark_or_cursor_with_cp()
    if is_one_dir()
        cmdline_c("cp #{CP_OPTION} %m %D", -1, nil)
    else 
        cmdline_c("cp #{CP_OPTION} %m %D2", -1, nil)
    end
end

def copy_mark_or_cursor_with_cp_background()
    if is_one_dir()
        cmdline_c("%s cp #{CP_OPTION} %m %D &", -3, nil)
    else 
        cmdline_c("%s cp #{CP_OPTION} %m %D2 &", -3, nil)
    end
end

defmenu("copy_menu",
    "copy(1) current directory", KEY_1,  "copy_cursor_or_mark_file3()",
    "copy(2) other directory", KEY_2,  "copy_cursor_or_mark_file2()",
    "(h)istory", KEY_h, "copy_mark_or_cursor_file_to_history()",
    "jump (m)enu", KEY_m, "copy_mark_or_cursor_file_to_jmenu()",
    "(t)ab",  KEY_t,  "copy_mark_or_cursor_file_to_tab()",
    "(c)p",  KEY_c,  "copy_mark_or_cursor_with_cp()",
    "(C)p background",  KEY_C,  "copy_mark_or_cursor_with_cp_background()"
)

def file_move(path)
    if msystem("uname -s").index("CYGWIN")
        if msystem("cygpath -w -a #{adir_path}") == msystem("cygpath -w -a #{path}")
            message("source and distination is same directory")
            return nil
        end
    end
    
    if path[-1] == "/"[0]
        if !File.exist?(path)
            strings = ["Yes", "No"]
            if select_string("#{path} does not exist. would you like to create this directory?", strings, 1) == 0
                FileUtils.mkdir_p(path)
            end
        end
        
        if File.directory?(path)
            move(adir_path(), adir_mark(), path, true)
            reread(0)
            reread(1)
        end
    else
        move(adir_path(), adir_mark(), path, true)
        reread(0)
        reread(1)
    end
end

def move_mark_or_cursor_file()
    if is_one_dir() 
        cmdline_c('%Q%r%o file_move %D', -1, nil)
    else 
        if $option_afu_copy
            if marking(adir())
                file_move sdir_path()
            else
                cmdline_c('%Q%r%o file_move %D2', -1, nil)
            end
        else
            cmdline_c('%Q%r%o file_move %D2', -1, nil)
        end
    end
end

def move_mark_or_cursor_file2()
    cmdline_c('%Q%r%o file_move %D', -1, nil)
end

def move_mark_or_cursor_file_to_tab()
    if tab_max() > 0
        select_str = []

        n = 0
        while n < tab_max()
            select_str.push(tab_path(n))

            n += 1
        end

        select_num = select_menu_mfiler("move distination", select_str)

        if select_num != -1
            file_move select_str[select_num]
        end
    end
end

def move_mark_or_cursor_file_to_jmenu()
    if $directory_menu.size > 0
        select_str = []
        select_dir = []

        $directory_menu.each() { |item|
            select_str.push(item[0])
            select_dir.push(item[2])
        }

        select_num = select_menu_mfiler("move distination", select_str)

        if select_num != -1
            file_move select_dir[select_num]
        end
    end
end

def move_mark_or_cursor_file_to_history()
    if $my_dir_history.size > 0
        select_str = []

        $my_dir_history.each() { |item|
            select_str.push(item)
        }

        select_num = select_menu_mfiler("move distination", select_str)

        if select_num != -1
            file_move select_str[select_num]
        end
    end
end

def move_mark_or_cursor_file_with_mv()
    if is_one_dir()
        cmdline_c("mv %m %D", -1, nil)
    else 
        cmdline_c("mv %m %D2", -1, nil)
    end
end

def move_mark_or_cursor_file_with_mv_background()
    if is_one_dir()
        cmdline_c("%s mv %m %D &", -3, nil)
    else 
        cmdline_c("%s mv %m %D2 &", -3, nil)
    end
end

def key_move_history()
    move_mark_or_cursor_file_to_history()
end

def key_move_jmenu()
    move_mark_or_cursor_file_to_jmenu()
end

def key_move_tab()
    move_mark_or_cursor_file_to_tab()
end

def key_move_mv()
    move_mark_or_cursor_file_with_mv()
end

defmenu("move_menu",
    "move(1) current directory", KEY_1,  "move_mark_or_cursor_file()",
    "move(2) other directory", KEY_2,  "move_mark_or_cursor_file2()",
    "(h)istory", KEY_h, "move_mark_or_cursor_file_to_history()",
    "jump (m)enu", KEY_m, "move_mark_or_cursor_file_to_jmenu()",
    "(t)ab",  KEY_t,  "move_mark_or_cursor_file_to_tab()",
    "(m)v",  KEY_m,  "move_mark_or_cursor_file_with_mv()",
    "(M)v background",  KEY_M,  "move_mark_or_cursor_file_with_mv_background()"
)

def delete_mark_or_cursor_file()
    remove(adir_path(), adir_mark(), true)
    reread(adir())
end

def throw_mark_or_cursor_file()
    trashbox(adir_path(), adir_mark(), true)
    reread(adir())
end

def delete_mark_or_cursor_file_with_rm()
    cmdline_c('rm -R %m', 0, nil)
end

def delete_mark_or_cursor_file_with_rm_background()
    cmdline_c('%s rm -R %m &', 0, nil)
end

defmenu('delete_menu',
    "(t)rashbox", KEY_t, "throw_mark_or_cursor_file()",
    "(d)elete", KEY_d, "delete_mark_or_cursor_file()",
    "(r)m",     KEY_r, "delete_mark_or_cursor_file_with_rm()",
    "(R)m background", KEY_R, "delete_mark_or_cursor_file_with_rm_background()"
)

def rename(cname, fname)
    if File.exist?(adir_path() + fname)
        message("file exists(" + fname + ")")
        return false
    end

    begin
        File.rename(cname, fname)
    rescue
        message("rename failed")
        return false
    end
    reread(adir())
    cursor_move(adir(), file_num(adir(), fname))
    
    return true
end

def rename2(cname, fname)
    if File.exist?(adir_path() + fname)
        message("file exists(" + fname + ")")
        return false
    end

    begin
        File.rename(cname, fname)
    rescue
        message("rename failed")
        return false
    end
    
    return true
end

def rename_cursor_or_mark_file()
    if marking(adir())
        rename_mark_file()
    else
        rename_cursor_file()
    end
end

def rename_cursor_file()
    if !marking(adir())
        p = 0
        if cursor_name()[0] != "."[0]
            ret = cursor_name().rindex(".")
            if ret
                p = cursor_name().length - ret
            end
        end
        
        cmdline_c('%Q%r rename %f, %f', -1 -p, nil)
    end
end

def rename_cursor_file2()
end

def rename_mark_file()
    cmdline_c("%r%Q gsub_rename //, \"\"", -5, nil)
end

def gsub_rename(from, to)
=begin
    ret1 = input_box("from", "", 0)
    if ret1[0] == 1
        return
    end
    from = ret1[1]
    
    ret2 = input_box("to", "", 0)
    if ret2[0] == 1
        return
    end
    to = ret2[1]
=end
    
    adir_mark2 = []
    adir_mark().each {|file|
        begin
            file2 = file.gsub(from, to)
        rescue
            message("regex error")
            mclear_immediately()
            return
        end
        
        adir_mark2.push(file2)
    }
    
    ### kakuninn ###
    maxx = mgetmaxx()
    maxy = mgetmaxy()
    
    i = 0
    while i < adir_mark2.size() 
        maxx = mgetmaxx()
        maxy = mgetmaxy()
        
        mclear()
        mfiler_view()
        
        mbox(0, 0, maxx-1, maxy-2)
        line = 0
        while line*2+2 < maxy-2 && i < adir_mark2.size()
            mmvprintw(line*2+1, 1, adir_mark()[i])
            mmvprintw(line*2+2, 1, ' -> ' + adir_mark2[i])
            line+=1
            i+=1
        end
        
        if i < adir_mark2.size()
            message("HIT ANY KEY")
        end
    end
    
    ret3 = select_string("rename ok?", ["Yes", "No"], 1)
    
    if ret3 == 1
        return
    end
    
    i = 0
    adir_mark_ = adir_mark().clone
    while i < adir_mark_.size()
        fnum = file_num(adir(), adir_mark_[i])
        if adir_mark_[i] != adir_mark2[i] 
            if !rename2(adir_mark_[i], adir_mark2[i])
                break
            end
        end
        
        mark(adir(), fnum, false)
        i+=1
    end
    
    reread(adir())
end

def backup_mark_file()
    adir_mark().each do |fname| 
        result = select_string("Would you like to make " + fname + ".bak?", ["Yes", "No"], -1)
        if result == 0
            copy_p(adir_path(), [fname], fname + ".bak", true)
        end
    end

    reread(adir())
end

def backup_cursor_file()
    if cursor_name().index("'")
        cmdline_c("%Q%r copy_p(adir_path(), adir_mark(), \"#{cursor_name_convert()}.bak\", true); reread(0); reread(1)", -30, nil)
    else
        cmdline_c("%Q%r copy_p(adir_path(), adir_mark(), '#{cursor_name_convert()}.bak', true); reread(0); reread(1)", -30, nil)
    end
end

def backup_cursor_or_mark_file()
    if marking(adir())
        backup_mark_file()
    else
        backup_cursor_file()
    end
end


def pack_mark_or_cursor_file()
    if is_one_dir()
        if marking(adir())
            if adir_path().index("'")
                cmdline_c("tar cvfz \"#{adir_path_convert()}.tgz\" %m", -8, nil)
            else
                cmdline_c("tar cvfz '#{adir_path_convert()}.tgz' %m", -8, nil)
            end
        else
            if adir_path().index("'") || File.basename(cursor_noext()).index("'")
                cmdline_c("tar cvfz \"#{adir_path_convert() + File.basename(cursor_noext_convert())}.tgz\" %m", -8, nil)
            else
                cmdline_c("tar cvfz '#{adir_path_convert() + File.basename(cursor_noext_convert())}.tgz' %m", -8, nil)
            end
        end
    else
        if marking(adir())
            if sdir_path().index("'")
                cmdline_c("tar cvfz \"#{sdir_path_convert()}.tgz\" %m", -8, nil)
            else
                cmdline_c("tar cvfz '#{sdir_path_convert()}.tgz' %m", -8, nil)
            end
        else
            if sdir_path().index("'") || File.basename(cursor_noext()).index("'")
                cmdline_c("tar cvfz \"#{sdir_path_convert() + File.basename(cursor_noext_convert())}.tgz\" %m", -8, nil)
            else
                cmdline_c("tar cvfz '#{sdir_path_convert() + File.basename(cursor_noext_convert())}.tgz' %m", -8, nil)
            end
        end
    end
end

def pack_mark_or_cursor_file2()
    if marking(adir())
        cmdline_c("tar cvfz '.tgz' %m", -8, nil)
    else
        if File.basename(cursor_noext()).index("'")
            cmdline_c("tar cvfz \"#{File.basename(cursor_noext_convert())}.tgz\" %m", -8, nil)
        else
            cmdline_c("tar cvfz '#{File.basename(cursor_noext_convert())}.tgz' %m", -8, nil)
        end
    end
end

def make_dir(fname)
    if File.exist?(adir_path() + fname)
        message("file exists")
        return
    end

    begin
        #Dir.mkdir(adir_path() + fname, 0755)
        FileUtils.mkdir_p(adir_path() + fname)
    rescue
        message("make_dir() failed")
    end

    reread(adir())
    if fname.index("/")
        cursor_move(adir(), file_num(adir(), fname[0..fname.index("/")-1]))
    else
        cursor_move(adir(), file_num(adir(), fname))
    end
end

def make_directory()
   cmdline_noconvert("%r%Q make_dir ''", -1, nil)
end

def make_new_file(fname)
    if File.exist?(adir_path() + fname)
        message("file exists")
        return
    end

    begin 
        f = File.new(adir_path() + fname,File::CREAT|File::TRUNC|File::WRONLY)
        #f.chmod(0644)
        f.close()
    rescue
        message("make_new_file() failed")
    end
    reread(adir())
    cursor_move(adir(), file_num(adir(), fname))
end

def make_new_file_cmdline()
    cmdline_noconvert("%r%Q make_new_file ''", -1, nil)
end

def make_new_link(src, dest)
    if File.exist?(dest) && File.stat(dest).directory?
        if dest[dest.length-1] != "/"[0]
            dest = dest + "/"
        end

        if src =~ /\/\/.+\/.+/
            bname = src.scan(/\/\/.+\/(.+)/)[0][0]
        else
            bname= File.basename(src)
        end

        dest = dest + bname
    end

    if File.exist?(dest)
        message("file exists")
        return
    end

    begin 
        File.symlink(src, dest)
    rescue
        message("make_new_link() failed")
    end
end

def make_new_link_mark(src, dest)
    if !File.exist?(dest) || !File.stat(dest).directory?
        message("distination is not directory")
        return
    end

    if dest[dest.length-1] != "/"[0]
        dest = dest + "/"
    end

    begin
        mark_num_ = mark_num(adir())
        progress_mark = mark_num(adir())
        
        src.each {|path|
            if path =~ /\/\/.+\/.+/
                fname = path.scan(/\/\/.+\/(.+)/)[0][0]
            else
                fname = File.basename(path)
            end
            
            cursor_move(adir(), file_num(adir(), fname))
            
            ### draw progress box ###
            mfiler_view()
            
            maxx = mgetmaxx()
            maxy = mgetmaxy()
            
            y = maxy / 2
            
            mbox(y, (maxx-22)/2, 22, 3)
            mmvprintw(y, (maxx-22)/2+2, "progress")
            mmvprintw(y+1, (maxx-22)/2+1, "(%d/%d) files", progress_mark, mark_num_)
            mrefresh()
            
            ### make sym link ###
            File.symlink(path, dest + fname)
            
            fname2 = path[adir_path().length..-1]
            mark(adir(), file_num(adir(), fname2), false)
            progress_mark-=1
        }
    rescue
        message("make_new_link_mark() failed")
    end
    
    mfiler_view()
    mrefresh()
end

def make_link()
    if is_one_dir() 
        if marking(adir())
            cmdline_c("%r%Q%o make_new_link_mark(adir_mark_fullpath(), %D); reread(0); reread(1)", -24, nil);
        else
            cmdline_c("%r%Q%o make_new_link(%F, %D); reread(0); reread(1)", -24, nil)
        end
    else 
        if $option_afu_copy
            if marking(adir())
                make_new_link_mark(adir_mark_fullpath(), sdir_path())
                reread(0)
                reread(1)
            end
        else
            if marking(adir())
               cmdline_c('%r%Q%o make_new_link_mark(adir_mark_fullpath(), %D2); reread(0); reread(1)', -24, nil)
            else
                cmdline_c("%r%Q%o make_new_link(%F, %D2); reread(0); reread(1)", -24, nil)
            end
        end
    end
end

defmenu("osx_make_link",
    "make (s)ymbolic link in current directory", KEY_s, "make_link2",
    "make (a)lias", KEY_a, "make_osx_alias"
)

def mkalias(fname, dist)
    if dist[-1] != "/"[0]
        dist = dist + "/"
    end

    shell("%q mkalias \"#{fname}\" \"#{dist}#{fname}\"", fname)
end

def mkalias_marking(dist)
    if dist[-1] != "/"[0]
        dist = dist + "/"
    end

    adir_mark().each do |fname|
        shell("%q mkalias \"#{fname}\" \"#{dist}#{fname}\"", fname)
    end
end

def make_osx_alias()
    if is_one_dir()
        if marking(adir())
            cmdline_c("%r%q mkalias_marking %D", -1, nil)
        else
            cmdline_c("%r%q mkalias %f, %D", -1, nil)
        end
    else
        if $option_afu_copy
            if marking(adir())
                mkalias_marking sdir_path
            end
        else
            if marking(adir())
                cmdline_c("%r%q mkalias_marking %D2", -1, nil)
            else
                cmdline_c("%r%q mkalias %f, %D2", -1, nil)
            end
        end
    end
end

def make_link2()
    if !marking(adir())
        cmdline_c("%r%Qmake_new_link(%F, ''); reread(0); reread(1)", -24, nil)
    end
end

def make_link_menu()
    if `uname -s`.index("Darwin")
        menu("osx_make_link")
    else
        make_link2()
    end
end

def unpack_gz
    if cursor_name().rindex(".tar.gz")
        if is_one_dir() 
            cmdline_c('tar xvfz %f -C %D', -1, nil)
        else
            cmdline_c('tar xvfz %f -C %D2', -1, nil)
        end
    else
        cmdline_c('gzip -d %F', -1, nil)
    end
end

def unpack_gz2()
    if cursor_name().rindex(".tar.gz")
        cmdline_c('tar xvfz %f -C %D', -1, nil)
    else
        cmdline_c('gzip -d %F', -1, nil)
    end
end

def unpack_bz2()
    if cursor_name().rindex(".tar.bz2")
        if is_one_dir()
            cmdline_c('tar xvfj %f -C %D', -1, nil)
        else
            cmdline_c('tar xvfj %f -C %D2', -1, nil)
        end
    else
        cmdline_c('bzip2 -d %f', -1, nil)
    end
end

def unpack_bz22()
    if cursor_name().rindex(".tar.bz2")
        cmdline_c('tar xvfj %f -C %D', -1, nil)
    else
        cmdline_c('bzip2 -d %f', -1, nil)
    end
end

def unpack_tar()
    if is_one_dir()
        cmdline_c('tar xvf %f -C %D', -1, nil)
    else
        cmdline_c('tar xvf %f -C %D2', -1, nil)
    end
end

def unpack_tar2()
    cmdline_c('tar xvf %f -C %D', -1, nil)
end

def unpack_tgz()
    if is_one_dir()
        cmdline_c('tar xvfz %f -C %D', -1, nil)
    else
        cmdline_c('tar xvfz %f -C %D2', -1, nil)
    end
end

def unpack_tgz2()
    cmdline_c('tar xvfz %f -C %D', -1, nil)
end

def unpack_lzh_main(fname, directory)
    cwd = Dir.pwd
    Dir.chdir(directory)
    
    shell('lha x ' + fname, "lha")
    
    Dir.chdir(cwd)
end

def unpack_lzh_main_sudo(fname, directory)
    cwd = Dir.pwd
    Dir.chdir(directory)
    
    shell('sudo lha x ' + fname, "lha")
    
    Dir.chdir(cwd)
end

def unpack_lzh()
    if is_one_dir()
        cmdline_c('%S cd %D; lha x %F', adir_path().size() + 8, nil)
    else
        cmdline_c('%S cd %D2; lha x %F', sdir_path().size() + 8, nil)
    end
end

def unpack_lzh2()
    cmdline_c('%S cd %D; lha x %F', adir_path().size() + 8, nil)
end

def unpack_zip()
    if is_one_dir()
        cmdline_c('unzip %f -d %D', -1, nil)
    else
        cmdline_c('unzip %f -d %D2', -1, nil)
    end
end

def unpack_zip2()
    cmdline_c('unzip %f -d %D', -1, nil)
end

def glob_star_nodir()
    cmd = ""
    
    Dir.glob("*").each do |fname|
        if !File.directory?(fname)
            cmd = cmd + fname + " "
        end
    end
    
    cmd = cmd[0..-2]
    
    return cmd
end

def glob_star()
    cmd = ""
    
    Dir.glob("*").each do |fname|
        if fname != "." && fname != ".."
            cmd = cmd + fname + " "
        end
    end
    
    cmd = cmd[0..-2]
    
    return cmd
end

def grep_current_directory()
    if marking(adir())
        cmdline_c("%q grep '' %m -n 2> /dev/null | $PAGER", 10, nil)
    else
        cmdline_c("%q%S grep '' * -n 2> /dev/null | $PAGER", 12, nil)
    end
end

def grep_recursive()
    if marking(adir())
        if `uname -s`.chomp() == "Linux" || `uname -s`.index("CYGWIN") || `uname -s`.index("Darwin")
            cmdline_c("%q grep -R '' %m -n 2> /dev/null | $PAGER", 13, nil)
        else
            cmdline_c("%q find . | xargs grep -n '' 2> /dev/null | $PAGER", 28, nil)
        end
    else
        if `uname -s`.chomp() == "Linux" || `uname -s`.index("CYGWIN") || `uname -s`.index("Darwin")
            cmdline_c("%q%S grep -R '' * -n 2> /dev/null | $PAGER", 15, nil)
        else
            cmdline_c("%q find . | xargs grep -n '' 2> /dev/null | $PAGER", 28, nil)
        end
    end
end

def mgrep_current_directory()
    if marking(adir())
        directory_exist = false
        adir_mark.each do |fname|
            if File.directory?(fname)
                directory_exist = true
            end
        end

        if directory_exist
            mgrep_recursive()
        else
            cmdline_c("%q%r mgrep \"grep -n ''\", ENV['EDITOR'], '+', true", 22, nil)
        end
    else
        cmdline_c("%q%r mgrep \"grep -n '' * 2>&1 | tee '#{ENV['MTEMP']}'/mfiler_out_of_grep\", ENV['EDITOR'], '+', false", 22, nil)
    end
end

def mgrep_recursive()
    if marking(adir())
        cmdline_c("%q%r mgrep \"grep -R -n ''\", ENV['EDITOR'], '+', true", 25, nil)
    else
        cmdline_c("%q%r mgrep \"grep -R -n '' * 2>&1 | tee '#{ENV['MTEMP']}'/mfiler_out_of_grep\", ENV['EDITOR'], '+', false", 25, nil)
    end
end

def info_directory()
    cmdline_c('du -sh %f', 7, nil)
end

def info_file()
    cmdline_c('%r puts `file %f`; print "file name encode: "; puts encode_type(cursor_name)', 0, nil)
end

