#processor 6502
#include "options.inc"

#if target & c128
host	= 128
#endif
#if target & c64
host	= 64
#endif
#if target & vic20
host	= 20
#endif

#if target & (c64 | c128)
#org $2000	;; C64 and C128
ackval	= 4
ack	= $dd00
data	= $dd01
ddr	= $dd03
strobe	= $dd0d
sample	= $d418
#endif

#if target & vic20
#org $2000	;; Vic-20
ackval	= $20
ack	= $911c
data	= $9110
ddr	= $9112
strobe	= $911d
sample	= $900e
#endif

#if target & (pet3001 | pet4001)
#org $2000	;; This does not actually work.
ackval	= 0
ack	= 0
data	= 0
ddr	= 0
strobe	= 0
sample	= 0
#endif

  sei
#if target & c128
  lda #$3e
  sta $ff00
#endif
#if (cable & (prlink | pc64)) * (target & vic20)
  lda #$ef
  and ack
  sta ack	; set CB1 to trigger on falling edge
#endif

loop:
#if cable & prlink
  lda #$10
0$:
  bit strobe    ; wait for handshaking
  beq 0$
#if target & vic20
  sta strobe
#endif
  lda #ackval
  eor ack
  ldx data      ; read the byte
  sta ack       ; acknowledge
  txa
#endif

#if cable & pc64
  lda #$10
0$:
  bit strobe    ; wait for handshaking
  beq 0$
#if target & vic20
  sta strobe
#endif
  lda ack
  tax
  and #255 - ackval
  sta ack
  lda #$10
1$:
  bit strobe
  beq 1$
#if target & vic20
  sta strobe
#endif
  lda data
  stx ack
#endif

#if cable & c64net
  lda #8
0$:
  bit data	; initial handshaking
  beq 0$
  ldx data	; get the high nybble
  sta data	; acknowledge (place 0 on PB2)
1$:
  bit data	; wait for acknowledgement
  bne 1$
  lda #4
  sta data	; acknowledge
  txa
#endif

  lsr
  lsr
  lsr
  lsr
  sta sample
  jmp loop
