summaryrefslogtreecommitdiff
path: root/modules/dep/g3dlite/source/FileSystem.cpp
blob: f082937a908b944a2366b822641a5f40a5fe61e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
/**
 @file FileSystem.cpp
 
 @author Morgan McGuire, http://graphics.cs.williams.edu
 
 @author  2002-06-06
 @edited  2010-04-10
 */
#include "G3D/FileSystem.h"
#include "G3D/System.h"
#include "G3D/stringutils.h"
#include "G3D/fileutils.h"
#include <sys/stat.h>
#include <sys/types.h>
#if _HAVE_ZIP /* G3DFIX: Use ZIP-library only if defined */
    #include "zip.h"
#endif
#include "G3D/g3dfnmatch.h"
#include "G3D/BinaryInput.h"
#include "G3D/BinaryOutput.h"

#ifdef G3D_WIN32
    // Needed for _getcwd
#   include <direct.h>

    // Needed for _findfirst
#   include <io.h>
#  ifdef __MINGW32__
#    define stat64 stat
#  else
#    define stat64 _stat64
#  endif
#else
#   include <dirent.h>
#   include <fnmatch.h>
#   include <unistd.h>
#   define _getcwd getcwd
#   define _stat stat
#endif

#ifdef __CYGWIN__
#define stat64 stat
#endif

