/* *******************************************************************
 *                                                                   *
 * Copyright (c) MIT/JGOFS                                           *
 *                                                                   *
 *                                                                   *
 * File             : nm.c                                           *
 *                                                                   *
 * Purpose          :                                                *         
 *                                                                   *
 * Version Number   : 1.5                                            *
 *                                                                   *
 * Revision History :                                                *
 *                                                                   *
 * Date                              Developer                       *
 * ----                              ---------                       *
 *                                                                   *
 * Sat Oct 17  1992 10.00           Glenn Flierl                     *
 * Oct 1993                         attr[][]                         *
 * July 1995                        Christine Hammond                *
 *        change to add field width determination based on width of  *
 *        the label in the data.  Preparer must determine max width  *
 *        of column from inspection of data column width.            *
 *        Ex:  event___ , sta__ ,bot                                 *
 *        will give lengths of 8, 5, and 3 for the respective cols   *
 *                                                                   *
 * January 1996                     Christine Hammond                * 
 *       'type' the functions that outer method calls to avoid       *
 *        warnings on ANSI compilers - void() used for functions     * 
 *        returning no value  (e.g., return;)                        * 
 *                                                                   *
 * March  1996                      Christine Hammond                * 
 *       fix in_proclabel (width sensing) to ignore attributes with a*
 *       substring 'width=', ex: 'inpwidth=N', and to properly deal  *
 *       with a 'width=N' attr when it occurs after a ';', as in     *
 *       a series of attributes, ex: 'meters;color=pink;width=12'    *
 *                                                                   *
 * March  1996                      Warren Sass, Christine Hammond   * 
 *       use a .h include file to set sizes of buffers used          *
 *       NOTE:  'minbufsize.h' also included in outer.c, to achieve  *
 *       some correspondence.  User-specified include file allowed   *
 *       (see minbufsize.h) as a compile switch IOBUF_INCLUDE        * 
 *                                                                   *
 * November  1996                   Warren Sass, Christine Hammond   *
 *       ioattrout change - remove code after getwidth() call whose  *
 *       comment stated:  don't show the width attribute             *
 *       code was:        str = '\0';                                *
 *       we want outer to determine what gets shown.                 *
 *                                                                   *
 * November  1996                        Christine Hammond           *
 *       proclabel change - place separating ';' AFTER first attrib  *
 *                                                                   *
 * May 1997                         Glenn Flierl                     *
 *       changed error calls to use error_ in outer.c                *
 *                                                                   *
 * June 1997 grf                                                     *
 *       changed sub names to in_xxxx, fixes for v 1.5               *
 ******************************************************************* */

#include <stdio.h>
#include <string.h>
#include OPTIONS
#include INNEROPTIONS

double strtod();

/* #define DEBUG */

#define SEPARATOR " ,=\t\n"
#define W_EXTEND '_'

char names[NVAR][VARNAMESIZE];
char values[NVAR][DATUMSIZE];
char attr[NVAR][ATTRSIZE];

int fldwidths[NVAR];
int map[NVAR];
int nheader, ndata;
FILE *fl;
int maxlev,newlev;
int eofflag=0;
char str[INBUFSIZE],*strp;
char tabcomments[COMMENTSIZE];

void in_proclabel();
void in_getwidth();
void in_striptoken();
/* * * * * *     end of declarations    * * * * * */

void in_proclabel(n, ptr)
int n;
char *ptr;
/* 
attr[] is the global array.
routine to determine the length of the title string indexed at 'n' and
pointed to by 'ptr', and based on the idea that the user preparing the
data has placed W_EXTEND characters to pad the title to the desired
width.  An attribute is constructed and saved in attr[], either by
appending to existing attr's or saving as the sole attribute, beginning
with 'width='.  Then, the W_EXTEND characters must be stripped from the
names.  Same name separators are used as before (space, tab, comma,
newline).  If an explicit 'width=' attribute is found, it is used.
*/

