      .include #stddef
      .include #system
      .include #cio
      .include #os
      .include #handler.h65
            
      .zext    _tmp1      
      .zext    _tmp2
      .zext    _tmp3
            

install:
      bput     0,:header,:headerend-:header
      getc     0
      sta      theirid
      print    0
      
      lda      #$60           ; an RTS
:loop
      cmp      $E500,y
:osmsb   =     *-1      
      beq      :found
      iny
      bne      :loop
      inc      :osmsb
      bne      :loop
      
      print    0,"Your ROMS are fucked up"
      rts

:fault
      print    0,"Target handler not found"
      rts
      
:found
      tya
      bne      :ok2
      dec      :osmsb
:ok2      
      dey
      sty      osrts
      move     :osmsb,osrts+1
      
      lda      theirid
      jsr      fhatabs
      bcc      :fault
      bne      :fault
      iny
      lda      HATABS,y
      sta      _tmp1
      lda      HATABS+1,y
      sta      _tmp1+1
      dpoke_y  HATABS,ourtab
      
      ldy      #0
      dpoke    _tmp3,theirtab
      lda      #<theirtab
      cmp      #$F4
      bcc      :ok

      .macro   fix
         lda   #>%1
         ldx   #<%1
         jsr   :fixup
      .endm
      
      fix      fix1
      fix      fix2
      fix      fix3
      fix      fix4
      fix      fix5
      fix      fix6
      fix      _tmp3
      
:ok
      ldx      #6
      clc
:copy
      lda      (_tmp1),y
      adc      #1
      sta      (_tmp3),y
      iny
      lda      (_tmp1),y
      adc      #0
      sta      (_tmp3),y
      iny
      dex
      bne      :copy
      
      lda      (_tmp1),y
      sta      (_tmp3),y
      iny
      lda      (_tmp1),y
      sta      (_tmp3),y
      iny
      lda      (_tmp1),y
      sta      (_tmp3),y

      dpoke    MEMLO,install
      print    0,"Snooper successfully installed"
      rts
      

:fixup
      stx      _tmp2
      sta      _tmp2+1
      lda      (_tmp2),y
      clc
      adc      #15
      sta      (_tmp2),y
      iny
      lda      (_tmp2),y
      adc      #0
      sta      (_tmp2),y
      dey
      rts
            
theirid:
      .byte    'D
      
      
:header
      .byte    "The HANDLER snooper by Natuerlich!",155
      .byte    "developed with NASM! 1991 for NASTY",155
      .byte    "Displays some info during CIO calls",155,155
      .byte    "OPTION - to single step",155
      .byte    "START  - to run",155
      .byte    "RESET  - to deinstall",155,155
      .byte    "CIO device ID to snoop ? > "
:headerend      
