let interpret prog =
  let mem = Array.make 256 0 in
  let ptr = ref 0 in
  let pc = ref 0 in
  let n = String.length prog in
  let acc = ref 0 in
  while !pc < n do
    let c = prog.[!pc] in
    (if c = '>' then ptr := !ptr + 1
     else if c = '<' then ptr := !ptr - 1
     else if c = '+' then mem.(!ptr) <- mem.(!ptr) + 1
     else if c = '-' then mem.(!ptr) <- mem.(!ptr) - 1
     else if c = '.' then acc := !acc + mem.(!ptr)
     else if c = '[' then begin
       if mem.(!ptr) = 0 then begin
         let depth = ref 1 in
         while !depth > 0 do
           pc := !pc + 1;
           let c = prog.[!pc] in
           if c = '[' then depth := !depth + 1
           else if c = ']' then depth := !depth - 1
         done
       end
     end
     else if c = ']' then begin
       if mem.(!ptr) <> 0 then begin
         let depth = ref 1 in
         while !depth > 0 do
           pc := !pc - 1;
           let c = prog.[!pc] in
           if c = ']' then depth := !depth + 1
           else if c = '[' then depth := !depth - 1
         done
       end
     end);
    pc := !pc + 1
  done;
  !acc

;;

interpret "+++[.-]"
