FMDetection:
ld a,($c000)
or $04 ; Disable I/O chip
out ($3E),a
ld bc $0700 ; Counter (7 -> b), plus 0 -> c
-: ld a,b
and %00000001 ; Mask to bit 0 only
out ($f2),a ; Output to the audio control port
ld e,a
in a,($f2) ; Read back
and %00000111 ; Mask to bits 0-2 only
cp e ; Check low 3 bits are the same as what was written
jr nz,+
inc c ; c = # of times the test was passed
+: djnz -
ld a,c
cp 7 ; Check test was passed 7 times out of 7
jr z,+
xor a ; If not, result is 0
+: and 1 ; If so, result is 1
out ($f2),a ; Output result to audio control port
ld (HasFM),a ; Store result in HasFM
ld a,($c000)
out ($3e),a ; Turn I/O chip back on
ret