/************************************************************************
 * inverse quantization                                                 *
 ************************************************************************/

#include <stdio.h>
#include "iq.h"
#include "jpeg.h"

void iq_init(DOLProcess *p) {
    p->local->num_iter = 0;
}

int iq_fire(DOLProcess *p) {
    //three quantization tables/image for JPEG,
    //only one table for JFIF, 64 elements for JFIF table.
    int i, j, nb_block;
    int block[64];
    unsigned char qtable[64];

    dbgprintf(VERBOSE, "\tIQ\tthread is alive!\n");

    DOL_read((void*)PORT_IN2, &qtable[0], sizeof(qtable), p);
    //read number of blocks to unquantify
    DOL_read((void*)PORT_IN3, &nb_block, sizeof(int), p);

    dbgprintf(VERBOSE, "\tIQ\tget Quantisation tables validation\n");

    for (j = 0; j < nb_block; j++) {
        for (i = 0; i < NB_SEND; i++) { //get from vld
            DOL_read((void*)PORT_IN1, &(block[MAX_SEND * i]),
                     MAX_SEND * (sizeof(block[0])), p);
        }

        unquantify(block, qtable);

        for (i = 0; i < NB_SEND; i++) { //send to zigzag
            DOL_write((void*)PORT_OUT1, &(block[MAX_SEND * i]),
                      MAX_SEND *  (sizeof(block[0])), p);

        }
    }

    dbgprintf(VERBOSE, "\tIQ\tget Quantisation tables validation: finished\n");

    //end this process
    p->local->num_iter++;
    if (p->local->num_iter == NUMBER_OF_FRAMES) {
        DOL_detach(p);
        return 0;
    }

    return 0;
}
