corz.org front page. welcome! cor's blog, aka 'corzblog'. I write stuff here.. downloads of all shapes and sizes, documents, secret chasms, you name it.. developing sites, software, stuff.. updates generally get posted here. music is everywhere, sometimes I pin it down.. soul-candy, captured things you can look at.. 'Mathematics For Women' copyright Cor 1994 ;o)
the power to serve, at home or anywhere. webmasters tricks, tips, tools and resources. the devil's work, or a capable multimedia desktop, you decide..
information and search
contact page for corz.org, ways to get $hit to me.. get a print friendly version of this page, probably.. Put YOUR money where MY mouth is!
 
corz.org text viewer..
[currently viewing: /public/machine/source/windows/AutoIt Includes/corz_essentials.au3 - raw]
 
#include-once
; feel free to tap into this in your apps, I do.

#cs

  corz essential functions v0.5.2
  (c) corz.org 2007


    function list..

        [see the functions themselves for more detailed usage instructions]

        BubbleSort( array )
        InsertionSort( array )
        ShellSort( array )

        MaxMax(int/float{num1), int/float{num2} [, int/float{num2})]
        MinMin(int/float{num1), int/float{num2} [, int/float{num2})]


        BaseName ( string {file/folder path} )
        GetExtension( string {file path} )
        RemoveExtension( string {file path} )
        CleanName( string {file path} )
        GetParent( string {file/folder path} )

        FolderIsEmpty( string {directory path} )
        IsDir( string {directory path} )
        ReadDir ( string {folder path}, string {extensions to return {wildcards allowed}})
            NOTE: This now returns an "AutoIt array"
        RecurseDir(string {folder path}, string {file masks[, bool {$dont_recurse=false}[, string {path to dump file}[, bool {$return_dirs=false}]]])

        GrabCommentsFromIniSection( string{path to ini file}, string{ini section}[, bool{make array}[, string{ignore lines containing this}]])
        WriteCommentsToIniSection( string{path to ini file}, string{ini section}, string{comments to write})

        IniReadCheckBoxValue( string {ini file path}, string {"section"}, string {"key"}, string {"default value"} )
        IniWriteCheckBoxValue( string {ini file path}, string {"section"}, string {"key"}, string {"value"} )
        IniKeyExists( array (probably output from IniReadSeaction), string {key to search for})
        InArray ( array{to search}, string{to find} ) 
        MakeDummyArray ( string )

        SaveSizePos(window handle, string{ini path}, string {ini section}[, int{min width}[, int{min height} 
                [,string{x name in ini}[, string{y name in ini}[, string{width name in ini}[, string{height name in ini}]]]]]])

        RememberComboSelection( array{this combo box's special selection array}, string{value to store})
        GetLastComboSelection( array{this combo box's special selection array}, array{list of current valid names in this combo})

        VisitURL( string {valid URI} )
        UrlToText( string{Valid URI or html file path)[, bool{local file = false} [, string{begin output from this string}]])
        ReplaceHTMLEntities( string{text to translate entities in;   (numneric) ö regular ("ö")})

        LogError( string )
        DoLog( string {log file full path}, string {a value to write*} [, string final output}])

        PrintArray ( array [, string {title}, bool {true if 2D array}] )    
        DumpArray ( array )    

        debug( string )
                                            
        ExitReport ( string )


        --
        From UDF's..
    
        ArrayBox(ByRef $Array$ArrayBase = 1, $sTitle = 'Array Box', $Width = 350, $Height = 350, $Left = -1, $Top = -1)
        ce_Singleton($occurenceName$flag = 0)
        ce_IsPressed($Key)
        QuitBox()

#ce


;
;
; BubbleSort()
;
; A very basic, but very handy array sort.
; Designed for small lists; menus and such-like, where it excels.
; Purist can kiss my butt, this is simple, and elegant.
;
; NOTE: this is for "AutoIt Arrays", where the first value is
; the total number of elements. Basically, it will be left as-is.
; Also note, this is a case-insensitive search.

; to use..        BubbleSort($my_array)
;
func BubbleSort(ByRef $bs_array)
    for $i = uBound($bs_array)-1 to 1 step -1
        for $j = 2 to $i
            if $bs_array[$j-1] > $bs_array[$j] then
                $temp = $bs_array[$j-1]
                $bs_array[$j-1] = $bs_array[$j]
                $bs_array[$j] = $temp
            endif
        next
    next
    return $bs_array
endfunc
;
; By the way, it should be noted that I have no idea why this works.
; Technically, using strings as numbers in AutoIt should implicitly call
; Number() and all "words" would be 0. But it does work, and works great! 
; Hmmm.


;
; InsertionSort()
;
; slightly different results, here
; simple algo, good for lists of numbers, and pretty fast, too..
;
func InsertionSort(ByRef $is_array)
    for $i = 1 to uBound($is_array)-1
        $index = $is_array[$i]
        $j = $i
        while $j > 1 and $is_array[$j-1] > $index
            $is_array[$j] = $is_array[$j-1]
            $j -= 1
        wend
        $is_array[$j] = $index
    next
    return $is_array
endfunc
; mail me if you want an AutoIt version of the QuickSort algo


;
;
; ShellSort()
; Invented by Donald Shell, 1959.
;
; more efficient than a BubbleSort
; good for repetative sorting of smaller lists
; neck-and-neck with InsertionSort in most of my tests
;
; note: this is designed for "AutoIt Arrays" (first value it the total)

func ShellSort(ByRef $some_array)

    $increment = 1
    while $increment > 0

        for $i = 2 to uBound($some_array)-1
            $j = $i
            $temp = $some_array[$i]

            while $j >= $increment and $some_array[$j-$increment] > $temp
                $some_array[$j] = $some_array[$j-$increment]
                $j = $j - $increment
            wend
            $some_array[$j] = $temp
        next

        if $increment/2 <> 0 then ; ?
            $increment = int($increment/2)
        elseif $increment = 1 then
            $increment = 0
        else
            $increment = 1
        endif
    wend
    return $some_array
endfunc




; MaxMax()
;
; Evaluates two or three numbers and returns the highest
; Because _Max($a,(_Max($b,$c)) is just plain ugly.
;
func MaxMax($num1$num2$num3=1.7E-308)
    if not IsNumber($num1) or not IsNumber($num2) or not IsNumber($num3) then return
    if $num1 > $num2 then
        if $num3 > $num1 then return $num3
        return $num1
    else
        if $num3 > $num2 then return $num3
        return $num2
    endif
endfunc  

;
; MinMin()
;
; Evaluates two or three numbers and returns the smallest
;
func MinMin($num1$num2$num3=1.7E+308)
    if not IsNumber($num1) or not IsNumber($num2) or not IsNumber($num3) then return
    if $num1 > $num2 then
        if $num3 < $num2 then return $num3
        return $num2
    else
        if $num3 < $num1 then return $num3
        return $num1
    endif
endfunc  


;
; BaseName()
;
; get the base name of a file from a full path..
; in other words; returns the path name without the folders part (ie. file name only)
;
func BaseName($bn_path)
    if StringRight($bn_path, 1) = "\" then $bn_path = StringTrimRight($bn_path, 1)
    $bn_path_parts = StringSplit($bn_path"\")
    return $bn_path_parts[$bn_path_parts[0]]
endfunc

;
; GetExtension()
;
; returns the extension of a file name, e.g. "txt"
; if the file has no extension, returns a blank "" string
;
func GetExtension($some_name)
    $name_parts = StringSplit($some_name".")
    if $name_parts[$name_parts[0]] <> $some_name and _ "." was not found
        not StringInStr($name_parts[$name_parts[0]], "\") then ; extensionless file in a path with a dot
        return $name_parts[$name_parts[0]]
    else
        return ""
    endif
endfunc

;
; RemoveExtension()
;
; removes the extension of a file name (including the dot ".")
; requires the above functions
;
func RemoveExtension($some_name)
    $add = 0
    if StringInStr(BaseName($some_name), ".") then $add = 1
    return StringTrimRight($some_name, StringLen(GetExtension($some_name)) + $add)
endfunc

;
; CleanName()
;
; returns a file name minus the path AND the extension
; basically does two of the above functions, all-in-one..
;
func CleanName($some_name)
    return RemoveExtension(BaseName($some_name))
endfunc


;
; GetParent()
;
; returns the parent directory of a given file or directory path..
;
func GetParent($gp_dir
    local $gp_full_path = StringSplit($gp_dir"\"; array    
    return StringTrimRight($gp_dir, StringLen($gp_full_path[$gp_full_path[0]]) + 1) ; 1 = "\"
endfunc


;
; FolderIsEmpty()
;
; empty the folder is?
; returns 1 if the given folder path is an empty folder
;
func FolderIsEmpty($fie_folder)
    local $fie_search_files = FileFindFirstFile($fie_folder & "\*.*")  
    if $fie_search_files = -1 then
        if @error = 1 then    
            FileClose($fie_search_files)
            return 1
        else
            return 2
        endif
    endif
    FileClose($fie_search_files)
    return 0
endfunc


;
; IsDir()
;
; is the given path a directory?
;
func IsDir($some_path)

    ; simple but slow..    
    ; (although the fastest of all the methods I've tried - a lot)
    return StringInStr(FileGetAttrib($some_path), "D";, 2 = slower!
endfunc



;
; ReadDir()
;
; open a folder and return files with a particular $extension 
; as an array of file names. See RecurseDir() (below) for
; more functionality.
;
func ReadDir($folder$extension)

    ; AutoIt array handling is basic, to say the least!
    dim $files[1]
    dim $new_array[2]

    ; create a "search handle" of all the *.$extension files in the folder
    $search_files = FileFindFirstFile($folder & "\*." & $extension)  

    if $search_files = -1 then
        $search_files = FileFindFirstFile($folder & "\*." & $extension)
    endif

    $i = 1
    do
        $tmp = FileFindNextFile($search_files)
        $files[$i-1] = $tmp
        $i += 1 ; like php, same as $i = $i + 1
        redim $files[$i]
    until @error

    FileClose($search_files; close the search handle

    ; this removes the extraneous/empty elements from the array
    $i = 2
    for $this_file in $files
        if StringInStr($this_file$extension, 2) then
            redim $new_array[$i]
            $new_array[0] = $i-1
            $new_array[$i-1] = $this_file
            $i = $i + 1
        endif
    next

    ; wipe this array..
    $files = 0

    ;if $new_array[1] = "" then return 0

    ; return the array of filenames..
    return $new_array

endfunc


;
; RecurseDir()    v2.2
;
; Recursively search a directory structure for files matching a pattern
; and return its files as an array of file paths, the first value being the
; total number of file paths in the array (a-la "AutoIt Array").
;
; I spent some time testing many different routines. _GetFileList, by Jos van
; der Zande, always gave me the best results, and nicely coded, but around ten 
; times slower (52s) than Larry (and Beerman's) recursion routines (4.9s) when 
; recursing my home folder.**
;
; ** 1000 folders, 4773 files, 702MB. [cpu:1.3GHz, 640MB RAM] at time of writing
;
; This function is based on _GetFileList, but after a few hacks and tweaks is now
; more than fifteen times faster than the original.** The results are still as good, 
; but instead of 50+ seconds to recurse my home folder, it now takes 3.3 seconds, 
; making it fastest and bestest of all the AutoIt recursion routines! *tic*
;
; Note: you can now supply multiple file masks (needed for backup). It makes a lot 
; of sense to grab any other extensions while we are in a directory. 
; The delimiter is a comma..
;
;        RecurseDir("C:\Program Files""*.reg,*.ini,*.cfg")
;
; When searching for multiple masks the speed improvements are *staggering*, and 
; logarithmic; basically multiply the number of masks. For instance, a backup of
; all the pref files in my Program Files folder is scanned, copied, zipped and 
; completed in around a minute. pretty good, considering it's over 12GB; all
; tools, no big game installs, and ten file masks to search.
;
; The optional third parameter "$dont_recurse" tells RecurseDir() to only return
; matches for files in the top level directory, no deeper. (true/false)
; see also ReadDir() above.
;
; You can also supply an optional fourth parameter which is a string; the path to
; a "dump file" to dump (log) the paths of all matched files; for debugging only,
; because it will slow things down some.
;
; In v2.2 you can also supply an optional fifth parameter, "$return_dirs" which
; will do exactly that, returning an AutoIt array of all the directories in the
; path, and *only* the directories. (true/false) 
;
; This function gets used a lot in my apps.
;
;
; **    A lot to do with using the "&=" operator. Those wee differences mount up.
;        Probably that operator wasn't available when the code was first written.
;
func RecurseDir($dir$mask$dont_recurse=false, $dump=""$return_dirs=false)
;debug(@ScriptLineNumber & ": " & "func: RecurseDir " & $dir)

   dim $n_dirnames[333333]    ; maximum number of directories which can be scanned
   local $n_dircount = 0    ; ^ could be set much higher, if required
   local $n_file
   local $n_search
   local $n_tfile
   local $file_array
   local $filenames
   local $filecount
   local $dircount = 1
   local $msg = "error"

   ; if there was an "\" on the end of the given directory, remove that..
   if StringRight($dir, 1) = "\" then $dir = StringTrimRight($dir, 1)

   $n_dirnames[$dircount] = $dir

   if not FileExists($dir) then return 0

    while $dircount > $n_dircount ; keep on looping until all directories are scanned..

        $n_dircount += 1
        $n_search = FileFindFirstFile($n_dirnames[$n_dircount] & "\*.*")

        while 1  ; find all subdirs in this directory and store them in a array..
            $n_file = FileFindNextFile($n_search
            if @error then exitloop
            ; skip directory references..
            if $n_file = "." or $n_file = ".." then continueloop

            $n_tfile = $n_dirnames[$n_dircount] & "\" & $n_file

            ; if it's a directory, add it to the list of directories to be processed..
            if StringInStr(FileGetAttrib($n_tfile ), "D") and not $dont_recurse then                                
                $dircount += 1
                $n_dirnames[$dircount] = $n_tfile
            endif
        wend
        FileClose($n_search)

        ; multiple masks..
        if StringInStr($mask",", 2) then
            $mask_array = StringSplit($mask",")
        else ; or else create a dummy array..
            dim $mask_array[2] = [1, $mask]
        endif

        ; loop through the array of masks..
        for $mask_c = 1 to $mask_array[0]
            ; find all files that match this mask..
            $n_search = FileFindFirstFile($n_dirnames[$n_dircount] & "\" & $mask_array[$mask_c] )  
            if $n_search = -1 then continueloop

            while 1
                $n_file = FileFindNextFile($n_search
                if @error then exitloop ; end of dir
                if $n_file = "." or $n_file = ".." then continueloop

                $n_tfile = $n_dirnames[$n_dircount] & "\" & $n_file
                if not StringInStr(FileGetAttrib( $n_tfile ), "D") then
                    $filecount += 1
                    $filenames &= $n_tfile & @LF
                endif
            wend
            FileClose($n_search)
        next
    wend

    ; flip to a string and back to remove extraneous entries
    ; this is quicker than redimming on every loop
    if $return_dirs then 
        $tmp_str = ""
        $i = 1
        while $n_dirnames[$i] <> ""
            $tmp_str &= $n_dirnames[$i] & "|"
            $i += 1
        wend
        $tmp_str = StringTrimRight($tmp_str, 1)
        $n_dirnames = StringSplit($tmp_str"|")
        return $n_dirnames
    endif

    $filenames = StringTrimRight($filenames, 1)
    if $filenames = "" then return 0
    $file_array = StringSplit($filenames, @LF)

    ; dump results to a file..
    if $dump then 
        $dump_file = FileOpen($dump, 2)
        FileWrite($dump_file$filenames)
        FileClose($dump_file)
    endif
    return($file_array)
endfunc



;
; GrabCommentsFromIniSection()
;
; AutoIt doesn't support ini comments (for some reason that I can't see -
; I would have them in an @extended variable in IniReadSection, or something)
; It's a shame, because otherwise AutoIt is very strong in the ini department.
; Anyway, I feel that ini file comments are very important, so I'll have to 
; write some code to deal with this..

;    GrabCommentsFromIniSection("test.ini""foo")
;
; ..returns all comments from the section "foo", in the file; "test.ini"
; The path must point to a real ini file with standard ini sections.
;
; Set the optional third parameter to TRUE to get back an AutoIt array of
; the comments, one line per element.
;
; Send a string of text for the [optional] fourth parameter ($ignore),
; and any comment lines containing that word/phrase will be ignored.
;
; NOTE: GrabCommentsFromIniSection() returns lines of comments with a CRLF
; ("\r\n"; Windows line-break) between each line, but none before or after..
;
; ALSO NOTE: Lines of comments beginning with a semi-colon ";" will be 
; returned beginning with a hash "#", instead. This improves portability.
;
func GrabCommentsFromIniSection($ini_file$ini_section$make_array=false, $ignore="(*&^(*&%*&^$&^£$^$%*&^%(*&%(")

    $whole_file = FileOpen($ini_file, 0)
    $file_lines = StringSplit(StringStripCR(FileRead($whole_file, FileGetSize($ini_file))), @LF)
    FileClose($whole_file)

    $comment_string = ""
    $found_my_section = false

    for $a = 1 to $file_lines[0]
        $file_lines[$a] = StringStripWS($file_lines[$a], 3)

        if $found_my_section and StringLeft($file_lines[$a], 1) = "[" then exitloop
        if $file_lines[$a] = "[" & $ini_section & "]" then $found_my_section = true

        if $found_my_section then
            if StringLeft($file_lines[$a], 1) = ";" then
                $file_lines[$a] = StringReplace($file_lines[$a], ";""#", 1)
            endif
            if StringLeft($file_lines[$a], 1) = "#" then
                if not StringInStr($file_lines[$a], $ignore) then
                    $comment_string &= @CRLF & $file_lines[$a]
                endif
            endif
        endif

    next

    $comment_string = StringStripWS($comment_string, 1)
    if $make_array then return StringSplit($comment_string, @CRLF, 1)
    return $comment_string
endfunc


;
; WriteCommentsToIniSection()    [counterpart of the above.function]
; (there's no theoretical limit for the number of comment lines)
;
; Supply the full path to the ini file, the name of the ini section, 
; and the string of comments to write.
;
; A CRLF (Windows Line-break character, "\r\n") is added before the comments.
; If you want line breaks after, you will need to add them yourself.e.g..
;
;    WriteCommentsToIniSection($ini_file$my_group$comment_string & @CRLF)
;
; Nothing else is added. Don't forget to put a "#" at the start of each line.
;
; WriteCommentsToIniSection() will backup the current ini file before proceeding. 
; When complete, it will compare the size of the files. If the new ini isn't 
; bigger than the old one, the backup is swapped back into place, no harm done.
; In this case, WriteCommentsToIniSection() will return False. Normally it
; returns True, meaning the operation was successful.
;
; NOTE: if you are writing to a new ini section, it's best to write the comments
; after this, which will ensure they are placed directly under the [section name]
;
func WriteCommentsToIniSection($ini_file$ini_section$comment_string)
    FileCopy($ini_file, @TempDir & "\" & Basename($ini_file) & ".bax.ini", 1)
    IniWrite($ini_file$ini_section"wctis_foo""bar"; create the section if it doesn't exist
    $whole_file = FileRead($ini_file)
    $whole_file = StringReplace($whole_file"[" & $ini_section & "]""[" & $ini_section & "]" & @CRLF & $comment_string)
    $tmp_file = FileOpen($ini_file, 2)
    FileWrite($tmp_file$whole_file)
    FileClose($tmp_file)
    if FileGetSize($ini_file) < FileGetSize(@TempDir & "\" & Basename($ini_file) & ".bax.ini") then
        FileDelete($ini_file)
        FileCopy(@TempDir & "\" & Basename($ini_file) & ".bax.ini"$ini_file; leave backup in-place
        return 0
    endif
    IniDelete($ini_file$ini_section"wctis_foo")
    return 1
endfunc


;
; IniReadCheckBoxValue()
;
; This function "transforms" an AutoIt or human unchecked value (4 or 0, respectively), 
; into plain old 4, which AutoIt can understand. this function is intended as a drop-in 
; replacement for the IniRead command, simply replace the function name.
; Of course, it's only useful when reading checkbox values, e.g..
;
;    $big_switch = IniReadCheckBoxValue($ini_path$my_name"big_switch"$GUI_UNCHECKED)
;
; AutoIt, annoyingly, uses 1 as the value for checked checkboxes, and 4 as the value 
; for unchecked checkboxes. this makes passing the values directly in and out of ini
; files undesirable, because "4" is not a logical value, and most humans would expect
; it to be 0 (zero). The following two functions act as interface between the program
; and the ini file, making sense of the "human" equivalents. Other "human" values are
; also understood, just in case..
;
func IniReadCheckBoxValue($rcbv_inifile$rcbv_section$rcbv_key$rcbv_default)
    $ircbv_val = IniRead($rcbv_inifile$rcbv_section$rcbv_key$rcbv_default)
    switch $ircbv_val
        case $GUI_UNCHECKED    ; 4
            return $GUI_UNCHECKED
        case "false""off""no""not""nope""nay""nay!""nah""nah!""no way!""no sir!""negative"
            return $GUI_UNCHECKED
        case "true""on""yes""yay""yay!""yup""hell yes!""indeed""yes sir!""yessir!""affirmative""cool"
            return $GUI_CHECKED
        case "0"
            return $GUI_UNCHECKED
        case $GUI_CHECKED ; 1
            return $GUI_CHECKED
        case else ; some special value, probably "-" (I sometimes employ, to enable user to disable something)
            return $ircbv_val
    endswitch
endfunc


;
; IniWriteCheckBoxValue()
;
; This function transforms an AutoIt checkbox value into a 'human' unchecked value (4 into 0, basically)
; this is intended as a drop-in replacement for the IniWrite command, simply replace the function name.
; Of course, it's only useful when writing checkbox values that will be read by 'IniReadCheckBoxValue'
; above. Instead of 0, you can also write "no""off", or whatever, by passing the optional 5th parameter..
;
func IniWriteCheckBoxValue($wcbv_inifile$wcbv_section$wcbv_key$wcbv_val$tring=0)
    if $wcbv_val = $GUI_UNCHECKED then $wcbv_val = $tring
    IniWrite($wcbv_inifile$wcbv_section$wcbv_key$wcbv_val)
endfunc

; the above functions are useful until you create a proper preferences interface for your application!
; actually, I tend to use $GUI_CHECKED and $GUI_UNCHECKED as general-purpose booleans these days.


;
; IniKeyExists()
;
; feed it a 2-dimensional array (as supplied by IniReadSeaction)
; if the key exists, IniKeyExists() returns its value; if not, it returns false.
; the search is case-insensitive, but otherwise must be an exact (not partial) match.
; sometimes handy.
;
func IniKeyExists(ByRef $search_array$search_string)
    if not IsArray($search_array) then
        return false
    endif
    for $i = 1 to $search_array[0][0]
        if $search_string = $search_array[$i][0] then
            return $search_array[$i][1]
        endif
    next
    return false
endfunc


;
;
; InArray()
;
; feed it an array and a string, returns true if $ia_search_string
; is one of the $ia_search_array's *values*. 
; the search is case-insensitive, but must be an exact (not partial) match.
; there's probably a real function for this these days.
;
func InArray(ByRef $ia_search_array$ia_search_string)
    if not IsArray($ia_search_array) then return false
    $ia_limit = UBound($ia_search_array) - 1
    for $i = 0 to $ia_limit 
        if $ia_search_string = $ia_search_array[$i] then
            return true
        endif
    next
    return false
endfunc



; MakeDummyArray()
;
; we need an array, but only have a string, what to do? this function returns an 
"AutoIt array" with a single data element, that is, two elements; $dummy_array[1]
; containing your string, and $dummy_array[0] being the total number of data elements, 
; AutoIt-style, which will always be 1, of course.
;
; Although this is simple enough to do in place, it's more readable to do use a function.
;
func MakeDummyArray($regular_string)
    local $dummy_array[2] = [1, $regular_string]
    return $dummy_array
endfunc




#cs

  SaveSizePos()

  save a window's size and position preferences..
  [mainly for windows that can be re-sized, but fine for fixed-size windows, too]

  note: at the time of writing, this needs debugging.


    SaveSizePos Parameters..

        window handle                            =        Control ID of the gui you want to save prefs for
        string    {ini path}                        =        Full path to ini file to save settings to.
        string {ini section}                    =        Name of [section] to use in the specified ini file.
        int {min width}                [optional]    =        Minimum width gui is allowed to shrink to, defaults to 100.
        int {min height}            [optional]    =        Minimum height gui is allowed to shrink to, defaults to 50.
        string {x name in ini}        [optional]    =        The name of the "x" key inside the ini, defaults to "x".
        string {y name in ini}        [optional]    =        The name of the "y" key inside the ini, defaults to "y".
        string {width name in ini}    [optional]    =        The name of the "width" key inside the ini, defaults to "width".
        string {height name in ini}    [optional]    =        The name of the "height" key inside the ini, defaults to "height".


    If don't want to write a value, set its name parameter to "-".

    If you need to set any of the later optional paramters, but not earlier ones, 
    set the earlier parameters to an empty string "" to get their default values.

    Simple usage..

        SaveSizePos($my_gui"my.ini""prefs")

        SaveSizePos($my_gui"my.ini""prefs", 380, 156)    ; this app uses the tips system!


    Saving prefs for a second gui within the app..

        SaveSizePos($my_other_gui"my.ini""prefs", 100, 20, "tool_x""tool_y""tool_width""tool_height")


    Save only width and height (but not x and y), and set minimum limits for those, too..

        SaveSizePos($some_gui"my.ini""main prefs", 380, 80, "-""-")


    And so on.

#ce

func SaveSizePos($ssp_gui$ssp_path$ssp_section$min_width=""$min_height=""$ssp_x=""$ssp_y=""$ssp_w=""$ssp_h="")

    $wsize_array = WinGetPos($ssp_gui)
    if not IsArray($wsize_array) then return

    $x = $wsize_array[0]
    $y = $wsize_array[1]
    $width = $wsize_array[2]
    $height = $wsize_array[3] 

    ; this is a better way to set the defaults in this case.
    if not $ssp_x then $ssp_x = "x"
    if not $ssp_y then $ssp_y = "y"
    if not $ssp_w then $ssp_w = "width"
    if not $ssp_h then $ssp_h = "height"

    if $x < 0 then $x = 0
    if $y > @DesktopWidth - $width then $y = @DesktopWidth - $width

    if $ssp_x <> "-" then IniWrite($ssp_path$ssp_section$ssp_x$x)
    if $ssp_y <> "-" then IniWrite($ssp_path$ssp_section$ssp_y$y)

    $width = $wsize_array[2]
    $height = $wsize_array[3] 

    if $min_width = "" then $min_width = 100    ; might be set to zero
    if $min_height = "" then $min_height = 50    ; ditto

    if $width < $min_width then $width = $min_width
    if $height < $min_height then $height = $min_height

    $size_array = WinGetClientSize($ssp_gui)
    if IsArray($size_array) then
        if $ssp_w <> "-" then IniWrite($ssp_path$ssp_section$ssp_w$size_array[0])
        if $ssp_h <> "-" then IniWrite($ssp_path$ssp_section$ssp_h$size_array[1])
    endif
endfunc



; RememberComboSelection()
; does what it says on the tin
;
; If the user deletes an item, the previous item will be selected
; This makes multiple deltions easier, and more. This code is also 
; more compact than checking for even a single "previous" entry on
; each combo box individually. It's neater, too. 
;
; To use, simply create a global "AutoIt" array for the values, 
; with the number of values you would like to remember (remember 
; to set element 0 to the total)..
;
;    global $previous_combo_selections[501] = [500] ; plenty!
;
; Rather than set a limit, we could use redim, but it's  slow. 
; Anyway, when the user selects something, store that..
;
;    RememberComboSelection($previous_combo_selections$current_preset)
;
; And when they delete an item, recall the previous item with..
;
;    $previous_selection = GetLastComboSelection($previous_combo_selections$preset_names)
;
"$previous_selection" will now contain the string, which you can 
; use to set the selection on your combo box, though you can, of 
; course, use it directly.
;
func RememberComboSelection(ByRef $combo_array$value)
    for $i = 1 to $combo_array[0]
        if $combo_array[$i] = "" then
            if $combo_array[$i-1] <> $value then 
                $combo_array[$i] = $value
            endif
            exitloop ; store or not, we're outta here
        endif
    next
endfunc

func GetLastComboSelection(ByRef $combo_array, ByRef $names_list)
    $new_val = ""
    $i = $combo_array[0]
    while $i > 0
        if $combo_array[$i] <> "" then
            if not InArray($names_list$combo_array[$i]) then
                $combo_array[$i] = ""
                $i -= 1
                continueloop
            endif
            $new_val = $combo_array[$i
            $combo_array[$i] = "" 
            exitloop
        endif
        $i -= 1
    wend
    ; in the absence of a stored value, load the "last" value.
    ; if deleting newly imported/created presets, this will get you the
    ; most recent additions, even when haven't been selected this session.
    if $new_val = "" then $new_val = $names_list[$names_list[0]]
    return $new_val
endfunc

; Although I don't, it would be trivial to store this array in an
; ini file between launches, and keep a selection "history".



;
; VisitURL()
;
; send the "default browser" to our URL..
; or...        ; Run(@ComSpec & " /c " & "start http://www.google.com""", @SW_HIDE)
;
; This uses the USER'S SYSTEM BROWSER! (eg. Firefox)
;
func VisitURL($vu_url="http://corz.org/")
    $vu_browser_str = RegRead("HKEY_CLASSES_ROOT\HTTP\shell\open\command""")
    $vu_browser_str = StringReplace($vu_browser_str, '"%1"', $vu_url)
    run($vu_browser_str"", @SW_SHOW)
endfunc



;
; UrlToText()
;
; basic HTML > text translation, for spoken web pages
; slow, and not terribly clever..
;
; feed it a URL or path to a local html file, returns the plain text, for speaking
; all formatting is removed, and "." dots are also added to break up big sections.
;
; you can send start and end points for the text stream; simply tag the words/phrases
; onto the end of the URL (or local file location) using an asterisk, e.g..
;
$myText = UrlToText('http://news.bbc.co.uk/**/st Updated*CONTACT US')
;
; which would get you the latest headlines from the BBC, ready for feeding to Sam, or Mike
; or Mary or whoever. If you omit the end point, e.g..
;
$myText = UrlToText('http://www.answers.com/topic/gal-pagos-tortoise-2*Synonyms')
;
; all the text from the start point to the end of the page will be returned. If you provide
; no start and end points, the text of the whole page is returned. Something to play with.
;
func UrlToText($url)

    $start = ""
    $end = ""
    if StringInStr($url"*", 0, -1) then
        $url_parts = StringSplit($url"*")
        $url = $url_parts[1]
        if uBound($url_parts) > 2 then $start = $url_parts[2]
        if uBound($url_parts) > 3 then $end = $url_parts[3]
    endif

    if StringLeft($url, 4) = "http" then 
        InetGet($url, @tempdir & "\UrlToText.tmp", 1)
        ; if no file or emp
        local $handle = FileOpen(@tempdir & "\UrlToText.tmp", 0)
    else
        local $handle = FileOpen($url, 0)
    endif
    $web_text = FileRead($handle)

    ; we'll break shit up for speaking..
    $web_text = StringRegExpReplace($web_text, '</(div|p|tr|table)>', '. ') 
    ; strip out the HTML..
    $web_text = StringRegExpReplace($web_text, '\s', ' ')
    $web_text = StringRegExpReplace($web_text, '<(?i)head(.*?)</(?i)head>', '') ; best done individually..
    $web_text = StringRegExpReplace($web_text, '<(?i)script(.*?)</(?i)script>', '')
    $web_text = StringRegExpReplace($web_text, '<(?i)style(.*?)</(?i)style>', '')
    $web_text = StringRegExpReplace($web_text, '</?[^>]*?>', '')
    $web_text = ReplaceHTMLEntities($web_text

    ; speak from..
    if $start then 
        $web_text = StringTrimLeft($web_text, StringInStr($web_text$start)-1)
    endif

    ; speak to..
    $strlen = StringLen($web_text)
    $end_pos = StringInStr($web_text$end)
    if $end_pos = 0 then $end_pos = $strlen
    if $end then 
        $web_text = StringTrimRight($web_text$strlen-$end_pos+1)
    endif
    FileClose($handle)
    FileDelete(@tempdir & "\UrlToText.tmp")
    return StringStripWS($web_text, 4)
endfunc


;
; ReplaceHTMLEntities()
;
; probably rather slow, but, erm, fairly thorough..

; note: unless you are using a proper international font, many of the entities
; below will appear as boxes, or empty. Worry not, everything is working fine.
;
func ReplaceHTMLEntities($text)
    for $i = 32 to 255
        $text = StringReplace($text, String('&#' & $i & ';'), chr($i))
    next
    $text = StringReplace($text"&Aacute;""Á")
    $text = StringReplace($text"&aacute;""á")
    $text = StringReplace($text"&Acirc;""Â")
    $text = StringReplace($text"&acirc;""â")
    $text = StringReplace($text"&acute;""´")
    $text = StringReplace($text"&AElig;""Æ")
    $text = StringReplace($text"&aelig;""æ")
    $text = StringReplace($text"&Agrave;""À")
    $text = StringReplace($text"&agrave;""à")
    $text = StringReplace($text"&alefsym;""?")
    $text = StringReplace($text"&Alpha;""?")
    $text = StringReplace($text"&alpha;""?")
    $text = StringReplace($text"&amp;""&")
    $text = StringReplace($text"&and;""?")
    $text = StringReplace($text"&ang;""?")
    $text = StringReplace($text"&Aring;""Å")
    $text = StringReplace($text"&aring;""å")
    $text = StringReplace($text"&asymp;""?")
    $text = StringReplace($text"&Atilde;""Ã")
    $text = StringReplace($text"&atilde;""ã")
    $text = StringReplace($text"&Auml;""Ä")
    $text = StringReplace($text"&auml;""ä")
    $text = StringReplace($text"&bdquo;""?")
    $text = StringReplace($text"&Beta;""?")
    $text = StringReplace($text"&beta;""?")
    $text = StringReplace($text"&brvbar;""¦")
    $text = StringReplace($text"&bull;""?")
    $text = StringReplace($text"&cap;""?")
    $text = StringReplace($text"&Ccedil;""Ç")
    $text = StringReplace($text"&ccedil;""ç")
    $text = StringReplace($text"&cedil;""¸")
    $text = StringReplace($text"&cent;""¢")
    $text = StringReplace($text"&Chi;""?")
    $text = StringReplace($text"&chi;""?")
    $text = StringReplace($text"&circ;""?")
    $text = StringReplace($text"&clubs;""?")
    $text = StringReplace($text"&cong;""?")
    $text = StringReplace($text"&copy;""©")
    $text = StringReplace($text"&crarr;""?")
    $text = StringReplace($text"&cup;""?")
    $text = StringReplace($text"&curren;""¤")
    $text = StringReplace($text"&dagger;""?")
    $text = StringReplace($text"&Dagger;""?")
    $text = StringReplace($text"&darr;""?")
    $text = StringReplace($text"&dArr;""?")
    $text = StringReplace($text"&deg;""°")
    $text = StringReplace($text"&Delta;""?")
    $text = StringReplace($text"&delta;""?")
    $text = StringReplace($text"&diams;""?")
    $text = StringReplace($text"&divide;""÷")
    $text = StringReplace($text"&Eacute;""É")
    $text = StringReplace($text"&eacute;""é")
    $text = StringReplace($text"&Ecirc;""Ê")
    $text = StringReplace($text"&ecirc;""ê")
    $text = StringReplace($text"&Egrave;""È")
    $text = StringReplace($text"&egrave;""è")
    $text = StringReplace($text"&empty;""?")
    $text = StringReplace($text"&emsp;""?")
    $text = StringReplace($text"&ensp;""?")
    $text = StringReplace($text"&Epsilon;""?")
    $text = StringReplace($text"&epsilon;""?")
    $text = StringReplace($text"&equiv;""?")
    $text = StringReplace($text"&Eta;""?")
    $text = StringReplace($text"&eta;""?")
    $text = StringReplace($text"&ETH;""Ð")
    $text = StringReplace($text"&eth;""ð")
    $text = StringReplace($text"&Euml;""Ë")
    $text = StringReplace($text"&euml;""ë")
    $text = StringReplace($text"&euro;""?")
    $text = StringReplace($text"&exist;""?")
    $text = StringReplace($text"&fnof;""?")
    $text = StringReplace($text"&forall;""?")
    $text = StringReplace($text"&frac12;""½")
    $text = StringReplace($text"&frac14;""¼")
    $text = StringReplace($text"&frac34;""¾")
    $text = StringReplace($text"&frasl;""?")
    $text = StringReplace($text"&Gamma;""?")
    $text = StringReplace($text"&gamma;""?")
    $text = StringReplace($text"&ge;""?")
    $text = StringReplace($text"&gt;"">")
    $text = StringReplace($text"&harr;""?")
    $text = StringReplace($text"&hArr;""?")
    $text = StringReplace($text"&hearts;""?")
    $text = StringReplace($text"&hellip;""?")
    $text = StringReplace($text"&Iacute;""Í")
    $text = StringReplace($text"&iacute;""í")
    $text = StringReplace($text"&Icirc;""Î")
    $text = StringReplace($text"&icirc;""î")
    $text = StringReplace($text"&iexcl;""¡")
    $text = StringReplace($text"&Igrave;""Ì")
    $text = StringReplace($text"&igrave;""ì")
    $text = StringReplace($text"&image;""?")
    $text = StringReplace($text"&infin;""?")
    $text = StringReplace($text"&int;""?")
    $text = StringReplace($text"&Iota;""?")
    $text = StringReplace($text"&iota;""?")
    $text = StringReplace($text"&iquest;""¿")
    $text = StringReplace($text"&isin;""?")
    $text = StringReplace($text"&Iuml;""Ï")
    $text = StringReplace($text"&iuml;""ï")
    $text = StringReplace($text"&Kappa;""?")
    $text = StringReplace($text"&kappa;""?")
    $text = StringReplace($text"&Lambda;""?")
    $text = StringReplace($text"&lambda;""?")
    $text = StringReplace($text"&lang;""?")
    $text = StringReplace($text"&laquo;""«")
    $text = StringReplace($text"&larr;""?")
    $text = StringReplace($text"&lArr;""?")
    $text = StringReplace($text"&lceil;""?")
    $text = StringReplace($text"&ldquo;""?")
    $text = StringReplace($text"&le;""?")
    $text = StringReplace($text"&lfloor;""?")
    $text = StringReplace($text"&lowast;""?")
    $text = StringReplace($text"&loz;""?")
    $text = StringReplace($text"&lrm;""?")
    $text = StringReplace($text"&lsaquo;""?")
    $text = StringReplace($text"&lsquo;""?")
    $text = StringReplace($text"&lt;""<")
    $text = StringReplace($text"&macr;""¯")
    $text = StringReplace($text"&mdash;""?")
    $text = StringReplace($text"&micro;""µ")
    $text = StringReplace($text"&middot;""·")
    $text = StringReplace($text"&minus;""?")
    $text = StringReplace($text"&Mu;""?")
    $text = StringReplace($text"&mu;""?")
    $text = StringReplace($text"&nabla;""?")
    $text = StringReplace($text"&nbsp;"" ")
    $text = StringReplace($text"&ndash;""?")
    $text = StringReplace($text"&ne;""?")
    $text = StringReplace($text"&ni;""?")
    $text = StringReplace($text"&not;""¬")
    $text = StringReplace($text"&notin;""?")
    $text = StringReplace($text"&nsub;""?")
    $text = StringReplace($text"&Ntilde;""Ñ")
    $text = StringReplace($text"&ntilde;""ñ")
    $text = StringReplace($text"&Nu;""?")
    $text = StringReplace($text"&nu;""?")
    $text = StringReplace($text"&Oacute;""Ó")
    $text = StringReplace($text"&oacute;""ó")
    $text = StringReplace($text"&Ocirc;""Ô")
    $text = StringReplace($text"&ocirc;""ô")
    $text = StringReplace($text"&OElig;""?")
    $text = StringReplace($text"&oelig;""?")
    $text = StringReplace($text"&Ograve;""Ò")
    $text = StringReplace($text"&ograve;""ò")
    $text = StringReplace($text"&oline;""?")
    $text = StringReplace($text"&Omega;""?")
    $text = StringReplace($text"&omega;""?")
    $text = StringReplace($text"&Omicron;""?")
    $text = StringReplace($text"&omicron;""?")
    $text = StringReplace($text"&oplus;""?")
    $text = StringReplace($text"&or;""?")
    $text = StringReplace($text"&ordf;""ª")
    $text = StringReplace($text"&ordm;""º")
    $text = StringReplace($text"&Oslash;""Ø")
    $text = StringReplace($text"&oslash;""ø")
    $text = StringReplace($text"&Otilde;""Õ")
    $text = StringReplace($text"&otilde;""õ")
    $text = StringReplace($text"&otimes;""?")
    $text = StringReplace($text"&Ouml;""Ö")
    $text = StringReplace($text"&ouml;""ö")
    $text = StringReplace($text"&para;""¶")
    $text = StringReplace($text"&part;""?")
    $text = StringReplace($text"&permil;""?")
    $text = StringReplace($text"&perp;""?")
    $text = StringReplace($text"&Phi;""?")
    $text = StringReplace($text"&phi;""?")
    $text = StringReplace($text"&Pi;""?")
    $text = StringReplace($text"&pi;""?")
    $text = StringReplace($text"&piv;""?")
    $text = StringReplace($text"&plusmn;""±")
    $text = StringReplace($text"&pound;""£")
    $text = StringReplace($text"&prime;""?")
    $text = StringReplace($text"&Prime;""?")
    $text = StringReplace($text"&prod;""?")
    $text = StringReplace($text"&prop;""?")
    $text = StringReplace($text"&Psi;""?")
    $text = StringReplace($text"&psi;""?")
    $text = StringReplace($text"&quot;", '"')
    $text = StringReplace($text, "
&radic;", "?")
    $text = StringReplace($text, "
&rang;", "?")
    $text = StringReplace($text, "
&raquo;", "»")
    $text = StringReplace($text, "
&rarr;", "?")
    $text = StringReplace($text, "
&rArr;", "?")
    $text = StringReplace($text, "
&rceil;", "?")
    $text = StringReplace($text, "
&rdquo;", "?")
    $text = StringReplace($text, "
&real;", "?")
    $text = StringReplace($text, "
&reg;", "®")
    $text = StringReplace($text, "
&rfloor;", "?")
    $text = StringReplace($text, "
&Rho;", "?")
    $text = StringReplace($text, "
&rho;", "?")
    $text = StringReplace($text, "
&rlm;", "?")
    $text = StringReplace($text, "
&rsaquo;", "?")
    $text = StringReplace($text, "
&rsquo;", "?")
    $text = StringReplace($text, "
&sbquo;", "?")
    $text = StringReplace($text, "
&Scaron;", "?")
    $text = StringReplace($text, "
&scaron;", "?")
    $text = StringReplace($text, "
&sdot;", "?")
    $text = StringReplace($text, "
&sect;", "§")
    $text = StringReplace($text, "
&shy;", "­")
    $text = StringReplace($text, "
&Sigma;", "?")
    $text = StringReplace($text, "
&sigma;", "?")
    $text = StringReplace($text, "
&sigmaf;", "?")
    $text = StringReplace($text, "
&sim;", "?")
    $text = StringReplace($text, "
&spades;", "?")
    $text = StringReplace($text, "
&sub;", "?")
    $text = StringReplace($text, "
&sube;", "?")
    $text = StringReplace($text, "
&sum;", "?")
    $text = StringReplace($text, "
&sup1;", "¹")
    $text = StringReplace($text, "
&sup2;", "²")
    $text = StringReplace($text, "
&sup3;", "³")
    $text = StringReplace($text, "
&sup;", "?")
    $text = StringReplace($text, "
&supe;", "?")
    $text = StringReplace($text, "
&szlig;", "ß")
    $text = StringReplace($text, "
&Tau;", "?")
    $text = StringReplace($text, "
&tau;", "?")
    $text = StringReplace($text, "
&there4;", "?")
    $text = StringReplace($text, "
&Theta;", "?")
    $text = StringReplace($text, "
&theta;", "?")
    $text = StringReplace($text, "
&thetasym;", "?")
    $text = StringReplace($text, "
&thinsp;", "?")
    $text = StringReplace($text, "
&THORN;", "Þ")
    $text = StringReplace($text, "
&thorn;", "þ")
    $text = StringReplace($text, "
&tilde;", "?")
    $text = StringReplace($text, "
&times;", "×")
    $text = StringReplace($text, "
&trade;", "?")
    $text = StringReplace($text, "
&Uacute;", "Ú")
    $text = StringReplace($text, "
&uacute;", "ú")
    $text = StringReplace($text, "
&uarr;", "?")
    $text = StringReplace($text, "
&uArr;", "?")
    $text = StringReplace($text, "
&Ucirc;", "Û")
    $text = StringReplace($text, "
&ucirc;", "û")
    $text = StringReplace($text, "
&Ugrave;", "Ù")
    $text = StringReplace($text, "
&ugrave;", "ù")
    $text = StringReplace($text, "
&uml;", "¨")
    $text = StringReplace($text, "
&upsih;", "?")
    $text = StringReplace($text, "
&Upsilon;", "?")
    $text = StringReplace($text, "
&upsilon;", "?")
    $text = StringReplace($text, "
&Uuml;", "Ü")
    $text = StringReplace($text, "
&uuml;", "ü")
    $text = StringReplace($text, "
&weierp;", "?")
    $text = StringReplace($text, "
&Xi;", "?")
    $text = StringReplace($text, "
&xi;", "?")
    $text = StringReplace($text, "
&Yacute;", "Ý")
    $text = StringReplace($text, "
&yacute;", "ý")
    $text = StringReplace($text, "
&yen;", "¥")
    $text = StringReplace($text, "
&yuml;", "ÿ")
    $text = StringReplace($text, "
&Yuml;", "?")
    $text = StringReplace($text, "
&Zeta;", "?")
    $text = StringReplace($text, "
&zeta;", "?")
    $text = StringReplace($text, "
&zwj;", "?")
    $text = StringReplace($text, "
&zwnj;", "?")
return $text
endfunc



;
; LogError()
;
; it should be "errer", really.
; log an (usually, exit) error to a file
;
func LogError($error_string)
    FileWriteLine(@ScriptDir & "
\error.log", "")
    FileWriteLine(@ScriptDir & "
\error.log", _
    "
--------------------------------------------------------------------------------")
    FileWriteLine(@ScriptDir & "
\error.log",  @Year & "/" & @Mon & "/" & @MDay _
                                            & "
  " & @Hour & ":" & @Min & ":" & @Sec )
    FileWriteLine(@ScriptDir & "
\error.log", "")
    FileWriteLine(@ScriptDir & "
\error.log", "command-line: " & $CmdLineRaw)
    FileWriteLine(@ScriptDir & "
\error.log", "")
    FileWriteLine(@ScriptDir & "
\error.log", $error_string)
endfunc


;
; DoLog()
;
; logs stuff..
;
; these init variables will likely be changed by the program, shortly after we load.
; or perhaps not. just as well we cover that here, before the program starts..
;
global $log_string
global $my_shortname
if $my_shortname = "
" then $my_shortname = "application"
global $log_file
if $log_file = "
" then $log_file = @ScriptFullPath&".log"
;
; the optional second parameter tells DoLog to append, or not.
$dl_append will most likely receive the output from a checkbox..
; 1 (append) or 4 [or anything else] (create new log)
;
; to stop and close the log, send "out" as your log string
; the optional third parameter '$log_extra' goes at top of log,
; and, if required, you must send it along with your "out" command, eg..
;
; DoLog("out", 0, "command-line: " & $my_arguments & @CRLF & @CRLF)
;
;
; and now the function itself..
;
func DoLog($dl_string$dl_append=4, $log_extra="
")
    if $dl_string = "
out" then
        if $log_string <> "
" then
            if $dl_append = 1 then
                $dl_append = 9 
            else
                $dl_append = 10 
            endif

            $my_log_file = FileOpen($log_file$dl_append)
            FileWriteLine($my_log_file, "
corz " & $my_shortname & " log @ "&@YEAR&"-"&@MON&"-"&@MDAY&".. " & @CRLF & _
                "
--------------------------------------------------------------------------------" & @CRLF & @CRLF)
            if $log_extra = "
" then FileWriteLine($my_log_file, "command-line: " & $CmdLineRaw)
            FileWriteLine($my_log_file$log_extra)
            FileWriteLine($my_log_file$log_string & @CRLF & @CRLF)
            FileClose($my_log_file)
            $log_string = "
"
        endif
    else
        $log_string &= $dl_string & @CRLF
    endif
endfunc



;
;;    debugging functions..
;


;
; PrintArray()
;
; debug output of an array, in the console 
; (your text editor can probably display this for you, if you so desire)..
;
func PrintArray(ByRef $array$tring="
array", $limit=0)
    if not IsArray($array) then 
        ConsoleWrite($tring & "
: NOT an array!" & @LF)
        ConsoleWrite("
it's a string: " & "->" & $tring & "<-" & @LF & @LF) ; & @CRLF
        
        return 0
    endif
    local $pa_string = "
"
    local $count = 0
    for $element in $array
        $pa_string &= '[' & $count & '] : ' & $element & @LF
        $count += 1
        if $count = $limit then exitloop
    next
    SplashOff()
    ProgressOff()
    ConsoleWrite($tring & "
" & @LF & $pa_string & @LF & @LF)
endfunc


;
; DumpArray()
;
; debug output of an array, to a file..
;
func DumpArray(ByRef $array$dump_file)
    if not IsArray($array) then return 0
    local $da_string = "
"
    local $count = 0
    for $element in $array
        $da_string &= '[' & $count & '] : ' & $element & @CRLF
        $count += 1
    next
    FileWrite($dump_file$da_string)
endfunc


;
; debug()
;
; provides quick debug report in your console..
;
; if your text editor can do it (probably), this is a great
; way to get debug output without halting the script execution..
;
func debug($d_string)
    if @compiled then return
    ConsoleWrite($d_string & @LF)
endfunc


;
; ExitReport()
;
; oh oh!
; A MessgeBox on exit error report.
;
func ExitReport($er_string
    MsgBox(262160, "
Error: ", "An error occured!" & @CRLF & $er_string, 60)
    exit
endfunc


; ArrayBox()
;
; from the UDF's, but wouldn't work there.
; here so I can get it working, and along my own lines

Func ArrayBox(ByRef $Array$ArrayBase = 1, $sTitle = 'Array Box', $Width = 350, $Height = 350, $Left = -1, $Top = -1)
    Dim $AllDone = 0, $msg$i$j$ArrayDimensions = UBound($Array, 0)
    Dim $hndForm_Main$hndListView_Display

    If $ArrayDimensions = 0 Then
        SetError(1)
        Return -1
    EndIf

    ;Setup
    If $ArrayBase <> 0 Then $ArrayBase = 1
        If $ArrayBase Then
        Select
            Case $ArrayDimensions = 1
                $ArrayMax = $Array[0]
            Case $ArrayDimensions = 2
                $ArrayMax = $Array[0][0]
        EndSelect
    Else
        $ArrayMax = UBound($Array, 1) - 1
    EndIf

    ;Create GUI
    If $Height < 100 Then $Height = 100
    If $Width < 100 Then $Width = 100

    $last_event_mode = AutoItSetOption("
GUIOnEventMode", 1) 

    $hndForm_Main = GUICreate($sTitle$Width$Height$Left$Top, BitOR(0x80000000, 0x00C00000, 0x00040000))
    GUISetOnEvent(-3, "
QuitBox" , $hndForm_Main)
    ;Create List Box
    If $ArrayDimensions = 1 Then
        $sTemp = 'Index|Value'
    ElseIf $ArrayDimensions = 2 Then
        $sTemp = 'Index'
        For $i = 0 To UBound($Array, 2) - 1
        $sTemp = $sTemp & '|' & $i
        Next
    EndIf
    $hndListView_Display = GUICtrlCreateListView($sTemp, 0, 0, $Width$Height-32, BitOR(0x0008, 0x0004))
    GUICtrlSetResizing($hndListView_Display, BitOR(0x0002, 0x0020, 0x0004, 0x0040))

    ;Create Controls, Show GUI
    $hndButton_Close = GUICtrlCreateButton('&Close',$Width-83,$Height-30,80,24)
    GUICtrlSetOnEvent(-1, "
QuitBox")
    GUICtrlSetResizing(-1, BitOR(0x0004, 0x0040, 0x0300))
    GUICtrlSetState($hndButton_Close, 512)
    GUISetState (@SW_SHOW, $hndForm_Main)


    ;Display Array
    Select
        Case $ArrayDimensions = 1 ;1-Dimensional Array
            For $i = $ArrayBase To $ArrayMax
                GUICtrlCreateListViewItem($i & '|' & $Array[$i], $hndListView_Display)
            Next ;$i
        Case $ArrayDimensions = 2 ;2-Dimensional Array
            For $i = $ArrayBase To $ArrayMax
                $sTemp=$Array[$i][0]
                for $j = 1 To UBound($Array, 2) - 1
                    $sTemp = $sTemp & '|' & $Array[$i][$j]
                Next ;$j
                GUICtrlCreateListViewItem('[' & $i & ']|' & $sTemp$hndListView_Display)
            Next ;$i
        Case Else ;Unhandled Type
    EndSelect

    global $QuitBox = 0
    do
        Sleep(100)
    until $QuitBox = 1

    AutoItSetOption("
GUIOnEventMode", $last_event_mode)
    GUIDelete($hndForm_Main)
    Return 0
EndFunc



; from the UDF's..
; here to save including the whole files.

; Description:    _Singleton
; Author(s):      Valik
Func ce_Singleton($occurenceName$flag = 0)
    Local $ERROR_ALREADY_EXISTS = 183
    $occurenceName = StringReplace($occurenceName, "
\", "") ; to avoid error
    Local $handle = DllCall("
kernel32.dll", "int", "CreateMutex", "int", 0, "long", 1, "str", $occurenceName)
    Local $lastError = DllCall("
kernel32.dll", "int", "GetLastError")
    If $lastError[0] = $ERROR_ALREADY_EXISTS Then
        If $flag = 0 Then
            Exit -1
        Else
            SetError($lastError[0])
            Return 0
        EndIf
    EndIf
    Return $handle[0]
EndFunc   ;==>_Singleton


; _IsPressed (is a key pressed?)
; Author(s):    ezzetabi and Jon / Valik 
;
func ce_IsPressed($Key)
    local $kp = DllCall('user32.dll', "
int", "GetAsyncKeyState", "int", '0x' & $Key; does this work on Win9x ? :/
    if not @error and BitAND($kp[0], 0x8000) = 0x8000 then return 1
    return 0
endfunc


func QuitBox()
    $QuitBox = 1
endfunc



#cs

    0.5.2

    *    fixed a bug in GetParent where for a path like..
        
            I:\work\dev\all files\test\a
            
        It would remove the "
\a", as expected, but removed it from 
        "
dev\all files", making "devll files", unexpected!

        Now we simply trim off "
so-many" characters from the right. the 
        "
so-many" being the length of the final part of the path.


    *    BaseName() will now trim any traling slashes you might have left at the
        end of the folder path, before working on the string.


#ce

"