

// YACL demo: a simple "which" program: displays which file will be
// executed in response to a command, using the PATH environment variable.

// M. A. Sridhar, 6/28/94


#include "base/string.h"
#include "base/strgseq.h"
#include "io/binfile.h"

#include <iostream.h>
#include <stdlib.h>

char* Extensions[] = {
#ifdef __UNIX__
    "",
#elif defined (__DOS__) || defined(__MS_WIN32__)
    ".exe",
    ".com",
    ".bat",
#elif defined (__OS2__)
    ".exe",
    ".cmd",
#endif
    0
};


main (int argc, char* argv[])
{
    char* path = getenv("PATH");
    if (!path) {
        cerr << "which: getenv(\"PATH\") failed" << endl;
        return -1;
    }
    CL_String path_string (path);
#if defined ( __DOS__ ) || defined(__OS2__) || defined(__MS_WIN32__)
    char field_seps[] = ";";
    char dir_sep = '\\';
#else
    static char field_seps[] = ":";
    char dir_sep = '/';
#endif
    CL_StringSequence dirs = path_string.Split (field_seps);
#if defined (__DOS__) || defined (__OS2__) || defined(__MS_WIN32__)
    dirs.Insert (".;");
#endif
    register short n = dirs.Size();
    for (short j = 1; j < argc; j++) {
        for (short i = 0; i < n; i++) {
            CL_String base_file = dirs[i] + CL_String (dir_sep, 1) + argv[j];
            for (short k = 0; Extensions[k] != 0; k++) {
                CL_String file = base_file + Extensions[k];
                if (CL_BinaryFile::Exists (file, CLFile_Read)) {
                    cout << file << endl;
                    break;
                }
            }
        }
    }
    return 0;
}
