`` File Sort - www.scriptol.org
`` Licence: Public Domain

`` Sort lines of a text file in ascending order
`` The file is renamed with a ".bak" extension
`` and is replaced by the same file, sorted.


` array is alias for the original array sorted
void quickSort(alias array theArray, int first, int last)
    int f = first
    int l = last
    dyn item = theArray[(f + l) / 2]

    do
        while theArray[f] < item let  f + 1
        while item < theArray[l] let  l - 1
        if f <= l
            swap(theArray[f], theArray[l])
            f + 1
            l - 1
        /if
    /do while f <= l

    if first < l ?  quickSort(theArray, first, l)
    if f < last  ?  quickSort(theArray, f, last)

return



void usage()
    print "File Sort - www.scriptol.org"
    print "usage: filesort filename"
    print "       a bak file will be created"
    exit(0)
return    

int main(int argc, array argv)

    array thefile
    text name = argv[1]
    
    if not file_exists(name)
        print name, "not found"
        usage()
    /if    

    thefile.load(name)
    scan thefile let thefile[] = thefile[].rtrim()
    thefile.sort()
    rename(name, name + ".bak")
    thefile.store(name)
    
return 1