#ifndef RunLock_HH
#define RunLock_HH

#include <sys/types.h>
#include <unistd.h>

#include <string>
#include <fstream>


class RunLock {

public:
  RunLock(const std::string &f) : _fileName(f+".lock") {
    
    std::ifstream fin(_fileName.c_str(),std::ios::in);
    if(fin) {
      std::cerr << "RunLock::ctor()  ERROR " << _fileName
		<< " already exists" << std::endl
		<< " If this lock file is stale, do " << std::endl
		<< "  rm " << _fileName << std::endl
		<< " and restart this program" << std::endl;
      assert(false);
    }

    std::ofstream fout(_fileName.c_str());
    assert(fout);
    fout << getpid() <<std::endl;
    fout.close();

    //std::string command("touch "+_fileName);
    //std::cout << command << std::endl;
    //system(command.c_str());
  }

  ~RunLock() {
    std::string command("rm "+_fileName);
    //std::cout << command << std::endl;
    system(command.c_str());
  }

  std::ostream& print(std::ostream &o=std::cout, std::string s="") const {
    o << s << "RTunLock::print()  Lock file "
      << _fileName << " created" << std::endl;
  return o;
}
 


private:
  const std::string _fileName;
};

#endif
