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

/*  Modification for the portabiliy on different platforms. Compile without 
    underscore only on IBM and HP.   S.Dobricic   */
#ifdef UNDERSCORE
#define ropen     ropen_
#define rclose    rclose_
#define readnewg  readnewg_
#endif

int fd;

int ropen(file,ret)
char *file;
int *ret;
{
char namef[200];
int bi;

	printf("%s \n",file);
   strcpy(namef,file);
	printf(" %s %s \n",file,namef);
   bi=0;
   while ((namef[bi] != ' ') && (namef[bi] != '\0')) bi++;
   namef[bi]='\0';
   fd = open(namef,O_RDONLY);

   if (fd == -1) 
   { 
    printf(" Error Open File: %s \n",namef);
    *ret = (int)1;
   }
   else
   {
    printf(" File %s opened \n",namef);
    *ret = (int)0;
   }
   return ;
}


int rclose()
{
 close(fd);
}

int readnewg(karray,ilen,keof)
int karray[400000];
int *ilen,*keof;
{
int *karrayt;
unsigned char c1[4];
int ic4=0, GRIB=1196575042;
unsigned char pp[4];
int k,i;

  while (ic4 != GRIB ) {

  for(k=0; k<3; k++ ){ c1[k]=c1[k+1]; }

  if (read(fd,&c1[3],1) != 1) 
  {
     *keof = (int)1;
      printf("eof \n"); 
      return;
  }

  ic4=c1[0]*16777216+c1[1]*65536+c1[2]*256+c1[3];

  }

  karray[0]=ic4;

  if (read(fd,pp,4) != 4) 
  {
     *keof = (int)1;
      printf("eof on the begining of GRIB \n");
      return ;
  }

  i = pp[0]*65536+pp[1]*256+pp[2];  /* Message lenght */

  karray[1]=i*256+pp[3];

  k=i-8;
  k=2*k-(k/4)*4;
  karrayt = ((int *) malloc(k));
  if (read(fd,karrayt,k)!=k) 
  {
     *keof = (int)1; 
      printf("eof on the midlle of GRIB \n"); 
      return 0;
  }
  i=(k+8)/4;
  for(k=2; k<i; k++) { karray[k]=karrayt[k-2]; }
  ilen = ((int *) malloc(4));
  *ilen = (int)i; 
  *keof = (int)0; 
  /*return ;*/
} 
