// 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
//    public release som v4.1   9 Aug 2008   (Birthday)
//    public release som v5.0   5 Dec 2009   (Long live the King)

//    improve efficiency by nested-if  29 July 2008
//    fprints now move to syscall 11   20 sept 2009

// 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
        c1 = (a >> 24) & 255
        if c1 != 0
            v = v*10 + c1 - 48
            c2 = (a >> 16) & 255
            if c2 != 0
                v = v*10 + c2 - 48
                c3 = (a >> 8) & 255
                if c3 != 0
                    v = v*10 + c3 - 48
                    c4 = a & 255
                    if c4 != 0
                        v = v*10 + c4 - 48
        i = i + 1
        a = s1[i]
    v

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

// pack array of char to som-string s1
// use nested if
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

