#include <iostream>
using namespace std;

char *my_strdup(const char *src);

class String {

private:
  char *m_pS;
  int m_size;

public:
  String();
  ~String();
  void Set(char *pS);
  void Print();
  int Match(char *pS);

};

String::String() { 
  cout << "Created a string!\n";
}

String::~String() {
  //destructor
  delete m_pS;
  cout << "Deleted a string!\n";
}

void String::Set(char *pS) {
  //find the size of pS
  //find a way to find out where the array ends
  int stringsize = 0;
  bool done = false;
  while (!done) {
  	if (pS[stringsize] == 0) {
		m_pS = new char[stringsize];
		done = true;
	}
	stringsize++;
  }  
  for (int i=0; i < stringsize; i++) {
    m_pS[i] = pS[i];
  }
  m_size = stringsize;
}

void String::Print() {
  cout << m_pS << endl;
}

int String::Match(char *pS) {
	int matches = 0;
	for (int i = 0; m_pS[i] != 0; i++) {
		if (pS[0] == m_pS[i]) {
		for (int j = 0; pS[j] != 0 && pS[j] == m_pS[i+j]; ++j) {
			if (pS[j+1] == 0) {
				matches++;
			}
		}
		}
	}
	return matches;
}

int main(int argc, char *argv[]) {
  String myString;
  int matches;
  char buf[BUFSIZ];
  
  myString.Set("THISIS REALLY IS A REALLY BIG STRING TEST!!!");
  myString.Print();
  matches = myString.Match("REALLY");
  cout << "matched " << matches << " times." << endl;
  cin.getline(buf, sizeof(buf));
  myString.Set(my_strdup(buf));
  printf("buf = \"%s\"\n", buf);

}

char *my_strdup(const char *src) {
  int i, len;
  char *ret = NULL;

  if (!src)
    return NULL;

  len = strlen(src);
  ret = (char*) malloc(len + 1);
  if (!ret)
    return NULL;

  /* the fast and easy way */
  /* memcpy(ret, src, len + 1); */

  /* the bullshit slow way */
  for (i = 0; i < len; i++)
    ret[i] = src[i];
  ret[len] = '\0';
  
  return ret;
}

