#include <math.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
/* #define DEBUG 1 */
#if HP || IBM
#define jdbopen_ jdbopen
#define jdbreada_ jdbreada
#define jdbread_ jdbread
#define jdbclose_ jdbclose
#define jdbcomments_ jdbcomments
#define jdblevel_ jdblevel
#define jdbattributes_ jdbattributes
#endif

#define NVALS 250
static int nnames=0;
static int nrow=0;
static char names[NVALS][40];
static int namelen=40;

struct rowpntr {
  float *vals;
  struct rowpntr *next;
} *rows;
static int lpntr[11],maxlevel;
double *yp;
static double nan;
static int unit;

typedef struct {
  long type;
  long mrows;
  long ncols;
  long imagf;
  long namlen;
} Fmatrix;

Fmatrix mat;

#define nanflag 1

int getnames(s)
char *s;
{
  nnames= -NVALS;
  maxlevel=jdbopen_(&unit,s,names,&namelen,&nnames);
  return maxlevel;
}

int getdata()
{
static int i,lev,nr;
struct rowpntr *rp,*rpo;
float *v,*vo;

rows=(struct rowpntr *)malloc(sizeof(rows));
rows->vals=(float *)malloc(nnames*sizeof(float));
rp=rows;
v=rp->vals;

nr=0;
while((lev=jdbread_(&unit,v))>=0){
  nr++;
  rp->next=(struct rowpntr *)malloc(sizeof(rows));
  rp=rp->next;
  rp->vals=(float *)malloc(nnames*sizeof(float));
  vo=v;
  v=rp->vals;
  for(i=0;i<nnames;i++)v[i]=vo[i];
  if(lev<maxlevel && nanflag){
    nr++;
    rp->next=(struct rowpntr *)malloc(sizeof(rows));
    rp=rp->next;
    rp->vals=(float *)malloc(nnames*sizeof(float));
    for(i=0;i<nnames;i++)vo[i]=nan;
    vo=v;
    v=rp->vals;
    for(i=0;i<nnames;i++)v[i]=vo[i];
  }
}
jdbclose_(&unit);
return nr;
}

main(argc,argv)
int argc;
char *argv[];
{
static char s[1024],s1[1024];
static char *sp;
static int i,k;
struct rowpntr *rp;
double *z;

#ifdef SUN
nan=quiet_nan((long)0);
#else
nan= 0.0/0.0;
#endif

if(argc<2){
  printf("Must have object name.\n");
  exit(1);
}

/* get obj name */
strcpy(s,argv[1]);
#ifdef DEBUG
fprintf(stderr,"%s\n",s);
#endif

i=getnames(s);
if(i<0){
  printf("Open failed on %s\n",s);
  exit(1);
}

nrow=getdata();
if(nrow==0){
  printf("No data in %s\n",s);
  exit(1);
};

mat.type=1000;
mat.mrows=nrow;
mat.ncols=1;
mat.imagf=0;

z=malloc(nrow*sizeof(double));

for(k=0;k<nnames;k++){
/*
  printf("%s\n",names+k);
*/
  rp=rows;
  for(i=0;i<nrow;i++){
    z[i]=(double)rp->vals[k];
    if(z[i] <= -9999) z[i]=nan;
    rp=rp->next;
  };
/*
  printf("\n");
*/
mat.namlen=strlen(names+k)+1;
fwrite(&mat,sizeof(Fmatrix),1,stdout);
fwrite(names+k,sizeof(char),mat.namlen,stdout);
fwrite(z,sizeof(double),nrow,stdout);
}

}
