/* *************************************************
   design:
   D_it = 1 for m_it > b0+b1*s_it
            or  m_it < b0-b2*s_it
	    where p(th_i | Y_t) ~ [m_it, s_it]
   d_it = argmax_{0,3} {E u(d_it,D_it=1,th) | Y_t}
 ************************************************* */	          

struct design 
{
  int kini; // number of initial treatments
  double b0, // intercept of decision boundaries
          b1, // slope of upper dec boundary
          b2, // lower deciscion boundary
      s0,      /* lower bound on log(s.d.) */
      s1;     // b1&b2 are the value of the decision boundaries at sd=s1
  double U,pB,n3,nreco,nrej,ntoreco,dt,mse;   // approx U(b0,b1,b2)
  int errI, errII, term, ngood, nbad;
  int ***ngoodgrid, ***nbadgrid;
  double *b0grid,  // grid on b0,b1,b2
    *b1grid,
    *b2grid,
    ***Ugrid,
    ***pBgrid,
    ***nrecogrid,
    ***nrejgrid,
    ***ntorecogrid,
    ***n3grid,
    ***dtgrid,
    ***errIgrid,
    ***errIIgrid,
    ***msegrid;      // approx U(b0,b1,b2) over grid
  int nb0,nb1,nb2; // grid sizes
  double c0,c1,c2; // coefficients for utility
  int uth,hyper,pool,logsd,patlimit;     
  double 
    a,za,
    b,zb,
    p0;
};

struct mcpars
{
  int 
    nsim,   // MC sample size for forward simulation
      nt;     // n periods
  double
    *pk;      // prob pk(j) = Pr(k[t+1]-k[t] = j)
  int
    Npk;
};

/* *************************************************
   
MODEL:
   y_it | th_i ~ Bin(k, th_i)
   th_i        ~ Be(u,v)
   u ~ Ga(au,bu)
   v ~ Ga(av,bv)

DECISIONS:
   D_it = I(stop treatment i at time t)
   d_it = 0         stop & abandon
        = 3         stop & phase 3

UTILITY:
   u(d_it = 0, D=1, th) = 0
   u(d_it = 3, D=1, th) = C3*Pr(A | Y_t) - c*n3(Y_t) - c0

 ************************************************* */

struct parameter
{
  double 
     *th,	// th_i = Pr(y_{it}=1)
    u,v,	// hyperprior pars
    au,bu,
    av,bv;
};

struct ergodic  // not currently used (for MCMC post sim)
{
  double
    *mth,	// E(th_i | Y_t)
    *sth;	// SD(th_i | Y_t)
  int
    *n;         // n updates of mth and sth
};

struct data 
{
  int N,	         // batch size,
    k,           // n trtments
    kmax,        // max k
    *t0,*t1;	 // first and last period for trt i
};



void init();
void init_read();
void init_pars();
void init_memalloc();

void dsg_forw(int on_grid);
void Uhat_init(int on_grid);
void Uhat_scale(int on_grid);
void Uhat_traj(double **M, double **S, int kmax, int i, FILE *trajfile);
void Uhat_b(double m,double logs,double weight, double th,double *U,double *pB,double *n,double *nreco,int *errI,int *errII,int *term,double b0,double b1,double b2);
void Uhat_write(int on_grid);
double uobs(double m, double s, double *pB, int *N3, double th, int *term);
int n2(double m, double s);


