#include /include/license.stan
data {
   #include /include/data_guts.stan
   real alpha_meanlog10;
   real alpha_sdlog10;
   real beta_minlog10;
   real beta_maxlog10;
}
parameters {
    real kd_log10, hb_log10, alpha_log10, beta_log10 ;
}
transformed parameters{
    // Priors
    real kd, hb, alpha, beta ;
    // model GUTS
    vector[n_N] Damage;
    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;
    }
    alpha = 10^alpha_log10 ;
    beta  = 10^beta_log10 ;
    
    for (g in 1:n_group){
        for(i in GROUP_N[1,g]:GROUP_N[2,g]){
            
            Damage[i] = conc[i] * ( 1 - exp( - kd * time_N[i] ));
            real D_max = max(Damage[GROUP_N[1,g]:i]);
            real D_alpha = D_max^beta / ( D_max^beta + alpha^beta );
            real psurv_pred =  exp(-hb * time_N[i]) * (1 - D_alpha);
            
            Psurv_hat[i] = psurv_pred > 0 ? psurv_pred : 1e-10;
        }
        for(i in GROUP_N[1,g]:GROUP_N[2,g]){
          Conditional_Psurv_hat[i] =  i == GROUP_N[1,g] ? Psurv_hat[i] : Psurv_hat[i] / Psurv_hat[i-1] ;
        }
    }
}
model {
    // PRIORS
    target += normal_lpdf(kd_log10 | kd_meanlog10, kd_sdlog10);
    target += normal_lpdf(hb_log10 | hb_meanlog10, hb_sdlog10);
    target += normal_lpdf(alpha_log10 | alpha_meanlog10, alpha_sdlog10);
    target += uniform_lpdf(beta_log10 | beta_minlog10 , beta_maxlog10 );
    //
    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
}
