// Original strict-subset worksheet, 2026-10-20, GPL-3.0; see LICENSE and NOTICES.md.
// Coefficients: WHO anthro 1.1.0 and anthroplus 1.1.0, unmodified selected tables.
// PRIVATE ONLY. No official software parity or clinical interpretation is asserted.
const TABLES = __TABLES__;
const MODES = {underHeight:['growthstandards_lenanthro','WHO 2006 length/height-for-age','anthro 1.1.0',false,false],underBmi:['growthstandards_bmianthro','WHO 2006 BMI-for-age','anthro 1.1.0',false,true],olderHeight:['hfa_growth_standards','WHO 2007 height-for-age','anthroplus 1.1.0',true,false],olderBmi:['bfa_growth_standards','WHO 2007 BMI-for-age','anthroplus 1.1.0',true,true],underWeight:['growthstandards_weianthro','WHO 2006 weight-for-age','anthro 1.1.0',false,false],olderWeight:['wfa_growth_standards','WHO 2007 weight-for-age','anthroplus 1.1.0',true,false]};
function choice(x,allowed,label){if(typeof x!=='string'||!allowed.includes(x))throw Error(`Choose ${label}.`);return x;}
function measurement(x,label,maximum){
 if(typeof x!=='number'&&typeof x!=='string')throw Error(`Enter ${label}.`);
 const t=String(x);if(!/^(?:0|[1-9]\d*)(?:\.\d{1,12})?$/.test(t))throw Error(`Enter ${label} as a plain positive decimal with at most 12 decimal places.`);
 const n=Number(t);if(!Number.isFinite(n)||n<0.001||n>maximum)throw Error(`${label} must be between 0.001 and ${maximum}. These are worksheet safety limits.`);return n;
}
function calendarDay(s,label){
 if(typeof s!=='string'||!/^\d{4}-\d{2}-\d{2}$/.test(s))throw Error(`Enter ${label} as a complete ISO calendar date.`);
 const y=Number(s.slice(0,4)),m=Number(s.slice(5,7)),d=Number(s.slice(8,10));
 if(y<1||m<1||m>12||d<1||d>31)throw Error(`Enter a real ${label}.`);
 const dt=new Date(0);dt.setUTCHours(0,0,0,0);dt.setUTCFullYear(y,m-1,d);
 if(dt.getUTCFullYear()!==y||dt.getUTCMonth()!==m-1||dt.getUTCDate()!==d)throw Error(`Enter a real ${label}.`);return dt.getTime()/86400000;
}
// Round the actual finite binary64 value to hundredths, ties to even; no epsilon band.
function roundEven2(x){
 if(!Number.isFinite(x))throw Error('The score is not finite.');if(x===0)return 0;
 const buf=new ArrayBuffer(8),dv=new DataView(buf);dv.setFloat64(0,Math.abs(x));const bits=dv.getBigUint64(0),e=Number((bits>>52n)&2047n),f=bits&((1n<<52n)-1n);
 let num=(e?f+(1n<<52n):f)*100n,den=1n;const exp=(e?e-1023:1-1023)-52;
 if(exp>=0)num<<=BigInt(exp);else den<<=BigInt(-exp);
 let q=num/den;const r=num%den;if(2n*r>den||(2n*r===den&&q%2n===1n))q++;
 const z=Number(q)/100*(x<0?-1:1);return z===0?0:z;
}
function coefficient(mode,sex,days){
 const [key,,,older]=MODES[mode],start=older?60:0,rows=TABLES[key][Number(sex)-1];
 if(!older)return rows[days];
 const numerator=16*days,k=Math.floor(numerator/487),t=(numerator%487)/487,lo=rows[k-start],hi=rows[k+1-start];
 return lo.map((v,i)=>v+t*(hi[i]-v));
}
function scores(y,l,m,s,isBmi){
 const raw=l===1?(y-m)/(m*s):Math.expm1(l*Math.log(y/m))/(l*s);
 let final=raw,tail='Unadjusted LMS';
 if(isBmi&&(raw>3||raw< -3)){
  const cut=z=>m*Math.exp(Math.log1p(l*s*z)/l);
  if(raw>3){const c3=cut(3),spacing=c3-cut(2);final=3+(y-c3)/spacing;tail='Upper tail: positive 2-to-3 SD spacing';}
  else{const c3=cut(-3),spacing=cut(-2)-c3;final=-3+(y-c3)/spacing;tail='Lower tail: negative 2-to-3 SD spacing';}
 }
 if(!Number.isFinite(raw)||!Number.isFinite(final)||Math.abs(final)>1e12)throw Error('The computed score exceeds this worksheet\'s numerical safety range; no score is returned.');
 return {raw,final,rounded:roundEven2(final),tail};
}
const text=(label,value)=>({label,value:String(value)}),number=(label,value,unit='',digits=6)=>({label,value,unit,digits});
function legacyCalculate(slug,v){
 if(slug!=='who-growth-z-score')throw Error('Choose the WHO reference z-score worksheet.');
 if(!v||typeof v!=='object'||Array.isArray(v))throw Error('Enter one measurement record.');
 const mode=choice(v.mode,Object.keys(MODES),'a reference and indicator'),sex=choice(v.sex,['1','2'],'the recorded published sex table'),posture=choice(v.posture,['recumbent','standing'],'the recorded measurement posture');
 const [key,title,release,older,isBmi]=MODES[mode];
 const days=calendarDay(v.measurementDate,'measurement date')-calendarDay(v.birthDate,'date of birth');if(days<0)throw Error('Measurement date cannot be before date of birth.');
 const cm=measurement(v.cm,'Measured length or height (cm)',300);
 const rows=[text('Reference and indicator',title),text('Coefficient release',release),text('Coefficient table',key),text('Recorded sex table',sex==='1'?'Boys (published code 1)':'Girls (published code 2)'),number('Chronological elapsed days',days,'days',0),number('Fixed decimal age in months',16*days/487,'months',8),text('Age convention','Chronological dates only; one fixed reference month is 30.4375 days. No corrected or gestational age.'),number('Entered length or height',cm,'cm',8),text('Recorded posture',posture)];
 const unavailable=(domain,applicability,quality,reason)=>[...rows,text('Reference domain',domain),text('Applicability',applicability),text('Measurement quality',quality),text('Score availability',reason),text('Scope','No numeric score is available for this record. This is an arithmetic worksheet, not a clinical assessment.')];
 const inDomain=older?days>=1827&&days<=6970:days<=1826;
 if(!inDomain)return unavailable('Outside selected reference domain','Not evaluated','Not evaluated',older?'This release contract accepts chronological days 1827 through 6970 only.':'This release contract accepts chronological days 0 through 1826 only.');
 if(!older&&days<=273&&posture==='standing')return unavailable('Within selected domain','Not evaluated','Standing measurement unavailable below 9 fixed months','This strict subset requires a recumbent measurement at chronological days 0 through 273.');
 if(older&&posture!=='standing')return unavailable('Within selected domain','Not evaluated','Standing height required for this reference','No 0.7 cm adjustment is supplied for the older reference.');
 if(isBmi){const oedema=choice(v.oedema,['absent','present','unknown'],'the recorded oedema state');if(oedema!=='absent')return unavailable('Within selected domain',oedema==='present'?'BMI comparison unavailable: recorded oedema present':'BMI comparison unavailable: oedema status unknown','No score quality flag evaluated','BMI reference comparison requires explicitly recorded absence of oedema. This worksheet does not determine that status.');}
 const corrected=older?cm:cm+(days<731&&posture==='standing'?0.7:days>=731&&posture==='recumbent'?-0.7:0);
 if(!(corrected>0))throw Error('The posture adjustment would produce a nonpositive measurement. Check the recorded cm and posture.');
 const basis=older||days>=731?'Standing height':'Recumbent length';rows.push(number('Standardized length or height',corrected,'cm',8),text('Reference measurement basis',basis),text('Posture adjustment',corrected===cm?'None':corrected>cm?'Added 0.7 cm to standing measurement':'Subtracted 0.7 cm from recumbent measurement'));
 let y=corrected;if(isBmi){const kg=measurement(v.kg,'Measured weight (kg)',1000);y=kg/((corrected/100)**2);rows.push(number('Entered weight',kg,'kg',8),number('BMI from standardized measurement',y,'kg/m²',8));}
 const [l,m,s]=coefficient(mode,sex,days),score=scores(y,l,m,s,isBmi),threshold=isBmi?5:6,flag=Math.abs(score.rounded)>threshold;
 rows.push(text('Reference domain','Within selected domain'),text('Applicability',isBmi?'Recorded oedema absent; selected strict measurement subset':'Selected strict measurement subset'),text('Coefficient lookup',older?'Linear L/M/S interpolation by exact elapsed days / 30.4375; no score interpolation':'Exact chronological-day row; no interpolation'),number('L coefficient',l,'',10),number('M coefficient',m,'',10),number('S coefficient',s,'',10),number('Unadjusted LMS audit score',score.raw,'',10),text('Tail method',score.tail),number('Final unrounded audit score',score.final,'',10),number('Z-score (two decimals, ties to even)',score.rounded,'',2),number('Reference quality flag',flag?1:0,'',0),text('Measurement quality',flag?`Flagged: absolute rounded score exceeds ${threshold}; check the measurement record. This is not a diagnosis.`:`Not flagged by this reference check (absolute rounded score at most ${threshold}); this does not establish clinical validity.`),text('Score availability','Available within the stated arithmetic subset'),text('Scope','Z-score arithmetic only. No percentile, diagnosis, target, growth forecast, prematurity correction or WHO software parity is supplied. Private model awaiting independent review.'));
 for(const row of rows)if(typeof row.value==='number'&&!Number.isFinite(row.value))throw Error('A finite result could not be produced.');
 return rows;
}

