/*
          stats_o1-s16.c
  histogramme du premier ordre d'un fichier
  d'échantillons stéréo et calcul de l'entropie

  création : Mon Jun 28 08:13:29 CEST 2004
    par whygee@f-cpu.org

  compilation :
    gcc -lm -o stats_o1-s16 stats_o1-s16.c

  invocation :
    ./stats_o1-s16 nom_fichier.raw sortie_image.raw
 */

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

unsigned long int histo[1024][1024];

int main(int argc, char *argv[]) {
  FILE *file_in, *file_out;
  signed short int droite, gauche,
    last_droite=256, last_gauche=256;
  unsigned long long int lli, taille=0;
  unsigned long int i, j, k, max, min;
  double h=0.0, entropie, proba;

  file_in=fopen(argv[1], "rb");
  if (file_in!=NULL) {
    file_out=fopen("histo1-s16", "wb");
    if (file_out!=NULL) {
      /* creation de l'histogramme en 2D */
      while (
        ( fread(&gauche, 1, sizeof(gauche), file_in)
        + fread(&droite, 1, sizeof(droite), file_in))
              == (sizeof(gauche) * 2 )) {
        taille++;
        droite=(droite >> 6)+512;
        gauche=(gauche >> 6)+512;
        histo[last_droite][droite]++;
        histo[last_gauche][gauche]++;
        last_droite=droite;
        last_gauche=gauche;
     }

     min=max=histo[0][0];
     for (i=0; i<1024; i++)
       for (j=0; j<1024; j++) {
         k=histo[i][j];
         /* recherche du maximum et du minimum */
         if (k>max)
           max=k;
         if (k<min)
           min=k;
         /* calcul de l'entropie */
         if (k>0) {
           proba=k;
           proba/=taille;
           entropie=proba*-log(proba)/M_LN2;
           h+=entropie;
         }
     }

     printf("max = %ld\n",max);
     printf("min = %ld\n",min);
     printf("entropie = %G\n",(h/4)+6);

     /* mise à l'echelle et écriture */
     for (i=0; i<1024; i++)
       for (j=0; j<1024; j++) {
         lli=histo[i][j];
         lli*=255;
         lli=lli/max;
         fputc(lli, file_out);
      }
    }
  }
  exit(EXIT_SUCCESS);
}
