```/* G02AA_T1W_F C++ Header Example Program.
*
* Copyright 2019 Numerical Algorithms Group.
* Mark 27, 2019.
*/

#include <nag.h>
#include <dco.hpp>
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <string>
using namespace std;

typedef double DCO_BASE_TYPE;
typedef dco::gt1s<DCO_BASE_TYPE> DCO_MODE;
typedef DCO_MODE::type DCO_TYPE;

int main(void)
{
/* Integer scalar and array declarations */
Integer exit_status = 0;

cout << "G02AA_T1W_F C++ Example Program Results\n\n";

Integer ifail = 0;

// Skip heading in data file
string mystr;
getline (cin, mystr);

Integer n;
cin >> n;
Integer pdg = n;
Integer pdx = n;

// Allocate arrays
DCO_TYPE *g = 0, *x = 0, *g_in = 0;
double   *xr = 0, *dxdg = 0;
g    = new DCO_TYPE [n * n];
g_in = new DCO_TYPE [n * n];
x    = new DCO_TYPE [n * n];
xr   = new double [n * n];
dxdg = new double [n * n];

// Read in matrix G */
double   tmp;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j){
cin >> tmp;
g_in[i+j*n] = tmp;
}
}

// Set up method parameters
DCO_TYPE errtol = 1.00e-7;
Integer  maxits = 200;
Integer  maxit = 10;

for (int i = 0; i < n * n; i ++) {
// g_in[i].tangent = 0.0;
dco::derivative(g_in[i]) = 0.0;
g[i] = g_in[i];
}

cout.setf(ios::scientific,ios::floatfield);
cout.precision(3);

// Output variables
Integer  iter, feval;
DCO_TYPE nrmgrd;
NagError fail;
INIT_FAIL(fail);
for (int k = 0; k < n; k ++) {
for (int l = 0; l < n; l ++) {

// g[k+l*n].tangent = 1.0;
dco::derivative(g[k+l*n]) = 1.0;
g02aa_t1w_f_(ad_handle, g, pdg, n, errtol, maxits, maxit, x, pdx,
iter, feval, nrmgrd, ifail);
if (ifail != 0) {
cout << "Error from G02AA_T1W_F. Returned with ifail = ";
cout << ifail << "\n";
exit_status = 1;
goto END;
}
if ( k == 0 &&  l == 0) {
for (int i = 0; i < n*n; ++i) {
xr[i] = dco::value(x[i]);
}
x04cac(Nag_ColMajor,Nag_GeneralMatrix,Nag_NonUnitDiag,n,n,xr,n,
"     Nearest Correlation Matrix",0,&fail);

cout << "\n\n Number of Newton steps taken  : " << iter << "\n";
cout <<     " Number of function evaluations:" << feval << "\n";
if (nrmgrd > errtol) {
cout << " Norm of gradient of last Newton step: ";
cout.width(12);
// cout << nrmgrd.value << "\n";
cout << dco::value(nrmgrd) << "\n";
}
}
double dx = 0.0;
for (int i = 0; i < n*n; i++) {
// dx += x[i].tangent;
dx += dco::derivative(x[i]);
}
dxdg[k+l*n] = dx;

for (int i = 0; i < n * n; i ++) {
g[i] = g_in[i];
}
}
}

cout << "\n\n";
x04cac(Nag_ColMajor,Nag_GeneralMatrix,Nag_NonUnitDiag,n,n,dxdg,n,
"   (1,...,1)^T * dX/dG",0,&fail);

END:

// Remove computational data object