/*
 * Copyright (C) 2007 Loren Merritt <lorenm@u.washington.edu>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "common.h"

static int read_golomb( xlsc_rac_t *c, uint8_t *model )
{
    int prefix = 0;
    while( !get_rac( c, model+1+MIN(prefix,6) ) )
        prefix++;
    int v = 1 << prefix;
    while( prefix-- )
        v += get_rac( c, model ) << prefix;
    if( get_rac_bypass( c ) )
        v = -v;
    return v;
}

static void read_mvd( xlsc_t *h )
{
    xlsc_rac_t *c = &h->out.c;
    uint8_t *model = h->model.mv;
    int i;

    for( i=0; i<2; i++ )
        if( get_rac( c, model+0 ) )
            ((int*)&h->mb.mv.x)[i] += read_golomb( c, model+1 );
}

static void read_residual( xlsc_t *h, int b )
{
    xlsc_rac_t *c = &h->out.c;
    uint8_t *model = h->model.coef[h->mb.intra];
    int16_t *dct = h->mb.dct[b];
    int i;

    if( !get_rac( c, model+0 ) )
        return;

    for( i=0; i<64; i++ )
    {
        if( i==63 || get_rac( c, model+1+i ) )
        {
            dct[xlsc_zigzag_tab[i]] = read_golomb( c, model+127+8*xlsc_coef_abs_context[i] );
            if( i==63 || get_rac( c, model+64+i ) )
                break;
        }
    }
}

void xlsc_macroblock_read( xlsc_t *h )
{
    int i;
    memset( h->mb.dct, 0, sizeof(h->mb.dct) );
    if( !h->fdec->intra )
    {
        h->mb.intra = get_rac( &h->out.c, h->model.mb );
        h->mb.mv = h->mb.mvp;
        if( !h->mb.intra )
            read_mvd( h );
    }
    for( i=0; i<4; i++ )
        read_residual( h, i );
}

