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

#include "cgribex.h"

#define MAX_VALUES  7200*3600
 
int main(int argc, char *argv[])
{
  int isec0[2], isec1[4096], isec2[4096], isec3[2], isec4[512];
  double fsec2[512], fsec3[2];
  int iword;
  size_t gribbuffersize = 0;
  unsigned char *gribbuffer = NULL;

  if ( argc != 2 )
    {
      printf("usage: %s filename\n", argv[0]);
      return(1);
    }

  char *ifile = argv[1];

  int ifileID = gribOpen(ifile, "r");
  if ( ifileID == -1 )
    {
      fprintf(stderr, "Open failed on %s\n", ifile);
      return (1);
    }

  size_t maxvalues = MAX_VALUES;
  double *data = (double *) malloc(maxvalues*sizeof(double));

  while ( 1 )
    {
      size_t recsize = gribGetSize(ifileID);
      size_t readsize = recsize;

      if ( recsize == 0 ) break;

      if ( gribbuffersize < recsize )
	{
	  gribbuffersize = recsize;
	  gribbuffer = (unsigned char *) realloc(gribbuffer, gribbuffersize);
	}

      int iret = gribRead(ifileID, gribbuffer, &readsize);
      if ( iret != 0 ) break;

      gribExDP(isec0, isec1, isec2, fsec2, isec3, fsec3, isec4, data,
	       (int)maxvalues, (int *) gribbuffer, (int)gribbuffersize, &iword, "D", &iret);

      size_t datasize = (size_t)isec4[0];

      printf("code: %d  level: %d  gridsize: %d  firstvalue: %g\n", 
	     ISEC1_Parameter, ISEC1_Level1, (int)datasize, *data);
      /*
      for (size_t i = 0; i < 16; i++)
	{
	  if (i % 8 == 0) printf("\n"); 
	  printf("%16.5lf", data[i]);
	}
      printf("\n");

      for (size_t i = datasize-16; i < datasize; i++)
	{
	  if (i % 8 == 0) printf("\n"); 
	  printf("%16.5lf", data[i]);
	}
      printf("\n");
      */
    }

  gribClose(ifileID);

  if ( data ) free(data);
  if ( gribbuffer) free(gribbuffer);

  return 0;
}
