def substr = {
  # x = string, y = start, z = length
  # t is the output string
  t = ""
  # set z to position of last char
  z = (y + z - 1)
  # make sure y and z are in bounds
  y = (y max 0)
  z = (x len min z)
  # copy
  while (y min z = y) {
    st = z
    z = (x idx y)
    t = (t cat z)
    z = st
    y = (y + 1)
  }
  # return
  x = t
}

def strpos = {
  # x = needle, y = haystack
  z = 1
  while (y len min z = z) {
    t = (x len)
    (substr) y z t , t
    return if (t = x)
    z = (z + 1)
  }
  if (t = x) {
    x = z
  } else {
    x = 0
  }
}

# get a string from the user
in x

y = "foo"
(strpos) y x , y
while (y = 0 !) {
  st = (y - 1)
  st = 1
  (substr) x st st , z
  t = "bar"
  z = (z cat t)
  st = (x len)
  st = (y + 3)
  (substr) x st st , x
  x = (z cat x)
  y = "foo"
  (strpos) y x , y
}

out x
