#include /include/license.stan
data {
   #include /include/data_guts.stan
   real kk_meanlog10;
   real kk_sdlog10;
   real z_meanlog10;
   real z_sdlog10;
}
parameters {
    real kd_log10, hb_log10, kk_log10, z_log10 ;
}
transformed parameters{
    // Priors
    real kd, hb, kk, z ;
    // model GUTS
    vector<lower=0, upper=1>[n_N] Psurv_hat;
    vector<lower=0, upper=1>[n_N] Conditional_Psurv_hat;
    
    kd = 10^kd_log10 ;
    if(HB_FIXED == 0){
        hb = 10^hb_log10 ;
    } else{
        hb = hb_value;
    }
    kk = 10^kk_log10 ;
    z  = 10^z_log10 ;
    
    for (g in 1:n_group){
        array[GROUP_N[3,g]] real ts ;
        vector[GROUP_X[3,g]] exposure_t ;
        vector[GROUP_X[3,g]] exposure_v ;
        //
        for(i in GROUP_N[1,g]:GROUP_N[2,g]){
            real xcor = conc[i] > 0 ? conc[i] : 10 ;
            real R = conc[i] > z ? z/xcor : 0.1 ;
            real tz = conc[i] > z ? -1/kd * log( 1 - R) : 1e9 ;
            real tprec = i == GROUP_N[1,g] ? time_N[i] : time_N[i-1];
            real tref = max([tprec, tz]) ;
            
            real Psurv_2 = time_N[i] > tz ? -kk * ((conc[i] - z) * (time_N[i] - tref) +
                conc[i]/kd * ( exp(-kd * time_N[i]) - exp(-kd * tref))) :  0 ;
            
            Psurv_hat[i] = exp(-hb * (time_N[i] - tprec) + Psurv_2) ;
            // 0 < psurv < 1
            Psurv_hat[i] = Psurv_hat[i] > 1-1e-10 ? 1-1e-10 : Psurv_hat[i] ;
            Psurv_hat[i] = Psurv_hat[i] < 1e-10 ? 1e-10 : Psurv_hat[i] ;
            // 0 < psurv < 1
            Conditional_Psurv_hat[i] =  i == GROUP_N[1,g] ? Psurv_hat[i] : Psurv_hat[i] / Psurv_hat[i-1] ;
            Conditional_Psurv_hat[i] = Conditional_Psurv_hat[i] > 1-1e-10 ? 1-1e-10 : Conditional_Psurv_hat[i] ;
            Conditional_Psurv_hat[i] = Conditional_Psurv_hat[i] < 1e-10 ? 1e-10 : Conditional_Psurv_hat[i] ;
        }
    }
}
model {
    // PRIORS
    target += normal_lpdf(kd_log10 | kd_meanlog10, kd_sdlog10);
    target += normal_lpdf(hb_log10 | hb_meanlog10, hb_sdlog10);
    target += normal_lpdf(kk_log10 | kk_meanlog10, kk_sdlog10);
    target += normal_lpdf(z_log10  |  z_meanlog10,  z_sdlog10);
    //
    for (g in 1:n_group){
      target += binomial_lpmf(
          Nsurv[GROUP_N[1,g]:GROUP_N[2,g]] | 
          Nprec[GROUP_N[1,g]:GROUP_N[2,g]], 
          Conditional_Psurv_hat[GROUP_N[1,g]:GROUP_N[2,g]]
        );
    }
}
generated quantities {
  #include /include/generated_quantities.stan
}
