/*
  Malcolm Kesson
  Nov 11 2019
  For an example of how this is used see:
    www.fundz.com/rfm/procedural/place_archives/index.html
*/
#include <vector>
#include <string>
#include <stdio.h>
  
#ifdef  _WIN32
    #include <Windows.h>
    std::vector<std::string> winGetFiles(std::string pattern) {
        std::vector<std::string> paths;
        std::string parentDir = pattern.substr(0, pattern.find_last_of("/\\"));
        //printf("%s\n", parentDir.c_str());
        WIN32_FIND_DATA fd;
        HANDLE hFind = ::FindFirstFile(pattern.c_str(), &fd);
        if(hFind != INVALID_HANDLE_VALUE) {
            do {
                // read all (real) files in current folder
                // , delete '!' read other 2 default folder . and ..
                if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) {
                    paths.push_back(parentDir + "/" + fd.cFileName);
                }
            } while(::FindNextFile(hFind, &fd));
            ::FindClose(hFind);
        }
        return paths;
    }
#else
    #include <glob.h>
    std::vector<std::string> globGetFiles(const std::string& pattern){
        glob_t glob_result;
        glob(pattern.c_str(),GLOB_TILDE,NULL,&glob_result);
        std::vector<std::string> paths;
        for(unsigned int i=0;i<glob_result.gl_pathc;++i){
            paths.push_back(std::string(glob_result.gl_pathv[i]));
            }
        globfree(&glob_result);
        return paths;
        }
#endif
  
std::vector<std::string> getFiles(std::string pattern) {
    #ifdef  _WIN32
        return winGetFiles(pattern);
    #else
        return globGetFiles(pattern);
    #endif
    }