{
#define YES  0
#define NO   1

   int len, docalc, others;
   char attrib[ATTRSIZE], *attrptr;

/* default value for flag indicating attributes other than 'width=' */

   others = NO;

/* calculate a field width, if no attributes are present or, 
   if none of the attributes are exactly == 'width=N'       */

   docalc = YES;
   attrptr = attr[n];
   while (*attrptr) {
        if (strncmp(attrptr,"width=",6) == 0) docalc = NO;
        if ((attrptr = strchr(attrptr,';')) != NULL){
          attrptr++; 
          others = YES;
        }
   }

   if (docalc == YES) {

     len = strlen(ptr);           /* length of (possibly) extended label */
     sprintf(attrib, "width=%d", len);
     if (others == YES) {         /* add to end of other attributes? */
        strcat(attr[n],";");
        strcat(attr[n],attrib);
     } else
        strcpy(attr[n],attrib);

  };   /* end docalc loop */
  
/* strip off the column extenders from the label */

  in_striptoken(ptr);

/* and save label name without the extra W_EXTEND characters */

  strcpy(names[n], ptr);
  return;
}

void in_striptoken(p)
char *p;
{
  char *tp;
  int i;

/* if there are extending characters at end of string, strip them */

  i = strlen(p);
  while ( (tp = strrchr(p,W_EXTEND)) == p+i-1) {
     *tp = '\0';        /* shorten string by that one extend char */
     i = strlen(p);
  };
  return;
}

int in_fg(str)
char *str;
{

  *str = 0;
  while(*str == 0){
    if(fgets(str,INBUFSIZE-1,fl) == NULL) return 1;
    if(strspn(str,SEPARATOR)==strlen(str))*str = 0;
  };
  return 0;
}

int in_readdata(flag)
int flag;
{
int state,nn,i;
char *pstr;

state=1;
nn=0;
if(*str == 0)
  if(in_fg(str))return -1;

  if (str[0] == '#'){
    *tabcomments=0;
    while (str[0] == '#') {
      strcat(tabcomments,str+1);
      if (in_fg(str)) return -1;
      };
    };

if(flag<=1) while(strchr(str,'=')==NULL) if(in_fg(str))return -1;

while(strchr(str,'=')){
  state=2;
  strp=strtok(str,SEPARATOR);
  while(strp){
    if(flag==0){
      if(pstr=strchr(strp,'[')){
	*(pstr+strlen(pstr)-1)=0;
	strcpy(attr[nheader],pstr+1);
	*pstr=0;
      } else attr[nheader][0]=0;

/* routine to determine field width and assign field name */

      in_proclabel(nheader, strp);
      nn=nheader++;
    } else {
      if(pstr=strchr(strp,'['))*pstr=0;
      for(nn=0;nn<nheader;nn++){
           in_striptoken(strp);
           if(strcmp(names[nn],strp)==0) break;
      };
      if(nn==nheader)  
        error_("unknown header variable name found - ",strp);
    };
    strp=strtok(NULL,SEPARATOR);
    if(strp==NULL)error_("no value assigned - ",names[nn]);
    strcpy(values[nn],strp);
    strp=strtok(NULL,SEPARATOR);
  };
  if(in_fg(str))return -1;
};

if (state==2 || flag<=1){
  strp=strtok(str,SEPARATOR);
  i=0;
  while(strp){
    if(flag==0){
      if(pstr=strchr(strp,'[')){
	*(pstr+strlen(pstr)-1)=0;
	strcpy(attr[nheader+ndata],pstr+1);
	*pstr=0;
      } else attr[nheader+ndata][0]=0;
/*      strcpy(names[nheader+ndata],strp); */
      in_proclabel(nheader+ndata, strp);
      nn=nheader+ndata;
      ndata++;
    } else {
      if(pstr=strchr(strp,'['))*pstr=0;
      for(nn=nheader;nn<nheader+ndata;nn++) {
        in_striptoken(strp);
	if(strcmp(names[nn],strp)==0)break;
      }
      if(nn==(nheader+ndata))error_("unknown data variable - ",strp);
    };
    map[i++]=nn;
    strp=strtok(NULL,SEPARATOR);
  };
  *str=0;
  return 1;
};

strp=strtok(str,SEPARATOR);
for(nn=0;nn<ndata;nn++){
  if(strp==NULL){
    if(in_fg(str)) return -1;
    strp=strtok(str,SEPARATOR);
  };
  strcpy(values[map[nn]],strp);
  strp=strtok(NULL,SEPARATOR);
};
*str = 0;
return 2;
}

