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+=normal_lpdf(z[p,i] | beta[i]+at,sqrt(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);
           }
         }
     }
     }
}

