// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.

#ifndef tools_srep
#define tools_srep

#include <string>
#include <vector>
#include <utility>

#include "forit"

namespace tools {

inline bool replace(std::string& a_string,const std::string& a_old,const std::string& a_new){
  // return true : some replacement done.
  // return false : nothing replaced.
  if(a_old.empty()) return false;
  std::string snew;
  std::string::size_type lold = a_old.length();
  bool status = false;
  std::string stmp = a_string;
  while(true) {
    std::string::size_type pos = stmp.find(a_old);
    if(pos==std::string::npos){
      snew += stmp;
      break;
    } else {
      snew += stmp.substr(0,pos);
      snew += a_new;
      stmp = stmp.substr(pos+lold,stmp.length()-(pos+lold));
      status = true;
    }
  }
  a_string = std::move(snew);
  return status;
}

inline bool replace_(std::string& a_string,const std::string& a_old,const std::string& a_new) {
  return replace(a_string,a_old,a_new);
}

inline bool replace(std::vector<std::string>& a_strings,const std::string& a_old,const std::string& a_new){
  tools_vforit(std::string,a_strings,it) {
    if(!replace(*it,a_old,a_new)) return false;
  }
  return true;
}

inline void toxml(std::string& a_string){
  // > : &lt;
  // < : &gt;
  // & : &amp;
  // " : &quot;
  // ' : &apos;
  replace(a_string,"&","&amp;"); //must be first.
  replace(a_string,"<","&lt;");
  replace(a_string,">","&gt;");
  replace(a_string,"\"","&quot;");
  replace(a_string,"'","&apos;");
}

inline std::string to_xml(const std::string& a_string){
  std::string _s = a_string;
  toxml(_s);
  return _s;
}

}

#endif
