 /* String formatting aSub subroutines
 *----------------------------------------------------------------------------*/

#include <algorithm>  // remove()
#include <iostream>
#include <string>
#include <registryFunction.h>
#include <aSubRecord.h>
#include <epicsExport.h>

static const int debug = 0;

void removeChars(std::string &str, const char* chars) {
    for (int i = 0; chars[i]; ++i) {
        str.erase(remove(str.begin(), str.end(), chars[i]), str.end());
    }
}

static long asQuotedStrToDouble(aSubRecord *pr) {
    std::string str = static_cast<char*>(pr->a);
    double* out = static_cast<double*>(pr->vala);

    if (str.empty()) return -1;
    if (debug) std::cout << str << " --> ";
    // Remove all double-quote characters
    removeChars(str, "\"");
    *out = strtod(str.c_str(), NULL);
    if (debug) std::cout << str << " --> " << *out << std::endl;
    return 0;
}

static long asQuotedStrToStr(aSubRecord *pr) {
    std::string str = static_cast<char*>(pr->a);

    if (debug) std::cout << str << " --> ";
    // Remove all double-quote characters
    removeChars(str, "\"");
    if (debug) std::cout << str << std::endl;
    pr->vala = static_cast<void*>(&str[0]);
    return 0;
}

epicsRegisterFunction(asQuotedStrToDouble);
epicsRegisterFunction(asQuotedStrToStr);

