/* Eric Knibbe, David Streng
*  CS 232
*  Project 3
*/

#ifndef PATH_CPP
#define PATH_CPP

#include "path.h"

// constructor for Path
Path::Path()
{
	//temp holds the current location in the PATH
	char* temp = getenv("PATH");

	//curr holds the temporary string of the currently processed
	//part of path, until it is put into the vector
	string curr = temp;

	//sze holds the size of the string, i is a counter
	int sze = curr.size(), i = 0;

	//reset curr to null so that you start fresh
	curr = "";	

	//while i is smaller than the size of the array, increase i by
	//one
	for(i = 0; i < sze-1; i++)
	{
		//while the current character is not a colon (iow, while
		//we are on a single path) save, character by character,
		//the path into a string, increasing i for each character
		while (*temp != ':' && i < sze)
		{
			curr += *temp;
			temp++;
			i++;
		}
		//skip the colon (and counteract the i++ in the for loop)
		temp++;
			
		//add this string to the vector and reset the string
		pth.push_back(curr);
		curr = "";
	}
}

// find
int Path::find(const string& program) const
{	
	dirent *d;
	string dirname;
	DIR *dir;
	for (int n=0; n < pth.size(); n++)
	{
		dirname = pth.at(n);
		dir = opendir(dirname.c_str());
		d = readdir(dir);
		while ((d != NULL) && (program.compare(d->d_name) != 0))
		{	
			d = readdir(dir);
		}
		if (d != NULL)
		{return n;}
		closedir(dir);
	}
	return -1;
}

// getDirectory
string Path::getDirectory(int i) const
{
	return pth.at(i);
}
#endif 

