// string-s.txt   string functions
//    som-string is an array of int
//    an int contains at most 4 char, right pad with 0
//    terminate by int 0

//    public release som v3.0   5 March 2007 (Maka-bucha day)
//    public release som v3.1 	19 Aug 2007 (Draft vote day)
//    public release som v4.0   2 July 2008

// copy s1 = s2
to strcpy s1 s2 | i =
    i = 0
    while s2[i] != 0
        s1[i] = s2[i]
        i = i + 1
    s1[i] = 0

to strlen s | k =
    k = 0
    while s[k] != 0
        k = k + 1
    k

// debug per "som-string-bug.txt, 7/9/2007" 16 Mar 2008
to streq s1 s2 | i =
    i = 0
    while and (s1[i] == s2[i]) s1[i]
        i = i + 1
    s1[i] == s2[i]

// s1 is som-string (packed string)
// s1 contains only number (no sign)
to atoi s1 | a i c1 c2 c3 c4 v =
    v = 0
    i = 0
    a = s1[i]
    while a != 0
        c4 = a & 255
        c3 = (a >> 8) & 255
        c2 = (a >> 16) & 255
        c1 = (a >> 24) & 255
        if c1 != 0 v = v*10 + c1 - 48
        if c2 != 0 v = v*10 + c2 - 48
        if c3 != 0 v = v*10 + c3 - 48
        if c4 != 0 v = v*10 + c4 - 48
        i = i + 1
        a = s1[i]
    v

// print string s1, s1 is som-string
to fprints fo s1 | a i c1 c2 c3 c4 =
    i = 0
    a = s1[i]
    while a != 0
        c4 = a & 255
        c3 = (a >> 8) & 255
        c2 = (a >> 16) & 255
        c1 = (a >> 24) & 255
        if c1 != 0 fprintc fo c1
        if c2 != 0 fprintc fo c2
        if c3 != 0 fprintc fo c3
        if c4 != 0 fprintc fo c4
        i = i + 1
        a = s1[i]

: prints s1 = fprints 1 s1		// prints to stdout

// pack array of char to som-string s1
to strpack s1 ar start len | a k i e =
    k = 0
    i = start
    e = start + len
    while i < e
        a = ar[i] << 24
        i = i + 1
        if i < e
            a = a | (ar[i] << 16)
            i = i + 1
        if i < e
            a = a | (ar[i] << 8)
            i = i + 1
        if i < e
            a = a | ar[i]
            i = i + 1
        s1[k] = a
        k = k + 1
    s1[k] = 0

// End