int ioopen_(s,nparams,ntotal)
char *s[];
int *nparams,*ntotal;
{
char tmp[INBUFSIZE],*tok;
int ncnt,i,j;
if((fl=fopen(s[0],"r")) == NULL)error_("file name ",s[0]);
s[0][0] = 0;
str[0]=0;
strp=str;
nheader=0;
ndata=0;
*tabcomments=0;
if(in_readdata(0)<=0)error_("file structure","");
*ntotal=nheader+ndata;
if (nheader>0){newlev=3;return 1;};
newlev=2;return 0;
}

void ioname_(vn,s)
int *vn;
char *s;
{
strcpy(s,names[*vn]);
}

int iovarlevel_(vn)
int *vn;
{
if(*vn<nheader) return 0;
return 1;
}

int ioattrout_(vn,str)
int *vn;
char *str;
{
char *at;
int j;
j= *vn;

if (attr[j][0]){
  at=strchr(attr[j],';');
  if(at){
    *at = '\0';
    strcpy(str,attr[j]);
    if (strncmp(str,"width=",6) == 0) {   /* width attr, use it for tabwidths */
      in_getwidth(&j,str);
    }
    strcpy(attr[j],at+1);
  } else {
    strcpy(str,attr[j]);
    if (strncmp(str,"width=",6) == 0) {
      in_getwidth(&j,str);
    }
    attr[j][0]='\0';
  };
  return 1;
} else return 0;
}

int iocommout_(str)
char *str;
{
char *at;
if (tabcomments[0]){
  at=strchr(tabcomments,'\n');
  if(at){
    *at = '\0';
    strcpy(str,tabcomments);
    strcpy(tabcomments,at+1);
  } else {
    strcpy(str,tabcomments);
    tabcomments[0]='\0';
  };
  return 1;
} else return 0;
}
  

void iovalreal_(vn,f)
int *vn;
float *f;
{
/*     following line changed by clh, May 1996
       if(strspn(tabvalues[i],"0123456789.+-"))
       to one below, to allow for strings that begin with digits
*/

int i;
char *end_char_ptr;

i=*vn;
if(i<0){*f= -9999.0;return;};

/*     if strtod does not point to NULL, make the 'number' returned a 
       'missing' one.  Note that if the string conversion produces no
        number, end_char_ptr will point to tabvalues[i], which is not NULL
*/
 *f=strtod(values[i],&end_char_ptr);
 if (*end_char_ptr != '\0')
   *f= -9999.0;

#ifdef DEBUG
printf("iovalreal %d %f\n",*vn,f);
#endif
return;
}

void iovalstr_(vn,tmp)
int *vn;
char *tmp;
{
static char *s;
int i;
i= *vn;
if(i<0){strcpy(tmp,"nd");return;};
s=values[i];
s=s+strspn(s," ");
strcpy(tmp,s);
#ifdef DEBUG
printf("iovalstr %d %s\n",*vn,tmp);
#endif
return;
}

int ioreadrec_(level)
int *level;
{
if(eofflag)return 0;
switch(*level){
 case 0:
  if(nheader){
    if (newlev & 1) {newlev=0;return 1;};
    newlev=in_readdata(1);
    if(newlev<0){eofflag=1;return 0;};
    newlev=newlev-1;
    return 1;
  } else {
    if (newlev & 2){newlev=0;return 1;};
    newlev=in_readdata(2);
    if(newlev<0){eofflag=1;return 0;};
    newlev=newlev-1;
    return 1;
  };
 case 1:
  if(newlev & 2){newlev=newlev-2; return 1;};
  newlev=in_readdata(2);
  if(newlev<0){eofflag=1;return 0;};
  if(newlev & 1) return 0;
  newlev=newlev-2;
  return 1;
};
return 0;
}

void ioclose_(maxlevel)
int *maxlevel;
{
fclose(fl);
}


int iowidth_(vn)
int *vn;
{
   int i;
   i = fldwidths[*vn];
return i;

}

void in_getwidth(vn, ptr)
int *vn;
char *ptr;
{
  char *p;
  int i,len;

  i = *vn;
  p = strchr(ptr,'=');

  sscanf(p+1,"%d", &len);

  fldwidths[i] = len;
  return;
}
