; Math init (just detects for 80387)

;ret : EAX=ERROR 80387 not detected!
;      EAX=0 80387 detected!

ERROR equ -1

.data
  ctrlword dw ?

.code
math_init proc private
  ;8087 detection
  fninit
  fnstcw ctrlword
  wait
  mov ax,ctrlword
  cmp ah,3
  jz ok1
    mov eax,ERROR  ;8087 not detected!
    ret
ok1:
  ;80387 detection
  and ctrlword,0ff7fh  ;turn on FPU ints
  fldcw ctrlword       ; by loading new cw
  fdisi                ;disable ints (works on 8087 only)
  fstcw ctrlword
  wait
  mov ax,ctrlword
  test ax,80h
  jz ok2
    ;only a 8087 was detected (or 287)
    mov eax,ERROR
    ret
ok2:
  finit
  fld1
  fldz
  fdiv     ;infinity
  fld st   ;generate negative infinity by pushing current stack
  fchs     ; and change sign
  fcompp   ;compare 2 infinities  ;equal for 87/287  NOT for 387
  fstsw ax
  wait
  and ah,40h ;mask C3 (of FPU status word)
  jz ok3     ;if zero, then must be 80387           
    mov eax,ERROR  ;287 ??
    ret
ok3:
  finit
  xor eax,eax  ;80387 detected !!!
  ret
math_init endp

