; original implemenation by Jeffrey Altman <jaltman@mit.edu>
;
; SearchPath  (path, filename)
; input:
;    top of stack is the filename
;    top of stack minus one is the path
; output:
;    top of stack is a fully qualified path or the number "0" 
;
; Usage:
;    Push "semicolon delimited path"
;    Push "filename"
;    Call SearchPath
;    Pop  $R0 ; fqpn 
;    IntCmp $R0 0 failed
;   
;
Function SearchPath
  Exch $R0  ; input - filename
  Exch 
  Exch $R1  ; input - semicolon delimited path
  Push $R3  ; worker - index to current end character
  Push $R4  ; worker - length of $R1
  Push $R5  ; worker - copy of directory string/fqpn to search for
  Push $R6  ; worker - single charcter copy or find handle
  
  StrCpy $R3 0        ; init character index
  StrLen $R4 $R1      ; determine length of semicolon delimited path
  StrCpy $R5 0        ; init return value
  
  findDir:  ; find a semi-colon or end of string
  IntCmp $R3 $R4 exit 0 exit   ; we are done if no unprocessed string left

  loop:  
    StrCpy $R6 $R1 1 $R3       ; get the next character
    StrCmp $R6 ";" foundDir    ; if it is semi-colon, we have found a dir
    IntOp $R3 $R3 + 1          ; increment index
    IntCmp $R3 $R4 foundDir    ; if we are at end of string, we have a dir
  Goto loop                    ; still more chars in this dir

  foundDir:
    StrCpy $R5 $R1 $R3     ; copy the dir to $R5
    StrCpy $R5 "$R5\$R0"   ; construct fqpn
    IfFileExists $R5 exit  ; if file exists we are done
    StrCpy $R5 0           ; reset return value to 0
    IntOp $R4 $R4 - $R3    ; compute maxlen of new delimited path
    IntCmp $R4 0 exit      ; no more path left, exit 
    IntOp $R3 $R3 + 1      ; Increment $R3 past the semi-colon
    StrCpy $R1 $R1 $R4 $R3 ; remove dir from the delimited path
    StrCpy $R3 0           ; index back to start of new delimited path
    goto findDir           ; get another directory to look in

  exit:
    Pop  $R6
    Exch $R5 ; output - fully qualified pathname
    Exch
    Pop  $R4
    Exch
    Pop  $R3
    Exch
    Pop  $R1
    Exch 
    Pop  $R0
FunctionEnd
