/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/


#include <Cached.h>

//__________________________________________________ subString

Cached Cached::subString(int StartPos, int Length) const
{
    char* temp = new char[Length + 1];

    if (Str) {
        //-- does not check that substring inside original string!
        strncpy(temp, Str + StartPos - 1, Length);
        temp[Length] = '\0';
    }
    else {
        *temp = '\0';
    }
    Cached SubString(temp);
    delete[] temp;

    return SubString;
}


static Cached add(const char* a, const char* b)
{
    if (!a)
        return b;
    if (!b)
        return a;

    size_t n = strlen(a) + strlen(b) + 1;
    char buf[1024];

    if (n < sizeof(buf)) {
        strcpy(buf, a);
        strcat(buf, b);
        return buf;
    }
    else {
        char* p = new char[n];
        strcpy(p, a);
        strcat(p, b);
        Cached x = p;
        delete[] p;
        return x;
    }
}

Cached operator+(const char* s, const Cached& c)
{
    return add(s, c);
}

Cached Cached::operator+(int n) const
{
    char buf[80];
    sprintf(buf, "%d", n);
    return add(*this, buf);
}

Cached Cached::toUpper()
{
    const char* t = Str;
    char* data = new char[strlen(Str) + 1];
    int i = 0;

    while (*t) {
        data[i] = toupper(*t);
        t++;
        i++;
    }
    data[i] = '\0';

    Cached x = data;
    delete[] data;
    return x;
}
