 functions {
      real simplx_lpdf(real y, real mu, real si2) {
        return -.5*(log(2)+log(pi())+log(si2)+3*log(y)+3*log(1-y)) -1*(y-mu)^2/(2*si2*y*(1-y)*mu^2*(1-mu)^2);
      }
  }
data {
  int<lower=0> N;
  int<lower=0> nit;
  matrix[N,nit] z;
  int<lower=0> zero_inf[nit];
  int<lower=0> one_inf[nit];
  int<lower=0> n_zero;
  int<lower=0> n_one;
}
parameters {
  vector[N] theta;
  vector[nit] beta;
  vector[nit] ln_phi;
  vector[nit] ln_alpha;
  vector[n_zero] gamma0_star;
  vector[n_one] gamma1_star;
}
transformed parameters{
  vector<lower=0>[nit] alpha = exp(ln_alpha);
  vector<lower=0>[nit] phi = exp(ln_phi);

  vector[nit] gamma0;
  vector[nit] gamma1;
  for(i in 1:nit){
    if(zero_inf[i]==0) gamma0[i]=-10; #only needed as a lower bound for gamma1 (if only one inflation)
    if(zero_inf[i]!=0) gamma0[i]=gamma0_star[zero_inf[i]];
    if(one_inf[i]==0) gamma1[i]=10; #arbitrary, not used ;
    if(one_inf[i]!=0) gamma1[i]=gamma1_star[one_inf[i]];
  }
}
model {
  for(i in 1:nit){
    if(zero_inf[i]!=0) gamma0_star[zero_inf[i]]~normal(0,10);
    if(one_inf[i]!=0) gamma1_star[one_inf[i]]~normal(0,10)T[gamma0[i],];
  }
  beta~normal(0,10) ;
  ln_phi~normal(0,10);
  ln_alpha~normal(0,10);
  theta~normal(0,1);

  for(p in 1:N){
    for(i in 1:nit){
      real at=alpha[i]*theta[p];

      if(z[p,i]!=0 && z[p,i]!=1 && z[p,i]!=-999){

       if(zero_inf[i]!=0 && one_inf[i]!=0){
         real p1=inv_logit(gamma1[i]-at);
         real p0=inv_logit(gamma0[i]-at);
         target+=log(p1-p0);
       }
       if(zero_inf[i]!=0 && one_inf[i]==0){
         real p0=inv_logit(gamma0[i]-at);
         target+=log1m(p0);
       }
       if(zero_inf[i]==0 && one_inf[i]!=0){
         real p1=inv_logit(gamma1[i]-at);
         target+=log(p1);
       }

       target+=simplx_lpdf(z[p,i] | inv_logit(beta[i]+at) ,phi[i]);

      }
      else{
         if(z[p,i]==0){
            real p0=inv_logit(gamma0[i]-at);
            target+=log(p0);
         }
         if(z[p,i]==1){
            real p1=inv_logit(gamma1[i]-at);
            target+=log1m(p1);
         }
      }
    }
 }

}

