#include <QFile>
#include <QPixmap>
#include <QImage>
#include <QApplication>

#define A   0
#define B   8
#define C   16 
#define D   24 

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QFile f(argv[1]);
    f.open(QFile::ReadOnly);
    QByteArray dataBA = f.readAll();
    unsigned char *data = (unsigned char *)dataBA.data();
    unsigned int magic = (data[0] << A) | (data[1] << B) | (data[2] << C) | (data[3] << D); data += 4;
    unsigned int dummy = (data[0] << A) | (data[1] << B) | (data[2] << C) | (data[3] << D); data += 4;
    unsigned int w     = (data[0] << A) | (data[1] << B) | (data[2] << C) | (data[3] << D); data += 4;
    unsigned int h     = (data[0] << A) | (data[1] << B) | (data[2] << C) | (data[3] << D); data += 4;
    unsigned int size  = (data[0] << A) | (data[1] << B) | (data[2] << C) | (data[3] << D); data += 4;
    unsigned int alph  = (data[0] << A) | (data[1] << B) | (data[2] << C) | (data[3] << D); data += 4;
    printf("file: %s  w: %i h: %i size: %i (%i %i)\n", argv[1], w, h, size, a, b);

    bool alpha = false;
    unsigned char *trans = 0;
    if ( alph == 4 ) {
        alpha = true;
        trans = ((unsigned char *)data) + size;
    }

    QImage img(w ,h, QImage::Format_ARGB32);
    unsigned short *pixels = (unsigned short *)data;
    for (int j = 0; j < h; j++) {
        for (int i = 0; i < w; i++) {
            int r = (pixels[i+j*w] >> 11) & 0x1F;
            int g = (pixels[i+j*w] >>  5) & 0x3F;
            int b = (pixels[i+j*w] >>  0) & 0x1F;
            if ( alpha ) {
                unsigned int a = trans[0];
                trans++;
                img.setPixel(i, j, qRgba(r<<3,g<<2,b<<3,a));
            } else {
                img.setPixel(i, j, qRgb(r<<3,g<<2,b<<3));
            }
        }
        if ((j & 1) == 0)
            trans -= w;
    }

    img.save(argv[2]);
    return -1;
}

