// STRING.CPP


#include "string.hpp"
#include <iostream.h>
#include <string.h>
#include <stdlib.h>



string::string()
{
    p = new srep;
    p->s = 0;
}

string::string(const string& x)
{
    x.p->n++;
    p = x.p;
}

string::string(const char* s)
{
    p = new srep;
    p->s = new char [strlen(s) +1];
    strcpy(p->s, s);
}
string::~string()
{
    if (--p->n == 0 )
    {
      delete [] p->s;
      delete p;
    }
}

string& string::operator=(const char *s)
{
    if (p->n > 1)		// disconnect self
    {
      p->n--;
      p = new srep;
    }
    else
      delete [] p->s;		 // free old string

    p->s = new char[strlen(s)+1];
    strcpy(p->s, s);
    return *this;
}

string& string::operator=(const string& x)
{
    x.p->n++;    // protect against "st = st"
    if (--p->n == 0)
    {
      delete [] p->s;
      delete p;
    }
    p= x.p;
    return *this;
}

ostream& operator<<(ostream& s, const string& x)
{
    return s<< x.p->s;
}

istream& operator>>(istream& s, string& x)
{
	 char buf[512];

	 // s.getline(buf,500);
    s >> buf;
    x = buf;
    return s;
}

void error( const char* p)
{
  cerr << p << "\n";
  exit(1);
}

char& string::operator[] (int i)
{
    if(i<0 || strlen(p->s) <i)
      error("index out of range");
    return p->s[i];
}

