/* vim: set expandtab shiftwidth=2 softtabstop=2 tw=70: */

#include <Rcpp.h>
using namespace Rcpp;

// Cross-reference work:
// 1. update ../src/registerDynamicSymbol.c with an item for this
// 2. main code should use the autogenerated wrapper in ../R/RcppExports.R
//
// [[Rcpp::export]]
NumericVector do_oce_convolve(NumericVector x, NumericVector f,
                              NumericVector end) {
  int endflag = floor(0.5 + end[0]);
  int nx = x.size();
  int nf = f.size();
  int i, ij, j;
  NumericVector res(nx);
  // do not look past the start of x
  // Just copy x, until we get to the point where the filter will fit
  if (endflag == 0) {
    for (i = 0; i < nf; i++)
      res[i] = 0.0;
    for (i = nf; i < nx; i++) {
      res[i] = 0.0;
      for (j = 0; j < nf; j++) {
        res[i] += f[j] * x[i - j];
      }
    }

  } else if (endflag == 1) {
    for (i = 0; i < nf; i++)
      res[i] = x[i];
    for (i = nf; i < nx; i++) {
      res[i] = 0.0;
      for (j = 0; j < nf; j++) {
        res[i] += f[j] * x[i - j];
      }
    }

  } else if (endflag == 2) {
    for (i = nf; i < nx; i++) {
      res[i] = 0.0;
      for (j = 0; j < nf; j++) {
        ij = i - j;
        if (ij >= 0)
          res[i] += f[j] * x[ij];
      }
    }
  } else {
    Rcpp::stop("'end' must be 0, 1, or 2");
  }
  for (i = 0; i < nf; i++)
    res[i] = x[i];
  for (i = nf; i < nx; i++) {
    res[i] = 0.0;
    for (j = 0; j < nf; j++) {
      res[i] += f[j] * x[i - j];
    }
  }
  return (res);
}
