//************************************************
// Author: Federica Lionetto
// Created on: 10/04/2015
//************************************************

/*
List of useful functions.
*/

// Header guard.
#ifndef __USEFULFUNCTIONS_C_INCLUDED__
#define __USEFULFUNCTIONS_C_INCLUDED__

#include "Lib.C"

// Declarations.

// It returns a vector of strings with all the files in a given directory or an error message if the given directory cannot be opened.
vector<string> open(string path = ".");

// It ignores lines in a text file.
std::istream& ignoreline(std::ifstream& in, std::ifstream::pos_type& pos);

// It gets the last line of a text file.
std::string getLastLine(std::ifstream& in);



// Definitions.

// It returns a vector of strings with all the files in a given directory or an error message if the given directory cannot be opened.
vector<string> open(string path) {
  DIR *dir = NULL;
  dirent *pdir = NULL;
  vector<string> files;
  
  dir = opendir(path.c_str());
  if (dir) {
  
  while (pdir = readdir(dir)) {
    if ((strcmp(pdir->d_name,".") != 0) && (strcmp(pdir->d_name,"..") != 0))
      files.push_back(pdir->d_name);
  }
  closedir(dir);
  }
  else
  {
    cout << "Error! Unable to open input directory..." << endl;
  }
  
  return files;
}

// It ignores lines in a text file.
std::istream& ignoreline(std::ifstream& in, std::ifstream::pos_type& pos)
{
    pos = in.tellg();
    return in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

// It gets the last line of a text file.
std::string getLastLine(std::ifstream& in)
{
    std::ifstream::pos_type pos = in.tellg();

    std::ifstream::pos_type lastPos;
    while (in >> std::ws && ignoreline(in, lastPos))
        pos = lastPos;

    in.clear();
    in.seekg(pos);

    std::string line;
    std::getline(in, line);
    return line;
}

#endif

