#include <iostream>
#include <string>
#include <vector>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include "testing.h"

using namespace std;

// returns whether or not file exists; works with file and directory names
int fileExists(const char * fileName)
{
   struct stat statInfo;  // we'll ignore this
   if (0 == stat(fileName, &statInfo)) {
      return 1;
   } else {
      cout << "Asking about " << fileName << " failed with " 
           << "'" << strerror(errno) << "'" << endl;
      return 0;
   }
}

// looks through the directory of the given name and stores the names 
// of the regular files in the directory as strings in a vector
// code adapted from submit.c in GRASST
void fillFileList(const char * directoryName, vector<string> & fileList)
{
   DIR * directoryHandle;
   struct dirent * entry;
   directoryHandle = opendir(directoryName);
   if (directoryHandle == 0) {
      cerr <<"Unable to open " << directoryName << endl;
   } else {
      // gather the names
      while ((entry = readdir(directoryHandle)) != NULL) {
         if (entry->d_name[0] != '.') {
            fileList.push_back(entry->d_name);
         }
      }
      closedir(directoryHandle);
   }     
}

// print a description and then the contents of the fileList vector
void printFileList(const string & description, const vector<string> & fileList)
{
   int count = fileList.size( );
   cout << description << ": ";
   for (int i=0; i < count; i++) {
      cout << fileList[i] << " ";
   }
   cout << endl;
}

// returns a string containing the processID of this process
string processIDstring( )
{
   int processID = getpid( );
   char holder[20];
   
   sprintf(holder, "%d", processID);
   return string(holder);  
}

// execute prog with input from inputDir/inputFile and save output in outputFile
// cputime and filesize limits imposed to decrease effect of runaway programs
// -t 2 means two seconds cputime and -f 10 means a filesize of 10 KB
int runProgram(const string & prog, const string & inputDir, 
               const string & inputFile, const string & outputFile)
{
   int returnValue;
   string command;
   
   command = "ulimit -t 2 -f 10; ";
   command +=  "./" + prog + " < " + inputDir + "/" + inputFile
           + " > " + outputFile;
   cout << command << endl;
   returnValue = system(command.c_str( ));
   return returnValue;
}

// remove fileToRemove from file system
int removeFile(const string & fileToRemove)
{
   int returnValue;
   string command;
   
   command = "rm " + fileToRemove;
   returnValue = system(command.c_str( ));
   return returnValue;
}