// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
#include <stdarg.h>
#include "econ.h"

// LINPACK routines
extern "C" void dqrdc(double *x,int *ldx,int *n,int *p,
                      double *qraux,int *jpvt,double *work,int *job);
extern "C" void dqrsl(double *x,int *ldx,int *n,int *k,
                      double *qraux,double *y,double *qy,double *qty,
                      double *b,double *rsd,double *xb,int *job,int *info);

// generate matrix from time-series
void matrixgen(mx res,int n,va_list ptr)
{
   int i,j;
   ts wrk;
   for (j=0;j<n;j++) {
      wrk = va_arg(ptr,ts);
      res.r=wrk.n;
      for (i=0;i<res.r;i++) res.x[res.c*res.r+i]=wrk.x[i];
      res.c=res.c+1;
      };
   return;
}

// time-series -> matrix
mx matrix(int n,...)
{
   va_list ptr;
   mx tmp;
   va_start(ptr,n);
   matrixgen(tmp,n,ptr);
   va_end(ptr);
   return tmp;
}

// least squares
void lsq(ts y,int n,...)
{
   va_list ptr;
   mx x;
   va_start(ptr,n);
   matrixgen(x,n,ptr);
   va_end(ptr);
   int r = row(x);
   int c = col(x);
   double qraux[MAX_MX_DIM];
   int jpvt[MAX_MX_DIM];
   double work[MAX_MX_DIM];
   int job = 0;
   if (r<c) "Fatal error in lsq-procedure : zero DF\n";
   dqrdc(data(x),(int *)&r,(int *)&r,(int *)&c,
         (double *)&qraux,(int *)&jpvt,(double *)&work,(int *)&job);
   double qy[MAX_MX_DIM];
   double qty[MAX_MX_DIM];
   double b[MAX_MX_DIM];
   double rsd[MAX_MX_DIM];
   double xb[MAX_MX_DIM];
   job = 110;
   int info;
   dqrsl(data(x),(int *)&r,(int *)&r,(int *)&c,
        (double *)&qraux,data(y),(double *)&qy,(double *)&qty,
        (double *)&b,(double *)&rsd,(double *)&xb,
        (int *)&job,(int *)&info);
   if (info==0) {
      cout << "Regression results\n";
      cout << "==================\n";
      cout << "coefficient     estimated value\n";
      for (int i=0;i<c;i++) cout << "     " << (i+1) << "            " <<
                                    b[i] << "\n";
   } else {
      cout << "Fatal error in lsq-procedure : singular matrix\n";
   };
}
