#include "io_ncbase.h"

#ifdef ENABLE_TRAJECTORY_NC
bool NCCheckErr(int ncerr) {
    if (ncerr != NC_NOERR) {
        cout << nc_strerror(ncerr) << endl;
        return true;
    }
    return false;
}

std::string NCGetAttrText(int ncid, int vid, const char *attribute) {
    size_t attlen;
    std::string attrOut;
    // Get attr length
    if (NCCheckErr(nc_inq_attlen(ncid, vid, attribute, &attlen))) {
        cout << "Warning: Getting length for attribute '" << attribute << "'" << endl;
        return attrOut;
    }
    // Allocate space for attr text, plus one for null char
    char *attrText = new char[(attlen + 1)];
    // Get attr text
    if (NCCheckErr(nc_get_att_text(ncid, vid, attribute, attrText))) {
        cout << "Warning: Getting attribute text for '" << attribute << "' " << endl;
        delete[] attrText;
        return attrOut;
    }
    // Append null char - NECESSARY?
    attrText[attlen] = '\0';
    attrOut.assign(attrText);
    delete[] attrText;

    return attrOut;
}

std::string NCGetAttrText(int ncid, const char *attribute) {
    return NCGetAttrText(ncid, NC_GLOBAL, attribute);
}

int NCGetDimInfo(int ncid, const char *attribute, unsigned int &length) {
    int dimID;
    size_t slength = 0;

    length = 0;
    // Get dimid
    if (NCCheckErr(nc_inq_dimid(ncid, attribute, &dimID))) {
        cerr << "Error: Getting dimID for attribute " << attribute << endl;
        return -1;
    }
    // get Dim length
    if (NCCheckErr(nc_inq_dimlen(ncid, dimID, &slength))) {
        cerr << "Error: Getting length for attribute " << attribute << endl;
        return -1;
    }
    length = (unsigned int) slength;
    return dimID;
}

// For backwards compatibility only
int NCGetDimInfo(int ncid, const char *attribute, int &length) {
    unsigned int ulen;
    int dimID = NCGetDimInfo(ncid, attribute, ulen);
    length = (int) ulen;
    return dimID;
}
#endif