#include "Bdef.h"

#if (INTFACE == C_CALL)
void Cblacs_gridexit(ConTxt)
int  ConTxt;
#else
void blacs_gridexit_(ConTxt)
int  *ConTxt;
#endif
{
   int i;
   BLACSCONTEXT *ctxt;
   extern int Np00, minID00, availID00, MaxNCtxt00;

   extern BLACSCONTEXT **MyConTxts00;

   if ( (Mpval(ConTxt) < 0) || (Mpval(ConTxt) > MaxNCtxt00) )
      BlacsErr(Mpval(ConTxt), __LINE__, __FILE__,
	       "Trying to kill non-existant context");

   if (MyConTxts00[Mpval(ConTxt)] == NULL)
      BlacsErr(Mpval(ConTxt), __LINE__, __FILE__,
	       "Trying to kill non-existant context");

   MGetConTxt(Mpval(ConTxt), ctxt);
/*
 * Destroy context
 */
   free(ctxt->coord2proc);
   free(ctxt->SDcount);
   free(ctxt->RVcount);
   free(ctxt);
   MyConTxts00[Mpval(ConTxt)] = NULL;

/*
 * Find new smallest ID for use
 */
   availID00 = minID00 + Np00;
   for (i=0; i < MaxNCtxt00; i++)
   {
      if (MyConTxts00[i])
         if (MyConTxts00[i]->maxID > availID00)
            availID00 = MyConTxts00[i]->maxID;
   }
}
