uses console
declare DemoTree(string src)
DemoTree "[]"
DemoTree "[1, 2, 4]"
DemoTree "[3, 1, 3, 1]"
DemoTree "[1, 2, 3, 1]"
DemoTree "[3, 2, 1, 3]"
DemoTree "[3, 3, 3, 1, 1, 3, 3, 3]"
pause
end

/*
RESULTS:
========

[]
[]

[1, 2, 4]
[ 1,[ 2,[[ 4]]]]

[3, 1, 3, 1]
[[[ 3]], 1,[[ 3]], 1]

[1, 2, 3, 1]
[ 1,[ 2,[ 3]], 1]

[3, 2, 1, 3]
[[[ 3], 2], 1,[[ 3]]]

[3, 3, 3, 1, 1, 3, 3, 3]
[[[ 3, 3, 3]], 1, 1,[[ 3, 3, 3]]]
*/



sub DemoTree(string src)
========================

string tree=nuls 1000   'TREE OUTPUT
int i=1                 'src char iterator
int j=1                 'tree char iterator
byte bs at strptr src   'src bytes
byte bt at strptr tree  'tree bytes
int bl=len src          'end of src
int lvl                 'current tree level
int olv                 'prior tree level
int v                   'number value
string vs               'number in string form

do
  exit if i>bl
  select bs[i]
  case 91 '['
    i++
  case 93 ']'
    if i=bl
      gosub writex
    endif
    i++
  case 44 ','
    i++
    gosub writex
  case 0 to 32 'white space
    i++
    'bt[j]=" " : j++
  case 48 to 57 '0..9'
    gosub ReadDigits
  case else
    i++
  end select
loop
tree=left(tree,j-1)
output src cr
output tree cr cr
exit sub

'SUBROUTINESOF DEMOTREE:
========================

writex:
=======
olv=lvl
  if i>=bl
    if v=0 and olv=0
      tree="[]" : j=3
      ret
    endif
  endif
  if v<olv
    gosub WriteRbr
  endif
  if olv
    gosub WriteComma
  endif
  if v>olv
    gosub WriteLbr
  endif
  gosub WriteDigits '3]]'
  if i>=bl
    v=0
    gosub WriteRbr
  endif
ret

ReadDigits:
===========
v=0
while i<=bl
  select bs[i]
  case 48 to 57 '1..9
    v*=10 : v+=bs[i]-48 'digit
  case else
    exit while
  end select
  i++
wend
ret
'
WriteDigits:
============
vs=" "+str(v) : mid(tree,j,vs) : j+=len vs
ret

WriteLbr:
=========
while v>lvl
  bt[j]=91 : j++ : lvl++
wend
ret

WriteRbr:
=========
while v<lvl
  bt[j]=93 : j++ : lvl--
wend
ret

WriteComma:
===========
bt[j]=44 : j++ ','
ret

end sub
