#include <Rcpp.h>

using namespace Rcpp ;
// [[Rcpp::export]]
SEXP findRecency(NumericMatrix cooccur_matrix, int na_allowed){
  int days = cooccur_matrix.ncol();
  int num_pairs = cooccur_matrix.nrow();
  int contact_check;                            // flag to check whether contact has occurred for that row
  int recency_counter;                          // counts intervening days to calculate recency
  NumericVector contacts(days);                  // number of observations of each recency in which there is a contact
  NumericVector observations(days);             // number of observations of each recency

  for(int i = 0; i < num_pairs; i++) {          // for each pair
    int contact_check = 0;                      //  reset contact check for new pair
    int recency_counter = 0;                    //  reset recency counter
    int na_counter = 0;                         // reset NA counter
    for(int j = 0; j < days; j++) {             //  for each day
      if(!R_IsNA(cooccur_matrix(i, j)) | na_counter <= na_allowed) {           //   if the element is not NA or if the NA counter is less than the number of NAs allowed
        if(contact_check == 0) {                //    if contact has not occurred before
          if(cooccur_matrix(i, j) == 1) {       //     if current observation is a contact
            contact_check = 1;                  //      assign contact check flag to signal that this pair has had previous contact
          }
        } else {                                //    if contact has occurred before
          observations[recency_counter]++;      //     incremement number of observations for appropriate recency
          if(cooccur_matrix(i, j) == 1) {       //     if current observation is a contact
            contacts[recency_counter]++;         //      increment number of instances for appropriate recency
            recency_counter = 0;                //      reset recency counter
          } else {                              //     if the current observation is not a contact
            recency_counter++;                  //      increment recency counter
          }
        }
      } else {                                  //   if the element is NA
        na_counter++;
        recency_counter = 0;                    //    reset recency counter
        contact_check = 0;                    //    reset recency counter
      }
    }
  }
  return Rcpp::List::create(Rcpp::Named("rec_contacts") = contacts, Rcpp::Named("rec_observations") = observations);
}

