#include <TMB.hpp>

template<class Type>
Type objective_function<Type>::operator() ()
{
  DATA_VECTOR(rec);
  DATA_VECTOR(ssb);
  DATA_VECTOR(knots);
  PARAMETER(logSdSpline);
  PARAMETER(logSdObs);
  PARAMETER_VECTOR(lambda);

  int noObs=rec.size();
  int noKnots=knots.size();
  Type sdSpline=exp(logSdSpline);
  Type sdObs=exp(logSdObs);
  vector<Type> lambda_dec(noKnots);

  Type ans=Type(0.0);
  for(int i=2;i<noKnots;i++){    
    ans+=-dnorm(lambda(i),lambda(i-1),sdSpline,true);
  }

  lambda_dec(0)=lambda(0);
  for(int i=1; i<noKnots; ++i){
    lambda_dec(i)=lambda_dec(i-1)-exp(lambda(i));
  }

  using namespace tmbutils;
  splinefun<Type> sp(knots,lambda_dec,3); 

  for(int i=0;i<noObs;i++){
    ans+=-dnorm(log(rec(i)),sp(ssb(i))+log(ssb(i)),sdObs,true); 
  } 

  ADREPORT(lambda_dec);
  return ans;
}
