#include "Bdef.h"

int Sidring_br(ctxt, scope, rsrc, csrc, step)
BLACSCONTEXT  *ctxt;
char  scope;
int  rsrc;
int  csrc;
int  step;
{
   void Ssend2d00();
   void Srecv2d00();

   int rdest, cdest, vsrc, itmp;
   int msgid;
   int info, rbufid;

   scope = Mlowcase(scope);
   switch(scope)
   {
   case 'r':
      msgid = Mrid(ctxt);
      cdest = (ctxt->npcol+ctxt->mycol+step)%ctxt->npcol;
      Srecv2d00(ctxt, msgid);
/*
    *    Free send buffer, send from receive buff
 */
      rbufid = pvm_getrbuf();
      info = pvm_freebuf(pvm_setsbuf(rbufid));
      Mpvmerror(info, "pvm_freebuf", __LINE__, __FILE__);
      if (cdest != csrc)
         Ssend2d00(ctxt, ctxt->myrow, cdest, msgid);
      break;
   case 'c':
      msgid = Mcid(ctxt);
      rdest = (ctxt->nprow+ctxt->myrow+step) % ctxt->nprow;
      Srecv2d00(ctxt, msgid);
/*
    *    Free send buffer, send from receive buff
 */
      rbufid = pvm_getrbuf();
      info = pvm_freebuf(pvm_setsbuf(rbufid));
      Mpvmerror(info, "pvm_freebuf", __LINE__, __FILE__);
      if (rdest != rsrc)
         Ssend2d00(ctxt, rdest, ctxt->mycol, msgid);
      break;
   case 'a':
      vsrc = Mvkpnum(ctxt, rsrc, csrc);
      msgid = Maid(ctxt);
      itmp = (ctxt->Ng+ctxt->vIam+step) % ctxt->Ng;
      Mvpcoord(ctxt, itmp, rdest, cdest);
      Srecv2d00(ctxt, msgid);
/*
    *    Free send buffer, send from receive buff
 */
      rbufid = pvm_getrbuf();
      info = pvm_freebuf(pvm_setsbuf(rbufid));
      Mpvmerror(info, "pvm_freebuf", __LINE__, __FILE__);
      if (itmp != vsrc) Ssend2d00(ctxt, rdest, cdest, msgid);
      break;
   default:
      return(BADSCP);
   }
   pvm_setrbuf(rbufid);  /* restore buffer state */
   return(0);
}
