% estimate.m: estimates a static logit model of retirement decisions
%             John Rust, Georgetown University  November 2012

  setup;

  global data;

  load('data');

  if (theta_init);

    load('theta_estimated');

    theta=theta_estimated;

    fprintf('loading theta_estimated as the starting values of theta for estimation\n');

  end;

  illf=-lfeval(theta);


  if (optimizer == 1);

  fprintf('using unconstrained quasi newton optimizer, fminunc\n');
  [theta_estimated,nllf]=fminunc(@lfeval,theta);

  elseif (optimizer == 3);

  optimset('GradObj','on');
  fprintf('using constrained quasi newton optimizer, fmincon\n');
  [theta_estimated,nllf]=fmincon(@lfeval,theta,[],[],[],[],theta_lb,theta_ub);

  else;

  optimset('GradObj','on');
  fprintf('using non-smooth function optimizer, fminsearch\n');
  [theta_estimated,nllf]=fminsearch(@lfeval,theta);

  end;

  fprintf('Estimation converged, initial likelihood: %g final likelihood: %g\n',illf,-nllf);

  load('theta_true');
  fprintf('estimated vs true parameters\n');
  [theta_estimated theta_true]

  save('theta_estimated','theta_estimated');

  im=information_matrix(theta_estimated);

  chisq=(theta_estimated-theta_true)'*inv(im)*(theta_estimated-theta_true);

  fprintf('Chi-squared (Wald) test that estimated theta equal true values: %g  marginal significance level: %g\n',chisq,cdf('chi2',chisq,size(theta_true,1)));
