/*
  ファイル操作
  Satofumi KAMIMURA
  $Id: fileUtils.cpp 286 2008-10-20 09:40:22Z satofumi $
*/

#include "fileUtils.h"
#include "detect_os.h"
#if defined Linux || defined Cygwin
#include <unistd.h>
#else
#include <windows.h>
#include <direct.h>
#include <io.h>
#ifndef F_OK
#define F_OK 06
#endif
#ifndef W_OK
#define W_OK 06
#endif
#endif
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fstream>


std::string VXV::searchFile(const char* file, const char* path[]) {

  for (const char** p = path; *p != NULL; ++p) {
    std::string full_path = std::string(*p);
    if ((!full_path.empty() && full_path[full_path.size()-1] != '/') &&
	(file[0] != '/')) {
      full_path += "/";
    }
    full_path += file;

    if (access(full_path.c_str(), F_OK) == 0) {
      return full_path;
    }
  }
  return "";
}


void VXV::createArgs(std::vector<char*>& args, const char* file) {
  std::ifstream fin(file);

  std::string line;
  while (!fin.eof()) {
    getline(fin, line);

    // 空白の除去
    int index = 0;
    do {
      index = static_cast<int>(line.find_first_of(" \t\r\n", index));
      if (index >= 0) {
	line.erase(index, 1);
      }
    } while (index >= 0);

    // コメントの除去
    int last = static_cast<int>(line.find("#"));
    if (last >= 0) {
      line.erase(last);
    }

    // 行の内容を args に追加
    if (!line.empty()) {
      char* buffer = new char [line.size() +1];
      sprintf(buffer, "%s", line.c_str());
      args.push_back(buffer);
    }
  }
  fin.close();
}


void VXV::deleteArgs(std::vector<char*>& args) {
  for (std::vector<char*>::iterator it = args.begin();
       it != args.end(); ++it) {
    delete [] *it;
  }
}


int VXV::createDirs(std::string dir_path) {
  if (!access(dir_path.c_str(), W_OK)) {
    return 0;
  }
  createDirs(dir_path.substr(0, dir_path.find_last_of('/')));

  // ディレクトリの作成
#if defined Linux || defined Cygwin
  return mkdir(dir_path.c_str(), 0755);
#else
  return _mkdir(dir_path.c_str());
#endif
}
