#include <stdio.h>
#include <rpc/rpc.h>
#include <rpc/xdr.h>
#include "xdrs.h"

XDR_element	xdrfile[MAX_NUM_XDR_FILES] = {
	NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
	NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
	NULL, NULL, NULL, NULL};
	
#ifdef cray
long XDR_OPEN (int *fname_len, char *filename, int *mode)
#else
long xdr_open_(int *fname_len, char *filename, int *mode)
#endif
{
    FILE	*f;
    int  	new_xdr_id;
    XDR	        *xdrs;
    char	local_filename[256];

    strncpy (local_filename, filename, *fname_len);
    local_filename[*fname_len] = '\0';

/* Get new XDR ID to access file */
    if ((new_xdr_id = xdr_getid()) == -1) {
	fprintf (stderr, "Error opening file %s\n",
		 local_filename);
	exit (-1);
    }

/* Save file name of XDR file */
    xdrfile[new_xdr_id].filename = (char *)
	malloc(sizeof(char)*(*fname_len + 1));
    strcpy (xdrfile[new_xdr_id].filename, local_filename);

    xdrs = (XDR *) malloc (sizeof(XDR));
    if (xdrs == NULL) {
	fprintf (stderr, "Error on xdr stream create\n");
	fprintf (stderr, "filename=%s\n", local_filename);
	exit (-1);
    }

    if (*mode == 1) {
	if ((f = fopen(local_filename, "r")) == NULL) {
	    fprintf (stderr, 
		     "Error opening XDR file %s for reading\n",
		     local_filename);
	    perror ("Reason");
	    exit (-1);
	}

	/* initialize XDR stream */      
	xdrstdio_create (xdrs, f, XDR_DECODE);
    }
    else if(*mode == 2) {
	if ((f = fopen(local_filename, "w")) == NULL ) {
	    fprintf (stderr, 
		     "Error opening XDR file %s for writing\n",
		     local_filename);
	    perror ("Reason");
	    exit (-1);
	}

	/* initialize XDR stream */      
	xdrstdio_create (xdrs, f, XDR_ENCODE);
 }
    else {
	fprintf(stderr, "error: cxdrinit called with mode=%1d\n", *mode);
	exit( -1 );
    }


    xdrfile[new_xdr_id].xdrs = xdrs;

/* Add file pointer to user's data area in XDR structure so
 * file can be closed when the destroy routine is called
 */
    xdrs->x_public = (caddr_t)f;

    return (new_xdr_id);
}

int xdr_getid()
{
    int	i;

    i = 0;
    while (xdrfile[i].filename != NULL) {
	i++;
	if (i >= MAX_NUM_XDR_FILES) {
	    fprintf (stderr, "XDR error: too many files open");
	    fprintf (stderr, "Max is %d\n", MAX_NUM_XDR_FILES);
	    return (-1);
	}
    }
    return (i);
}
