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

#include "readbmp.h"
#include "rle.h"


int main(int argc, char *argv[])
{
  FILE *rh,*wh;
  long   filecount,i;
  struct bmpdata_s **bmpdata; 
  struct RLE16_s RLE16,RLE16Color;
  
  // teste eingabe
  
  if(argc==1)
  {
    puts("type: conv_anim2 [files.bmp]");
    return (0);
  }
  
  // ausgabefile
  wh = fopen("./output.anim","wb");
  if(wh==0)
  {
   puts("cant write to this dir!");
   exit(0);
  }
  
  filecount=argc-1;
  
  // lade daten
  
  bmpdata  = malloc(filecount*sizeof(struct bmpdata_s *));
  
  printf(".reading files %d\n",filecount);
  
  for(i=0;i<filecount;i++)
  {  
      unsigned short *cmapshort;
  
      rh = fopen(argv[i+1],"rb");
      if(rh==0)
      {
          puts("cant open file");return(-1);
      }
      
      bmpdata[i] = malloc(sizeof(struct bmpdata_s));
      readbmp(rh,bmpdata[i]);
      cmapshort = (unsigned short *) color32to15(bmpdata[i]->cmap);
      free(bmpdata[i]->cmap);                                   // free 32bit cmap
      bmpdata[i]->cmap = (unsigned long *) cmapshort;          // set to 16bit cmap
      
      fclose(rh);
  }

  // schreibe framecounter
  fwrite(&filecount,4,1,wh);        // framecount

  // schreibe First FRAME

  puts(".make first frame");
  simpleRLE16(bmpdata[0]->data,bmpdata[0]->len/2,&RLE16);
  
  fwrite(&RLE16.simpleRLE16len,4,1,wh);                        // write len
  fwrite(bmpdata[0]->cmap,512,1,wh);                           // cmap datas
  fwrite(&RLE16.simpleRLE16key,2,1,wh);                        // key
  fwrite(RLE16.simpleRLE16data,RLE16.simpleRLE16len,1,wh);     // rle datas
  
  free(RLE16.simpleRLE16data);
  
  // schreibe REST FRAMES
  
  puts(".frame compress");
  
  for(i=0;i<filecount-1;i++)
  {
    
    unsigned short *delta;
  
    printf(".deltacompress %d with %d\n",i,i+1);
        
    delta  = (unsigned short *) deltaframes(bmpdata[i]->data,bmpdata[i+1]->data,bmpdata[i+1]->len/2);
    simpleRLE16(delta,bmpdata[i+1]->len/2,&RLE16);
    free(delta);    //free delta buffer
     
    //delta  = (unsigned short *) deltaframes(bmpdata[i]->cmap,bmpdata[i+1]->cmap,512/2); 
   //simpleRLE16(delta,512/2,&RLE16Color);
    //free(delta);
  
    fwrite(&RLE16.simpleRLE16len,4,1,wh);                        // write len
    fwrite(bmpdata[i+1]->cmap,512,1,wh);                           // cmap datas
    fwrite(&RLE16.simpleRLE16key,2,1,wh);                        // key
    fwrite(RLE16.simpleRLE16data,RLE16.simpleRLE16len,1,wh);     // rle datas
  
    printf(".famelen = %d bytes\n",RLE16.simpleRLE16len+2+512+4);
  
   
    free(RLE16.simpleRLE16data);
      
  }
  
  for(i=0;i<filecount;i++)
  {
     free(bmpdata[i]);
  }
  
  free(bmpdata);
  fclose(wh);
  

  return 0;
}
