#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double PseudoLikelihood(NumericMatrix x, NumericMatrix graph, NumericVector thresholds, double beta, NumericVector responses, bool logis){
  int n = x.nrow();
  int k = x.ncol();

  double logPS = 0;
  double e = 0;

  // for every response, compute log PL and sum:
  for (int i=0;i<n;i++){
    // for every node, compute log PL and sum:
    for (int j=0;j<k;j++){
      e=thresholds[j];
      for (int jj=0;jj<k;jj++){
        e += x(i,jj) * graph(j, jj);
      }
      // Apply the inverse temperature beta and compute the log-sum-exp
      // normalizer with a max-shift for numerical stability:
      double a = beta * responses[0] * e;
      double b = beta * responses[1] * e;
      double m = (a > b) ? a : b;
      logPS += beta * x(i,j) * e  -  (m + log(exp(a - m) + exp(b - m)));
    }
  }
  
  if (!logis){
    return(exp(logPS));
  } else {
     return(logPS); 
  }
}
