// The easiest way to pull in all necessary definitions is to include oct.h
#include <octave/oct.h>
// Overwrite type names duplicated in Octave and NAG header files
#define Complex NagComplex
#define MatrixType NagMatrixType
// and include the appropriate NAG header files
#include <nag_engine.h>

// The third parameter (nargout) is not used, so it is
// omitted from the list of arguments to DEFUN_DLD in order to avoid
// the warning from gcc about an unused function parameter. 
DEFUN_DLD (nag_tsa, args, ,
  "Calls G13AAF, which carries out non-seasonal \n\
and seasonal differencing on a time series.\n")
{
  // Variable to store function output values
  octave_value_list retval;
  int nargin = args.length ();
  if (nargin != 5)
    {
      error ("Insufficient input arguments.");
    }
  else
    {
      // Retrieve input arguments from args
      NDArray x = args(0).array_value();
      Integer nx = args(1).int_value();
      Integer nd = args(2).int_value();
      Integer nds = args(3).int_value();
      Integer ns = args(4).int_value();
      if (! error_state)
        {
          // Declare local variables
          Integer nxd, ifail;
          dim_vector dv(1); dv(0)=nx;
          NDArray xd(dv);
          
          // Call NAG routine
          ifail = -1;
          g13aaf_(x.fortran_vec(),nx,nd,nds,ns,xd.fortran_vec(),nxd,ifail);
          
          if (ifail!=0)
            {
              error ("G13AAF ifail = %ld\n",ifail);
              goto END;
            }
          // Assign output arguments to retval      
          retval(0) = xd;
          retval(1) = nxd;
          retval(2) = ifail;
        }
    }

 END:
  return retval;
}
