'======================
'CASE INSENSITIVE INSTR
'======================


basic


'---------------------------------------------------------------------------
function instrci(byval i as sys, byval s0 as bstr, byval w0 as bstr ) as sys
'===========================================================================
  #noinit
  dim as sys j
  'asm
  mov eax,[i]
  dec eax
  cmp eax,0
  jl fwd xinstr   'invalid offset
  mov [j],eax
  mov edi,[s0]    'main string
  cmp edi,0
  jz xinstr       'empty string
  mov edx,[w0]    'keyword
  cmp edx,0
  jz xinstr       'empty keyword
  mov ecx,[edx-4] 'length of keyword
  '
  mov esi,edi
  add esi,[edi-4] 'main string boundary
  sub esi,ecx     'minus length of keyword
  mov eax,esi     'search limit
  sub eax,[j]     'offset
  cmp eax,edi     '
  jl xinstr       'no room for keyword
  '
  add edi,[j]     'set offset
  '
  trinstr1:
  '--------
  '
  mov ah,[edx]
  or ah,32
  '
  trinstr2:
  '-------
    cmp edi,esi   'boundary check
    jg xinstr
    mov al,[edi]
    or al,32
    inc edi       'pre inc
    cmp al,ah
    jnz trinstr2  'prelim check against keyword first letter
    '
    push edi
    push edx
    push ecx
    dec edi
    rinstr:
    '------
      dec ecx     'downcount
      jl  ninstr  'match complete
      '
      'case insensitive compare
      '
      mov al,[edi]
      mov ah,[edx]
      cmp al,ah
      jz nconv3
      cmp al,65
      jb nminstr
      cmp ah,65
      jb nminstr
      cmp al,90
      ja nconv1
      or al,32
      nconv1:
      cmp ah,90
      ja nconv2
      or ah,32
      nconv2:
      cmp al,ah
      jnz nminstr
      '
      nconv3:
      inc edx
      inc edi
    jmp rinstr
    '
  nminstr: 'no match
  pop ecx
  pop edx
  pop edi
  jmp trinstr1 'carry on searching
  '
  ninstr: 'done
  '------------
  pop ecx
  pop edx
  pop edi
  sub edi,[s0]
  mov function,edi
  '
  xinstr: 'exit
  '------------
  'end asm
exit function

end function


'=======
testing:
'=======


print instrci(2,"Hello World. Hello Sky!","Hello Sky")
print instrci(2,"Hello World. hELLO Sky!","Hello SKY")
