#include <sys/types.h>
#include <netinet/in.h>
#include <stdio.h>
#include "strfile.h"
#include "byteorder.h"

extern char *malloc();

write_tbl(tbl, file)
STRFILE tbl;
FILE *file;
{
     int i;
     STRFILE newtbl;

#define DOIT(a) newtbl.a = htonl(tbl.a)
     
     DOIT(str_numstr);
     DOIT(str_longlen);
     DOIT(str_shortlen);

     for (i = 0; i < MAXDELIMS; i++) {
	  DOIT(str_delims[i]);
     }

     DOIT(str_unused);

     if (! fwrite(&newtbl, sizeof newtbl, 1, file)) {
	  return(-1);
     }

#undef DOIT

     return(0);
}


read_tbl(tbl, file)
STRFILE *tbl;
FILE *file;
{
     int i;

     if (! fread(tbl, sizeof(*tbl), 1, file)) {
	  return(-1);
     }

#define DOIT(a) tbl->a = ntohl(tbl->a)
     
     DOIT(str_numstr);
     DOIT(str_longlen);
     DOIT(str_shortlen);

     for (i = 0; i < MAXDELIMS; i++) {
	  DOIT(str_delims[i]);
     }

     DOIT(str_unused);

#undef DOIT

     return(0);
}


write_longs(array, num, file)
long *array;
int num;
FILE *file;
{
     int i;
     long *new, *ptr;

     ptr = new = (long *) malloc(num * sizeof(*new));
     if (! new) {
	  return(-1);
     }

     for (i = 0; i < num; i++, ptr++, array++) {
	  *ptr = htonl(*array);
     }

     i = fwrite(new, sizeof(*new), num, file);

     free(new);

     if (! i) {
	  return(-1);
     }

     return(0);
}


read_longs(array, num, file)
long *array;
int num;
FILE *file;
{
     int i;

     for (i = 0; i < num; i++, array++) {
	  if (! fread(array, sizeof *array, 1, file)) {
	       return(-1);
	  }
	  *array = ntohl(*array);
     }

     return(0);
}
