/*
 *
 * Copyright 1998-1999, University of Notre Dame.
 * Authors: Jeffrey M. Squyres, Kinis L. Meyer with M. D. McNally 
 *          and Andrew Lumsdaine
 *
 * This file is part of the Notre Dame LAM implementation of MPI.
 *
 * You should have received a copy of the License Agreement for the
 * Notre Dame LAM implementation of MPI along with the software; see
 * the file LICENSE.  If not, contact Office of Research, University
 * of Notre Dame, Notre Dame, IN 46556.
 *
 * Permission to modify the code and to distribute modified code is
 * granted, provided the text of this NOTICE is retained, a notice that
 * the code was modified is included with the above COPYRIGHT NOTICE and
 * with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE
 * file is distributed with the modified code.
 *
 * LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.
 * By way of example, but not limitation, Licensor MAKES NO
 * REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY
 * PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS
 * OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS
 * OR OTHER RIGHTS.  
 *
 * Additional copyrights may follow.
 *
 *	Ohio Trollius
 *	Copyright 1996 The Ohio State University
 *	RBD
 *
 *	$Id: reqfree.c,v 6.3 1999/11/12 05:19:32 jsquyres Exp $
 *
 *	Function:	- free communication request
 *	Accepts:	- ptr to request
 *	Returns: 	- MPI_SUCCESS or error code
 */

#include <blktype.h>
#include <mpi.h>
#include <mpisys.h>
#include <rpisys.h>

/*
 * external functions
 */
extern void		lam_initerr();
extern void		lam_resetfunc();
extern void		lam_setfunc();
extern void		_mpi_req_rem();
extern int		lam_errfunc();
extern int		lam_mkerr();
extern int		_mpi_req_destroy();
extern int		_mpi_req_end();

int
MPI_Request_free(preq)

MPI_Request		*preq;

{
	MPI_Request	req;			/* request */
	int		err;			/* error code */

	lam_initerr();
	lam_setfunc(BLKMPIREQFREE);
/*
 * Check arguments.
 */
	if (preq == 0) {
		return(lam_errfunc(MPI_COMM_WORLD,
			BLKMPIREQFREE, lam_mkerr(MPI_ERR_ARG, 0)));
	}

	if ((req = *preq) == MPI_REQUEST_NULL) {
		return(lam_errfunc(MPI_COMM_WORLD,
			BLKMPIREQFREE, lam_mkerr(MPI_ERR_REQUEST, 0)));
	}
/*
 * Destroy all the shadows
 */
	if (req->rq_shadow != MPI_REQUEST_NULL)
	  MPI_Request_free(&req->rq_shadow);
/*
 * If active, flag it for destruction.
 * Otherwise destroy it.
 */
	if (req->rq_state == LAM_RQSACTIVE || req->rq_state == LAM_RQSSTART) {

		req->rq_flags |= LAM_RQFORPHAN;
	}
	else {
		_mpi_req_rem(req);

		if (req->rq_state == LAM_RQSDONE) {
			err = _mpi_req_end(req);
			if (err != MPI_SUCCESS) {
				return(lam_errfunc(MPI_COMM_WORLD,
						BLKMPIREQFREE, err));
			}
		}

		err = _mpi_req_destroy(preq);
		if (err != MPI_SUCCESS) {
			return(lam_errfunc(MPI_COMM_WORLD,
					BLKMPIREQFREE, err));
		}
	}

	*preq = MPI_REQUEST_NULL;
	
	lam_resetfunc(BLKMPIREQFREE);
	return(MPI_SUCCESS);
}
