(bind-func replace
(lambda (orig:i8* rep:i8* with:i8*)
(if (null? (strstr orig rep)) (Str orig)
(let ((origl (strlen orig))
(repl (strlen rep))
(withl (strlen with))
(pos (strstr orig rep))
(start (- (ptrtoi64 pos) (ptrtoi64 orig)))
(newstr:i8* (salloc (+ 1 (strlen orig) (- withl repl)))))
(memset newstr 0 (+ 1 (strlen orig) (- withl repl)))
(strncpy newstr orig start)
(strncpy (pref-ptr newstr start) with withl)
(strncpy (pref-ptr newstr (+ start withl))
(pref-ptr orig (+ start repl))
(- origl (+ start repl)))
(Str newstr)))))