#include "base32decode.h"

static const unsigned char base32values[128] = {
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
    0x08, 0x09, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
    0xff, 0xff, 0x0a, 0x0b, 0x0c, 0xff, 0x0d, 0x0e,
    0x0f, 0xff, 0x10, 0x11, 0x12, 0x13, 0x14, 0xff,
    0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c,
    0x1d, 0x1e, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff,
    0xff, 0xff, 0x0a, 0x0b, 0x0c, 0xff, 0x0d, 0x0e,
    0x0f, 0xff, 0x10, 0x11, 0x12, 0x13, 0x14, 0xff,
    0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c,
    0x1d, 0x1e, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff
};

int base32decode(unsigned char *out, long long outlen, const unsigned char *in, long long inlen) {

    long long i, j = 0;
    unsigned char u;
    unsigned long long v = 0, vbits = 0;

    for (i = 0; i < inlen; ++i) {
        
        if (in[i] & 0x80) return 0;
        u = base32values[in[i]];
        if (u > 0x1f) return 0;
        v |= u << vbits;
        vbits += 5;

        if (vbits >= 8) {
            if (j >= outlen) return 0;
            out[j++] = v;
            vbits -= 8; 
            v >>= 8;
        }
    }
    if (vbits) {
        if (j >= outlen) return 0;
        out[j++] = v;
    }
    return 1;
}