// R5 original extension. Legacy four-mode scoreOnly returns the original rows exactly.
const WEIGHT_MODES=['underWeight','olderWeight'];
function newContext(v){
 const recorded=choice(v.recordedTableConfirmed,['unknown','confirmed'],'the recorded sex-table confirmation');
 const context=choice(v.referenceContext,['unknown','termChronological','preterm'],'the reference context');
 if(recorded!=='confirmed')return 'Published sex table has not been confirmed against the record.';
 if(context!=='termChronological')return context==='preterm'?'Prematurity-related comparisons are outside this worksheet.':'Term-birth chronological-age context is unknown.';
 return null;
}
// 41 terms n=0..40 inclusive; first omitted n=41. Compensated summation.
// For |z|<=3: truncation <=2.608e-25 and conservative binary64 allowance
// <1e-10 probability. The independent public oracle audits the selected budget.
function centralCDF(z){
 if(!Number.isFinite(z)||Math.abs(z)>3)throw Error('CDF input is outside the central reference range.');
 let term=z,sum=z,compensation=0;
 for(let n=1;n<=40;n++){
  term=-term*z*z*(2*n-1)/(2*n*(2*n+1));
  const adjusted=term-compensation,next=sum+adjusted;
  compensation=(next-sum)-adjusted;sum=next;
 }
 const probability=0.5+sum/Math.sqrt(2*Math.PI);
 if(!(probability>0&&probability<1))throw Error('A finite central percentile could not be produced.');
 return probability;
}
// Exact rational decimal arithmetic is used ONLY to certify L=1 height boundary
// membership. It does not replace any legacy floating-point score or flag.
const qadd=(a,b)=>[a[0]*b[1]+b[0]*a[1],a[1]*b[1]],
 qneg=a=>[-a[0],a[1]],qsub=(a,b)=>qadd(a,qneg(b)),qmul=(a,b)=>[a[0]*b[0],a[1]*b[1]],
 qscale=(a,n)=>[a[0]*BigInt(n),a[1]];
