* Implementation Notes

BermudanSwaption and DiscountCurve were implemented with the help of
a number of convenience functions and macros that may help others to
add additional QuantLib functionality to RQuantLib. The convenience
functions employ the standard template library from C++, as well
as some low-level pointer manipulations (unavoidable due to the
system-level interface to R).

It is important to observe that the C/C++ code has to make
very specific assumptions about what kind of parameters (SEXP's) to expect
(list, vector, matrix, etc.) and very little checking is done in
this code, so a parameter of the wrong type will most likely
lead to a program crash. This places the responsibility for
parameter checking at the level of the R code used to invoke
the C/C++ function. This R code must ultimately call the C/C++ function
with all parameters spelled out (no defaults).
See the R code for BermudaSwaption and DiscountCurve for an example 
of the kind of parameter checking that is required to prevent
crashes.

To keep things simple (yet flexible enough) it is assumed that 
the C++ function will be called from R with arguments of only three types:

1. a list of name/value pairs, where the value can be a number, a string,
   or a date, where a date like 9/12/2005 would be represented as c(9,12,2005)

2. a vector of numbers

3. a two-dimensional matrix of numbers

For example, we might have

result <- myfunc(params = list(tradeDate=c(9,15,2005),
                               strike=10.5,
                               method="Newton"),
                 myvec=c(1,2,3),
                 mymat=matrix(seq(1,20),4,5))

The C++ prototype might be:

extern "C" SEXP myfunc(SEXP params, SEXP vec, SEXP, mat)

Here the first parameter is a list, and its first element (at position 0)
is a date. The trade date can be extracted in the C++ code with:

Date tradeDate = getDateValueAt(params, 0);

The name of the first element of the list ('tradeDate' in this case) can
be extracted using:

char *firstElementName = getNameAt(params, 0);

So the getter functions with "Value" as part of their name get what is on
the right-hand-side of the equals sign, while the getNameAt function returns
what is on the left-hand-side (at the corresponding position in the list).

Similarly, the strike and method can be extracted using:

double strike = getDoubleValueAt(params, 1);
char *method = getStringValueAt(params, 2);

The strings 'strike' and 'method' would be returned by
getNameAt(params, 1) and getNameAt(params, 2), respectively.

Note that for a parameter like 'params' with different item types the
C++ code would have to know in advance what to expect, so looking at
the left-hand-sides is pointless in this case. On the other hand, in
the case of a list parameter like tsQuotes in DiscountCurve the names on
the left-hand-side identify the instruments used for curve construction,
and the values are all of the same type, so the C++ code does not need
to know in advance what to expect.

It is tricky to work with vector parameters in SEXP form since R sometimes
passes the vectors as double's, sometimes as int's. This is taken care
of automatically by two functions that can be used to extract myvec
and mymat, as follows:

int vecsize;
double *myvec = allocDoubleVector(vec, &vecsize)

int dim1, dim2
double **mymat = allocDoubleMatrix(mat, &dim1, &dim2)

Note that these are NOT SEXP's, they are old-fashioned pointers to
malloc-ed memory. Thus, do not apply PROTECT to them, and free the storage
when you are finished using them:

free(myvec);
freeDoubleMatrix(mymat); // same as free(*mymat); free(mymat);

Elements of myvec and mymat are accessed in the usual way, mymat[i][j], etc.

With this much information the general pattern for a C++ function
can now be sketched:

// Can have more than three parameters!
extern "C" SEXP myfunc(SEXP p1, SEXP p2, SEXP p3) {

    SEXP rl; // return list is defined outside the try/catch block

    // Put pointers to non-garbage collected memory (if there
    // are any) before the try/catch block.
    double *myvec;
    double **mymat

    try {

        // Extract the parameter values as described above
   
        // Do some computations using these parameters

        // set rl equal to a list of return values (see below) (*)

    // Catch any exceptions thrown by QuantLib, RQuantLib, etc.    
    } catch(RQLException& e) {
	    error("RQuantLib Exception: %s\n", e.what());
    } catch(std::exception& e) {
	    error("QuantLib exception: %s\n", e.what());
    } catch(...) {
	error("QuantLib exception: unknown reason\n");
    }

    // If we get here, it is OK to free our non-garbage collected storage
    freeDoubleMatrix(mymat);
    free(myvec);

    return rl; // done
}

Two convenience functions have been implemented to facilitate the
construction of the return list. One function takes a list of
name/value pairs to be returned, where all of the values are
doubles. The other function takes a list of name/SEXP pairs, where
the SEXP's can be doubles, vectors of doubles, or anything else.

The first function is useful when only named scalar values
need to be returned (no vectors). Here is an example:

    list<pair<string,double> > values;
    values.push_back(make_pair("a", aValue);
    values.push_back(make_pair("sigma", sigmaValue);
    values.push_back(make_pair("price", priceValue);
    values.push_back(make_pair("ATMStrike", strikeValue));

    rl = makeReturnList(values, params);

Here values is a list of ordered pairs (string, double), and the
operation values.push_back(make_pair(string, double)) appends
the specified pair to the end of the list.
The second parameter to makeReturnList is typically an input
parameter SEXP. If you do not want to return this replace
params with 0 here.

The second function must be used to return vectors and scalars. Here
is an example. Note that the allocations here are garbage-collected, so
we must PROTECT the pointers while working with them, and UNPROTECT
before returning to R (and don't try to free them!).

    int n = 100;
    SEXP retvec1 = PROTECT(allocVector(REALSXP,n)); // vector of n reals
    SEXP retvec2 = PROTECT(allocVector(REALSXP,n)); // vector of n reals

    SEXP retReal = PROTECT(allocVector(REALSXP,1)); // single real value
    SEXP retInt  = PROETCT(allocVector(INTSXP,1));  // single int value
    SEXP retStr  = PROTECT(allocVector(STRSXP,1));  // single string value

    // To use retvec1, retvec2 they must be cast:
    REAL(retvec1)[i] = value; // some computed result
    double z = REAL(retvec2)[j];
    ...

    // Assign values to scalars (using convenience functions):
    setDoubleValue(retReal, 3.14);
    setIntValue(retInt, 7);
    setStringValue(retStr, "hello world");

    // Ready to construct the return list rl...
    list<pair<string,SEXP> > values;
    values.push_back(make_pair("retvec1", retvec1));
    values.push_back(make_pair("retvec2", retvec2));
    values.push_back(make_pair("myreal", retReal));
    values.push_back(make_pair("myint", retInt));
    values.push_back(make_pair("mystr", retStr));

    rl = makeReturnList(values, params);

    UNPROTECT(5); // must equal number of PROTECT's above.
    
BermudaSwaption provides an example where the first version of
makeReturnList is used, and DiscountCurve provides an example where
the second version is used (the function name is overloaded, and
the argument types determine what gets called).