namespace G3D {

static FileSystem* common = NULL;

FileSystem& FileSystem::instance() {
    init();
    return *common;
}


void FileSystem::init() {
    if (common == NULL) {
        common = new FileSystem();
    }
}


void FileSystem::cleanup() {
    if (common != NULL) {
        delete common;
        common = NULL;
    }
}

FileSystem::FileSystem() : m_cacheLifetime(10) {}

/////////////////////////////////////////////////////////////

bool FileSystem::Dir::contains(const std::string& f) const {
    
    for (int i = 0; i < nodeArray.size(); ++i) {
#       ifdef G3D_WIN32
            if (stricmp(f.c_str(), nodeArray[i].name.c_str()) == 0) {
                return true;
            }
#       else
            if (f == nodeArray[i].name) {
                return true;
            }
#       endif
    }
    return false;
}
    
void FileSystem::Dir::computeZipListing(const std::string& zipfile, const std::string& pathInsideZipfile) {
#if _HAVE_ZIP /* G3DFIX: Use ZIP-library only if defined */
    struct zip* z = zip_open( FilePath::removeTrailingSlash(zipfile).c_str(), ZIP_CHECKCONS, NULL );
    debugAssert(z);

    int count = zip_get_num_files( z );
    Set<std::string> alreadyAdded;
    for (int i = 0; i < count; ++i) {
        struct zip_stat info;
        zip_stat_init( &info );    // TODO: Docs unclear if zip_stat_init is required.
        zip_stat_index( z, i, ZIP_FL_NOCASE, &info );
        
        // Fully-qualified name of a file inside zipfile
        std::string name = info.name;

        if (beginsWith(name, pathInsideZipfile)) {
            // We found something inside the directory we were looking for,
            // so the directory itself must exist                        
            exists = true;

            // For building the cached directory listing, extract only elements that do not contain 
            // additional subdirectories.

            int start = pathInsideZipfile.size();
            if ((int(name.length()) > start) && isSlash(name[start])) {
                ++start;
            }
            int end = findSlash(name, start);
            if (end == -1) {
                // There are no more slashes; add this name
                name = name.substr(start);
                if (alreadyAdded.insert(name)) {
                    Entry& e = nodeArray.next();
                    e.name = name;
                    e.type = FILE_TYPE;
                }
            } else {
                // There are more slashes, indicating that this is a directory
                name = name.substr(start, end);
                if (alreadyAdded.insert(name)) {
                    Entry& e = nodeArray.next();
                    e.name = name;
                    e.type = DIR_TYPE;
                }
            }
        }
    }
    
    zip_close(z);
    z = NULL;
#endif
}


FileSystem::Dir& FileSystem::getContents(const std::string& path, bool forceUpdate) {
    const std::string& key = 
#   if defined(G3D_WIN32)
        FilePath::canonicalize(FilePath::removeTrailingSlash(toLower(FilePath::canonicalize(resolve(path)))));
#   else
        FilePath::canonicalize(FilePath::removeTrailingSlash(FilePath::canonicalize(resolve(path))));
#   endif
    
    RealTime now = System::time();
    Dir& dir = m_cache.getCreate(key);

    if ((now > dir.lastChecked + cacheLifetime()) || forceUpdate) {
        dir = Dir();

        // Out of date: update
        dir.lastChecked = now;

        struct _stat st;
        const bool exists = _stat(key.c_str(), &st) != -1;
        const bool isDirectory = (st.st_mode & S_IFDIR) != 0;

        // Does this path exist on the real filesystem?
        if (exists && isDirectory) {

            // Is this path actually a directory?
            if (isDirectory) {
                dir.exists = true;
                // Update contents
#               ifdef G3D_WIN32
                    const std::string& filespec = FilePath::concat(key, "*");
                    struct _finddata_t fileinfo;
                    intptr_t handle = _findfirst(filespec.c_str(), &fileinfo);
                    debugAssert(handle != -1);
                    int result = 0;
                    do {
                        if ((strcmp(fileinfo.name, ".") != 0) && (strcmp(fileinfo.name, "..") != 0)) {
                            Entry& e = dir.nodeArray.next();
                            e.name = fileinfo.name;
                            if ((fileinfo.attrib & _A_SUBDIR) != 0) {
                                e.type = DIR_TYPE;
                            } else {
                                e.type = FILE_TYPE;
                            }
                        }

                        result = _findnext(handle, &fileinfo);
                    } while (result == 0);
                    _findclose(handle);

#               else
                    DIR* listing = opendir(key.c_str());
                    debugAssertM(listing, "opendir failed on '" + key + "'");
                    struct dirent* entry = readdir(listing);
                    while (entry != NULL) {
                        if ((strcmp(entry->d_name, "..") != 0) && (strcmp(entry->d_name, ".") != 0)) {
                            Entry& e = dir.nodeArray.next();
                            e.name = entry->d_name;

#                           ifdef _DIRENT_HAVE_D_TYPE
                                // Not all POSIX systems support this field
                                // http://www.delorie.com/gnu/docs/glibc/libc_270.html
                                switch (entry->d_type) {
                                case DT_DIR:
                                    e.type = DIR_TYPE;
                                    break;
                                    
                                case DT_REG:
                                    e.type = FILE_TYPE;
                                    break;
                                    
                                case DT_UNKNOWN:
                                default:
                                    e.type = UNKNOWN;
                                    break;
                                }
#                           endif
                        }
                        entry = readdir(listing);
                    }
                    closedir(listing);
                    listing = NULL;
                    entry = NULL;
#               endif
            }

        } else {
            std::string zip;

            if (exists && isZipfile(path)) {
                // This is a zipfile; get its root
                dir.isZipfile = true;                
                dir.computeZipListing(path, "");

            } else if (inZipfile(path, zip)) {

                // There is a zipfile somewhere in the path.  Does
                // the rest of the path exist inside the zipfile?
                dir.inZipfile = true;

                dir.computeZipListing(zip, path.substr(zip.length() + 1));
            }
        }        
    }

    return dir;
}


bool FileSystem::_inZipfile(const std::string& path, std::string& z) {
    // Reject trivial cases before parsing
    if (path.find('.') == std::string::npos) {
        // There is no zipfile possible, since G3D requires
        // an extension on zipfiles.
        return false;
    }

    // Look at all sub-paths containing periods.
    // For each, ask if it is a zipfile.
    int current = 0;
    current = path.find('.', current);

    while (current != -1) {
        // xxxxx/foo.zip/yyyyy
        current = path.find('.', current);

        // Look forward for the next slash
        int s = findSlash(path, current);

        if (s == -1) {
            // No more slashes
            return false;
        }

        z = path.substr(0, s); 
        if (_isZipfile(z)) {
            return true;
        }
        
        current = s + 1;
    }

    z = "";
    return false;
}


bool FileSystem::_isZipfile(const std::string& filename) {
    if (FilePath::ext(filename).empty()) {
        return false;
    }
    
    FILE* f = fopen(FilePath::removeTrailingSlash(filename).c_str(), "r");
    if (f == NULL) {
        return false;
    }
    uint8 header[4];
    fread(header, 4, 1, f);
    
    const uint8 zipHeader[4] = {0x50, 0x4b, 0x03, 0x04};
    for (int i = 0; i < 4; ++i) {
        if (header[i] != zipHeader[i]) {
            fclose(f);
            return false;
        }
    }
    
    fclose(f);
    return true;
}


FILE* FileSystem::_fopen(const char* filename, const char* mode) {
    for (const char* m = mode; *m != '\0'; ++m) {
        if (*m == 'w') {
            // Purge the cache entry for the parent of this directory
            _clearCache(FilePath::parent(_resolve(filename)));
            break;
        }
    }
    return ::fopen(filename, mode);
}


void FileSystem::_clearCache(const std::string& path) {
    if ((path == "") || FilePath::isRoot(path)) {
        m_cache.clear();
    } else {
        Array<std::string> keys;
        m_cache.getKeys(keys);

        const std::string& prefix = 
#           ifdef G3D_WIN32
                toLower(FilePath::canonicalize(FilePath::removeTrailingSlash(_resolve(path))));
#           else
                FilePath::canonicalize(FilePath::removeTrailingSlash(_resolve(path)));
#           endif
        const std::string& prefixSlash = prefix + "/";

        for (int k = 0; k < keys.size(); ++k) {
            const std::string& key = keys[k];
            if ((key == prefix) || beginsWith(key, prefixSlash)) {
                m_cache.remove(keys[k]);
            }
        }
    }
}


void FileSystem::_setCacheLifetime(float t) {
    m_cacheLifetime = t;
}


void FileSystem::_createDirectory(const std::string& dir) {
    
    if (dir == "") {
        return;
    }
    
    std::string d = _resolve(dir);
    
    // Add a trailing / if there isn't one.
    switch (d[d.size() - 1]) {
    case '/':
    case '\\':
        break;

    default:
        d += "/";
    }

    // If it already exists, do nothing
    if (_exists(FilePath::removeTrailingSlash(d))) {
        return;
    }

    // Parse the name apart
    std::string root, base, ext;
    Array<std::string> path;

    std::string lead;
    FilePath::parse(d, root, path, base, ext);
    debugAssert(base == "");
    debugAssert(ext == "");

    // Begin with an extra period so "c:\" becomes "c:\.\" after
    // appending a path and "c:" becomes "c:.\", not root: "c:\"
    std::string p = root + ".";

    // Create any intermediate that doesn't exist
    for (int i = 0; i < path.size(); ++i) {
        p += "/" + path[i];
        if (! _exists(p)) {
            // Windows only requires one argument to mkdir,
            // where as unix also requires the permissions.
#           ifndef G3D_WIN32
                mkdir(p.c_str(), 0777);
#           else
                _mkdir(p.c_str());
#           endif
        }
    }

    _clearCache(FilePath::parent(FilePath::removeTrailingSlash(d)));
}


void FileSystem::_copyFile(const std::string& source, const std::string& dest) {
#   ifdef G3D_WIN32
        // TODO: handle case where srcPath is in a zipfile
        CopyFileA(source.c_str(), dest.c_str(), FALSE);
        _clearCache(FilePath::parent(_resolve(dest)));
#   else
        // Read it all in, then dump it out
        BinaryInput  in(source, G3D_LITTLE_ENDIAN);
        BinaryOutput out(dest, G3D_LITTLE_ENDIAN);
        out.writeBytes(in.getCArray(), in.size());
        out.commit(false);
#   endif        
}


bool FileSystem::_exists(const std::string& f, bool trustCache) {

    if (FilePath::isRoot(f)) {
#       ifdef G3D_WIN32
            const std::string& winname = toLower(f.substr(0, 1)) + ":\\";
            return _drives().contains(winname);
#       else
            return true;
#       endif
    }

    std::string path = FilePath::removeTrailingSlash(f);
    std::string parentPath = FilePath::parent(path);

    const Dir& entry = getContents(parentPath, ! trustCache);

    if (FilePath::containsWildcards(f)) {
        if (! entry.exists) {
            // The directory didn't exist, so neither do its contents
            return false;
        } 

        const std::string& pattern = FilePath::baseExt(path);

#       ifdef G3D_WIN32
            static const int flags = FNM_CASEFOLD;
#       else
            static const int flags = 0;
#       endif

        // See if any element of entry matches the wild card
        for (int i = 0; i < entry.nodeArray.size(); ++i) {
            if (FilePath::matches(entry.nodeArray[i].name, pattern, flags)) {
                return true;
            }
        }

        // Could not find a match
        return false;

    } else {
        return entry.exists && entry.contains(FilePath::baseExt(path));
    }
}


bool FileSystem::_isDirectory(const std::string& filename) {
    // TODO: work with zipfiles and cache
    struct _stat st;
    const bool exists = _stat(FilePath::removeTrailingSlash(filename).c_str(), &st) != -1;
    return exists && ((st.st_mode & S_IFDIR) != 0);
}


std::string FileSystem::_resolve(const std::string& filename, const std::string& cwd) {
    if (filename.size() >= 1) {
        if (isSlash(filename[0])) {
            // Already resolved
            return filename;
        } else {

            #ifdef G3D_WIN32
                if ((filename.size() >= 2) && (filename[1] == ':')) {
                    // There is a drive spec on the front.
                    if ((filename.size() >= 3) && isSlash(filename[2])) {
                        // Already fully qualified
                        return filename;
                    } else {
                        // The drive spec is relative to the
                        // working directory on that drive.
                        debugAssertM(false, "Files of the form d:path are"
                                     " not supported (use a fully qualified"
                                     " name).");
                        return filename;
                    }
                }
            #endif
        }
    }

    // Prepend the working directory.
    return FilePath::concat(cwd, filename);
}


std::string FileSystem::_currentDirectory() {
    static const int N = 2048;
    char buffer[N];

    _getcwd(buffer, N);
    return std::string(buffer);
}


bool FileSystem::_isNewer(const std::string& src, const std::string& dst) {
    // TODO: work with cache and zipfiles
    struct _stat sts;
    bool sexists = _stat(src.c_str(), &sts) != -1;

    struct _stat dts;
    bool dexists = _stat(dst.c_str(), &dts) != -1;

    return sexists && ((! dexists) || (sts.st_mtime > dts.st_mtime));
}


int64 FileSystem::_size(const std::string& filename) {
    struct stat64 st;
    int result = stat64(filename.c_str(), &st);
    
    if (result == -1) {
#if _HAVE_ZIP /* G3DFIX: Use ZIP-library only if defined */
        std::string zip, contents;
        if (zipfileExists(filename, zip, contents)) {
            int64 requiredMem;
            
            struct zip *z = zip_open( zip.c_str(), ZIP_CHECKCONS, NULL );
            debugAssertM(z != NULL, zip + ": zip open failed.");
            {
                struct zip_stat info;
                zip_stat_init( &info );    // Docs unclear if zip_stat_init is required.
                int success = zip_stat( z, contents.c_str(), ZIP_FL_NOCASE, &info );
                debugAssertM(success == 0, zip + ": " + contents + ": zip stat failed.");
                requiredMem = info.size;
            }
            zip_close(z);
            return requiredMem;
        } else {
#endif
            return -1;
#if _HAVE_ZIP /* G3DFIX: Use ZIP-library only if defined */
        }
#endif
    }
    
    return st.st_size;
}


void FileSystem::listHelper(const std::string& shortSpec, const std::string& parentPath, Array<std::string>& result, const ListSettings& settings) {
    Dir& dir = getContents(parentPath, false);

    if (! dir.exists) {
        return;
    }

    for (int i = 0; i < dir.nodeArray.size(); ++i) {
        Entry& entry = dir.nodeArray[i];
        // See if it matches the spec
        if (FilePath::matches(entry.name, shortSpec, settings.caseSensitive)) {

            if ((entry.type == UNKNOWN) && ! (settings.files && settings.directories)) {
                // Update the type
                entry.type = isDirectory(FilePath::concat(parentPath, entry.name)) ? DIR_TYPE : FILE_TYPE;
            }
            
            if ((settings.files && settings.directories) ||
                (settings.files && (entry.type == FILE_TYPE)) ||
                (settings.directories && (entry.type == DIR_TYPE))) {
                
                if (settings.includeParentPath) {
                    result.append(FilePath::concat(parentPath, entry.name));
                } else {
                    result.append(entry.name);
                }
            }
        } // match

        if (settings.recursive && (entry.type == DIR_TYPE)) {
            listHelper(shortSpec, FilePath::concat(parentPath, entry.name), result, settings);
        }
    } // for
}


void FileSystem::_list(const std::string& spec, Array<std::string>& result, const ListSettings& settings) {
    const std::string& shortSpec = FilePath::baseExt(spec);
    const std::string& parentPath = FilePath::parent(spec);

    listHelper(shortSpec, parentPath, result, settings);
}



#ifdef G3D_WIN32
const Array<std::string>& FileSystem::_drives() {
    if (m_winDrive.length() == 0) {
        // See http://msdn.microsoft.com/en-us/library/aa364975(VS.85).aspx
        static const size_t bufSize = 5000;
        char bufData[bufSize];
        GetLogicalDriveStringsA(bufSize, bufData);

        // Drive list is a series of NULL-terminated strings, itself terminated with a NULL.
        for (int i = 0; bufData[i] != '\0'; ++i) {
            const char* thisString = bufData + i;
            m_winDrive.append(toLower(thisString));
            i += strlen(thisString) + 1;
        }
    }

    return m_winDrive;
}
#endif

/////////////////////////////////////////////////////////////////////

bool FilePath::isRoot(const std::string& f) {
#   ifdef G3D_WIN32
        if (f.length() < 2) {
            return false;
        }

        if (f[1] == ':') {
            if (f.length() == 2) {
                // e.g.,   "x:"
                return true;
            } else if ((f.length() == 3) && isSlash(f[2])) {
                // e.g.,   "x:\"
                return true;
            }
        }

        if (isSlash(f[0]) && isSlash(f[1])) {        
            // e.g., "\\foo\"
            return true;
        }
#   else
        if (f == "/") {
            return true;
        }
#   endif

    return false;
}


std::string FilePath::removeTrailingSlash(const std::string& f) {
    bool removeSlash = ((endsWith(f, "/") || endsWith(f, "\\"))) && ! isRoot(f);

    return removeSlash ? f.substr(0, f.length() - 1) : f;
}


std::string FilePath::concat(const std::string& dirname, const std::string& file) {
    // Ensure that the directory ends in a slash
    if (! dirname.empty() && 
        ! isSlash(dirname[dirname.size() - 1]) &&
        (dirname[dirname.size() - 1] != ':')) {
        return dirname + '/' + file;
    } else {
        return dirname + file;
    }
}


std::string FilePath::ext(const std::string& filename) {
    int i = filename.rfind(".");
    if (i >= 0) {
        return filename.substr(i + 1, filename.length() - i);
    } else {
        return "";
    }
}


std::string FilePath::baseExt(const std::string& filename) {
    int i = findLastSlash(filename);

#   ifdef G3D_WIN32
        int j = filename.rfind(":");
        if ((i == -1) && (j >= 0)) {
            i = j;
        }
#   endif

    if (i == -1) {
        return filename;
    } else {
        return filename.substr(i + 1, filename.length() - i);
    }
}


std::string FilePath::base(const std::string& path) {
    std::string filename = baseExt(path);
    int i = filename.rfind(".");
    if (i == -1) {
        // No extension
        return filename;
    } else {
        return filename.substr(0, i);
    }
}


std::string FilePath::parent(const std::string& path) {    
    int i = findLastSlash(removeTrailingSlash(path));

#   ifdef G3D_WIN32
        int j = path.rfind(":");
        if ((i == -1) && (j >= 0)) {
            i = j;
        }
#   endif

    if (i == -1) {
        return "";
    } else {
        return path.substr(0, i + 1);
    }
}


bool FilePath::containsWildcards(const std::string& filename) {
    return (filename.find('*') != std::string::npos) || (filename.find('?') != std::string::npos);
}


bool FilePath::matches(const std::string& path, const std::string& pattern, bool caseSensitive) {
    int flags = FNM_PERIOD | FNM_NOESCAPE | FNM_PATHNAME;
    if (!  caseSensitive) {
        flags |= FNM_CASEFOLD;
    }
    return g3dfnmatch(pattern.c_str(), path.c_str(), flags) == 0;
}


static int fixslash(int c) {
    return (c == '\\') ? '/' : c;
}


std::string FilePath::canonicalize(std::string x) {
    std::transform(x.begin(), x.end(), x.begin(), fixslash);
    return x;
}


void FilePath::parse
(const std::string&     filename,
 std::string&           root,
 Array<std::string>&    path,
 std::string&           base,
 std::string&           ext) {

    std::string f = filename;

    root = "";
    path.clear();
    base = "";
    ext = "";

    if (f == "") {
        // Empty filename
        return;
    }

    // See if there is a root/drive spec.
    if ((f.size() >= 2) && (f[1] == ':')) {
        
        if ((f.size() > 2) && isSlash(f[2])) {
        
            // e.g.  c:\foo
            root = f.substr(0, 3);
            f = f.substr(3, f.size() - 3);
        
        } else {
        
            // e.g.  c:foo
            root = f.substr(2);
            f = f.substr(2, f.size() - 2);

        }

    } else if ((f.size() >= 2) & isSlash(f[0]) && isSlash(f[1])) {
        
        // e.g. //foo
        root = f.substr(0, 2);
        f = f.substr(2, f.size() - 2);

    } else if (isSlash(f[0])) {
        
        root = f.substr(0, 1);
        f = f.substr(1, f.size() - 1);

    }

    // Pull the extension off
    {
        // Find the period
        size_t i = f.rfind('.');

        if (i != std::string::npos) {
            // Make sure it is after the last slash!
            size_t j = iMax(f.rfind('/'), f.rfind('\\'));
            if ((j == std::string::npos) || (i > j)) {
                ext = f.substr(i + 1, f.size() - i - 1);
                f = f.substr(0, i);
            }
        }
    }

    // Pull the basename off
    {
        // Find the last slash
        size_t i = iMax(f.rfind('/'), f.rfind('\\'));
        
        if (i == std::string::npos) {
            
            // There is no slash; the basename is the whole thing
            base = f;
            f    = "";

        } else if ((i != std::string::npos) && (i < f.size() - 1)) {
            
            base = f.substr(i + 1, f.size() - i - 1);
            f    = f.substr(0, i);

        }
    }

    // Parse what remains into path.
    size_t prev, cur = 0;

    while (cur < f.size()) {
        prev = cur;
        
        // Allow either slash
        size_t i = f.find('/', prev + 1);
        size_t j = f.find('\\', prev + 1);
        if (i == std::string::npos) {
            i = f.size();
        }

        if (j == std::string::npos) {
            j = f.size();
        }

        cur = iMin(i, j);

        if (cur == std::string::npos) {
            cur = f.size();
        }

        path.append(f.substr(prev, cur - prev));
        ++cur;
    }
}

}