function decimalQ(token){
 const t=String(token),match=/^(-?)(\d+)(?:\.(\d+))?$/.exec(t);
 if(!match)throw Error('An exact coefficient token could not be read.');
 const frac=match[3]||'';return [(match[1]? -1n:1n)*BigInt(match[2]+frac),10n**BigInt(frac.length)];
}
function heightCentralMembership(mode,sex,days,v){
 const [key,,,older]=MODES[mode],rr=TABLES[key][Number(sex)-1];
 let m,s;
 if(older){
  const k=Math.floor(16*days/487),r=16*days-487*k;
  const blend=j=>qmul(qadd(qscale(decimalQ(rr[k-60][j]),487-r),qscale(decimalQ(rr[k+1-60][j]),r)),[1n,487n]);
  m=blend(1);s=blend(2);
 }else{m=decimalQ(rr[days][1]);s=decimalQ(rr[days][2]);}
 let y=decimalQ(v.cm);
 if(!older&&days<731&&v.posture==='standing')y=qadd(y,[7n,10n]);
 if(!older&&days>=731&&v.posture==='recumbent')y=qsub(y,[7n,10n]);
 const low=qsub(y,qmul(m,qsub([1n,1n],qscale(s,3)))),high=qsub(y,qmul(m,qadd([1n,1n],qscale(s,3))));
 if(low[0]<0n||high[0]>0n)return {inside:false,reason:'Unrounded base LMS score is outside −3 to +3.'};
 const delta=qsub(y,m),ms=qmul(m,s),numerator=delta[0]*ms[1],denominator=delta[1]*ms[0];
 // Quantize exact rational BASE z toward zero to14decimal places: decimal
 // error<1e-14; subsequent binary64 division adds<2.23e-16 (total<1.1e-14).
 // This is an independently computed LMS approximation, not clipping
 // an out-of-range value or rounding the score to its displayed hundredths.
 const preciseBase=Number(numerator*100000000000000n/denominator)/1e14;
 return {inside:true,exactBoundary:low[0]===0n?-3:high[0]===0n?3:null,preciseBase};
}
function percentileRows(v,mode,sex,days,basez){
 const reason=newContext(v);
 const unavailable=why=>[text('Percentile availability','Unavailable: '+why),text('Percentile scope','No percentile number is returned; any separately valid z-score is not a percentile.')];
 if(reason)return unavailable(reason);
 let z=basez;
 if(mode==='underHeight'||mode==='olderHeight'){
  const domain=heightCentralMembership(mode,sex,days,v);
  if(!domain.inside)return unavailable(domain.reason);
  z=domain.exactBoundary!==null?domain.exactBoundary:domain.preciseBase;
 }else{
  // This is an error enclosure, never an expanded domain. Ambiguous boundary
  // membership WITHHOLDS. No clipping or epsilon acceptance is performed.
  const error=1e-10,low=basez-error,high=basez+error;
  if(low>3||high< -3)return unavailable('Unrounded base LMS score is outside −3 to +3.');
  if(low< -3||high>3)return unavailable('Numerical boundary uncertainty at −3 or +3; central membership is not established.');
 }
 if(!Number.isFinite(z)||Math.abs(z)>3)return unavailable('Numerical boundary uncertainty; central membership is not established.');
 const p=100*centralCDF(z);
 return [number('Approximate reference percentile',p,'%',3),text('Percentile availability','Available within the central unrounded LMS range −3 to +3.'),text('Percentile definition','100 × normal CDF of the unrounded base LMS score; not a percentage of expected weight.'),text('Percentile precision','Approximate, three decimals. Combined numerical budget ≤0.00000002 percentage points; total display-error envelope ≤0.00050002 percentage points. This is not a clinical uncertainty interval.'),text('Percentile applicability','Confirmed published sex table; recorded term-birth chronological-age educational context.')];
}
function weightScores(y,l,m,s){
 const raw=l===0?Math.log(y/m)/s:l===1?(y-m)/(m*s):Math.expm1(l*Math.log(y/m))/(l*s);
 const cut=z=>l===0?m*Math.exp(s*z):m*Math.exp(Math.log1p(l*s*z)/l);
 let final=raw,tail='Unadjusted LMS';
 if(raw>3){const c3=cut(3);final=3+(y-c3)/(c3-cut(2));tail='Upper tail: positive 2-to-3 SD spacing';}
 if(raw< -3){const c3=cut(-3);final=-3+(y-c3)/(cut(-2)-c3);tail='Lower tail: negative 2-to-3 SD spacing';}
 if(!Number.isFinite(raw)||!Number.isFinite(final)||Math.abs(final)>1e12)throw Error('The computed score exceeds this worksheet\'s numerical safety range; no score is returned.');
 return {raw,final,rounded:roundEven2(final),tail};
}
function weightCalculate(v,comparison){
 const mode=v.mode,sex=choice(v.sex,['1','2'],'the recorded published sex table');
 const [key,title,release,older]=MODES[mode];
 const days=calendarDay(v.measurementDate,'measurement date')-calendarDay(v.birthDate,'date of birth');
 if(days<0)throw Error('Measurement date cannot be before date of birth.');
 const kg=measurement(v.kg,'Measured weight (kg)',1000),oedema=choice(v.oedema,['unknown','absent','present'],'the recorded oedema state');
 const rows=[text('Reference and indicator',title),text('Coefficient release',release),text('Coefficient table',key),text('Recorded sex table',sex==='1'?'Boys (published code 1)':'Girls (published code 2)'),number('Chronological elapsed days',days,'days',0),number('Fixed decimal age in months',16*days/487,'months',8),text('Age convention','Chronological dates only; one fixed reference month is 30.4375 days. No corrected or gestational age.'),number('Entered weight',kg,'kg',8),text('Reference measurement basis','Measured weight only; height and posture are not used.')];
 const unavailable=(why,domain='Within selected reference domain')=>[...rows,text('Reference domain',domain),text('Applicability',why),text('Measurement quality','No score quality flag evaluated'),text('Score availability','Unavailable: '+why),...(comparison==='scoreAndPercentile'?[text('Percentile availability','Unavailable: '+why)]:[]),text('Scope','No numeric new comparison is returned. Educational reference arithmetic, not diagnosis, target weight, growth forecast or prematurity assessment.')];
 if(!(older?days>=1827&&days<=3682:days<=1826))return unavailable(older?'This selected software reference accepts chronological days1827 through3682 only, not a calendar-birthday rule.':'This selected software reference accepts chronological days0 through1826 only.','Outside selected reference domain');
 const context=newContext(v);if(context)return unavailable(context);
 if(oedema!=='absent')return unavailable(oedema==='present'?'Weight comparison unavailable: recorded oedema present.':'Weight comparison unavailable: oedema status unknown.');
 const [l,m,s]=coefficient(mode,sex,days),score=weightScores(kg,l,m,s),flag=score.rounded< -6||score.rounded>5;
 rows.push(text('Reference domain','Within selected reference domain'),text('Applicability','Confirmed published table and term-birth chronological context; recorded oedema absent.'),text('Coefficient lookup',older?'Linear L/M/S interpolation by exact elapsed days / 30.4375; month121 is padding only.':'Exact chronological-day row; no interpolation'),number('L coefficient',l,'',10),number('M coefficient',m,'',10),number('S coefficient',s,'',10),number('Unadjusted LMS audit score',score.raw,'',10),text('Tail method',score.tail),number('Final unrounded audit score',score.final,'',10),number('Z-score (two decimals, ties to even)',score.rounded,'',2),number('Reference quality flag',flag?1:0,'',0),text('Measurement quality',flag?'Flagged: rounded score is below −6 or above +5; check the record. This is not a diagnosis.':'Not flagged by the rounded-score −6/+5 check; this does not establish clinical validity.'),text('Score availability','Available within the stated arithmetic subset'),text('Scope','Selected weight-for-age arithmetic only. No diagnosis, target weight, growth forecast, prematurity correction or official WHO software parity.'));
 if(comparison==='scoreAndPercentile')rows.push(...percentileRows(v,mode,sex,days,score.raw));
 return rows;
}
export function calculate(slug,v){
 if(slug!=='who-growth-z-score')throw Error('Choose the WHO reference z-score worksheet.');
 if(!v||typeof v!=='object'||Array.isArray(v))throw Error('Enter one measurement record.');
 const comparison=v.outputComparison===undefined?'scoreOnly':choice(v.outputComparison,['scoreOnly','scoreAndPercentile'],'an output comparison');
 if(WEIGHT_MODES.includes(v.mode))return weightCalculate(v,comparison);
 const original=legacyCalculate(slug,v);
 if(comparison==='scoreOnly')return original;
 const raw=original.find(row=>row.label==='Unadjusted LMS audit score');
 if(!raw)return [...original.map(row=>row.label==='Scope'?text('Scope','Selected reference arithmetic only; no percentile is available for this record. No diagnosis, target or forecast.'):row),text('Percentile availability','Unavailable: the selected measurement/reference comparison is unavailable.')];
 const days=original.find(row=>row.label==='Chronological elapsed days').value;
 const scoped=original.map(row=>row.label==='Scope'?text('Scope','Selected z-score and optional central-percentile arithmetic only. No diagnosis, target, growth forecast, prematurity correction or official WHO software parity.'):row);
 return [...scoped,...percentileRows(v,v.mode,v.sex,days,raw.value)];
}
