#include <string>
#include <cstdlib>
#include <fstream>
#include <map>


/*
################################################################################
# BlueKaribu IniParser
# Copyright by Jens Schmidt
################################################################################
*/

class bk_parse
{
  public:                       // öffentlich
    bk_parse(std::string inifile);               // der Default-Konstruktor
    void writeIni();
    std::map<std::string, std::map<std::string, std::string> > section;
    std::string filename;            
  private:
    std::map<int, std::string> my_explode (std::string str, char sep);
    std::string str_replace(std::string rep, std::string wit, std::string in);
};


bk_parse::bk_parse(std::string inifile)
{
  this->filename = inifile;
  std::ifstream fin(this->filename.c_str());
  std::string buffer, act_map;
  std::map<int, std::string> tokenmap;

  while (fin.good()) {
    getline(fin,buffer,'\n');
    if (buffer[0] == '[' && buffer[buffer.length()-1] == ']') {
      act_map = this->str_replace("[", "", this->str_replace("]", "", buffer));        
    } else {
      tokenmap = this->my_explode(buffer, '=');
      this->section[act_map][tokenmap[0]] = tokenmap[1];  
    }
  }
  fin.close(); 
}

std::string bk_parse::str_replace(std::string rep, std::string wit, std::string in) {
  int pos;
  while (true) {
    pos = in.find(rep);
    if (pos == -1) {break;} else {
      in.erase(pos, rep.length());
      in.insert(pos, wit);
    }
  }
  return in;
}

std::map<int, std::string> bk_parse::my_explode (std::string str, char sep) {
std::map<int, std::string> returnmap;
std::string strTemp = "";
int x = 0;
  for(unsigned int i=0;i<=str.length();i++)
  {
	if(str[i]==sep or str.length() == i) {
    returnmap[x] = strTemp;
    strTemp.clear();
    x++;
	} else {
      strTemp += str[i];
    }
 }   
	return returnmap;
}


void bk_parse::writeIni() {
  std::ofstream writer(this->filename.c_str());
  for( std::map<std::string, std::map<std::string, std::string> >::iterator iter = this->section.begin(); iter != this->section.end(); iter++ ) {
    writer << "[" << (*iter).first << "]" << std::endl;
    for( std::map<std::string, std::string>::iterator iter2 = (*iter).second.begin(); iter2 != (*iter).second.end(); iter2++ ) {
      writer << (*iter2).first << "="<< (*iter2).second << std::endl;
    }
  }     
}

