#define main historical_tests_main
#include "test_drill_smo.c"
#undef main
static double sat_ref(double x){return x>1?1:x < -1?-1:x;}
int main(void){
 unsigned cases=0;double maxerror=0;
 for(unsigned k=0;k<1000;++k){
  drill_smo_config c=config();c.max_dt_s=0.0001f;
  drill_smo_state s;assert(drill_smo_init(&s,&c));
  const float old=-2.0f+4.0f*(float)(k%29)/28.0f;
  const float measured=-1.0f+2.0f*(float)(k%31)/30.0f;
  const float voltage=-7.0f+14.0f*(float)(k%37)/36.0f;
  const float dts[]={0.00001f,0.00005f,0.0001f};const float dt=dts[k%3];
  s.estimated_current_alpha_a=old;
  drill_smo_input i={.voltage_alpha_v=voltage,.current_alpha_a=measured,.dt_s=dt,.commanded_direction=1};drill_smo_output o;
  assert(drill_smo_step(&s,&i,&o));
  /* Independent double bisection of the implicit circuit equation; no
   * production closed-form branch selection copied into the reference. */
  double lo=-100,hi=100;
  for(unsigned n=0;n<100;++n){
   double x=(lo+hi)/2;
   double residual=(double)c.phase_inductance_h/(double)dt*(x-(double)old)-(double)voltage+(double)c.phase_resistance_ohm*x+(double)c.sliding_gain_v*sat_ref((x-(double)measured)/(double)c.current_error_sat_a);
   if(residual>0)hi=x;else lo=x;
  }
  double error=fabs((double)s.estimated_current_alpha_a-(lo+hi)/2);if(error>maxerror)maxerror=error;
  assert(error<0.000001);++cases;
 }
 printf("A97_IMPLICIT_ROOT_PASS cases=%u max_abs_current_error_A=%.12g\n",cases,maxerror);return 0;
}
