%lfeval.m: evaluates the (negative of) log-likelihood function for the data

   function [llfv,dllfv]=lfeval(theta);

     global work_disutility_age search_cost_age lsigma u_scale crra_coef data Npeople firstage lastage;

     work_disutility_age=theta(1);
     search_cost_age=theta(2);
%     u_scale=theta(3);
     crra_coef=theta(3);
     llfv=0;
     dllfv=zeros(3,1);

     for i=1:Npeople;

      for age=firstage:lastage;

        indx=(i-1)*(lastage-firstage+1)+age-firstage+1;

        pindex=data(indx,1);
        d=data(indx,2);
        emp_state=data(indx,3);
        age=data(indx,4);
        income=data(indx,5);
        pension=data(indx,6);
     
        [uw,duw]=uf(age,income,pension,emp_state,1);
        [unw,dunw]=uf(age,income,pension,emp_state,0);

        %if (i<=2);
        %  fprintf('i=%i pindex=%i indx=%i\n',i,pindex,indx);
        %end;

        mu=max(uw,unw);
     
        euw=exp(uw-mu);
        eunw=exp(unw-mu);

        prob=euw/(euw+eunw);

        ap=(d*prob+(1-d)*(1-prob)); 
        llfv=llfv+log(ap); 

        dllfv=dllfv+((2*d-1)*prob*(1-prob)*(duw-dunw))/ap;

      end;

     end;
%fprintf('wda=%g sca=%g u_scale=%g crra_coef=%g llf=%g\n',work_disutility_age,search_cost_age,u_scale,crra_coef,llfv);
     
     llfv=-llfv; 
     dllfv=-dllfv;
