#include <stdio.h>
#include <stdlib.h>
#include "readbmp.h"

/* kein kommentar zu meinen bmp reader :) (geschrieben in 10 Minuten)*/

void readbmp(FILE *rh,struct bmpdata_s *bmpdata)
{

    struct bmps_s bmps;
    struct bmph_s bmph;
    
    unsigned long *colors,i;
    unsigned char *data;
    
    //printf(".readbmp");
    // LESE BMPKOPF
        
    fread(bmps.ID,2,1,rh);
    if(bmps.ID[0]!='B' || bmps.ID[1]!='M')
    {
         printf(".error: not a bmp file (%C%C)\n",bmps.ID[0],bmps.ID[1]);
         return;
    }
    
    // size
    
    fread(&bmps.bmpsize,4,1,rh);
    //printf(".bfSize = %d\n",bmps.bmpsize);
    
    // skip 4 bytes
    fread(&bmps.dummy,4,1,rh);
    
    
    fread(&bmps.bfOffBits,4,1,rh);
    //printf(".bfOffBits = %d\n",bmps.bfOffBits);

     // skip 4 bytes
    fread(&bmps.dummy,4,1,rh);

    // LESE BMPINFOHEADER
    
    fread(&bmph.biWidth,4,1,rh);
    fread(&bmph.biHeight,4,1,rh);
    fread(&bmph.biPlanes,2,1,rh);
    fread(&bmph.biBitCount,2,1,rh);
    fread(&bmph.biCompression,4,1,rh);
    fread(&bmph.biSizeImage,4,1,rh);
    fread(&bmph.biXPelsPerMeter,4,1,rh);
    fread(&bmph.biYPelsPerMeter,4,1,rh);
    fread(&bmph.biClrUsed,4,1,rh);
    fread(&bmph.biClrImportant,4,1,rh);

    //printf(" - size (%dx%dx%d) comp=%d\n",bmph.biWidth,bmph.biHeight,bmph.biPlanes*bmph.biBitCount,bmph.biCompression);

    data = (unsigned char*) malloc(bmph.biWidth*bmph.biHeight);

    // reading colors

    colors = (unsigned long*) malloc(256*sizeof(unsigned long));
    fread(colors,1024,1,rh);
    
    for(i=0;i<bmph.biHeight;i++)
    {
        fread(&data[((bmph.biHeight-1)-i)*bmph.biWidth],bmph.biWidth,1,rh);
    }
    
    bmpdata->data = (unsigned short*) data;
    bmpdata->len  = bmph.biWidth*bmph.biHeight;
    bmpdata->cmap = colors;
    bmpdata->width  = bmph.biWidth;
    bmpdata->height = bmph.biHeight;
    bmpdata->depth  = bmph.biPlanes*bmph.biBitCount;
   
    
}
