/*--------------------------------------------------
  rsdpa_mpist.cpp
--------------------------------------------------*/

#include <rsdpa_mpist.h>

int rMpiSt::iam    = 0;
int rMpiSt::ictxt  = 0;
int rMpiSt::myrow  = 0;
int rMpiSt::mycol  = 0;
int rMpiSt::nprow  = 0;
int rMpiSt::npcol  = 0;
int rMpiSt::nprocs = 0;
int rMpiSt::mb     = 1;
int rMpiSt::ictxt2 = 0;
int rMpiSt::myrow2 = 0;
int rMpiSt::mycol2 = 0;
int rMpiSt::nprow2 = 0;
int rMpiSt::npcol2 = 0;
int rMpiSt::mb2    = 40;

void rMpiSt::initialize(int& argc, char** & argv)
{
  MPI_Init(&argc,&argv);
  Cblacs_pinfo(&iam, &nprocs);
  // rMessage("iam = " << iam << " nprocs = " << nprocs);
  Cblacs_get(-1,0,&ictxt);
  Cblacs_gridinit(&ictxt,"Row-major",nprocs,1);
  Cblacs_gridinfo(ictxt,&nprow,&npcol,&myrow,&mycol);
  Cblacs_get(-1,0,&ictxt2);
  nprow2 = (int) sqrt((double)nprocs);
  npcol2 = nprocs/nprow2;
  while (nprow2*npcol2 != nprocs) {
    nprow2 --;
    npcol2 = nprocs/nprow2;
  }
  Cblacs_gridinit(&ictxt2,"Row-major",nprow2,npcol2);
  Cblacs_gridinfo(ictxt2,&nprow2,&npcol2,&myrow2,&mycol2);
}

void rMpiSt::finalize()
{
  Cblacs_barrier(ictxt,"All");
  Cblacs_gridexit(ictxt);
  Cblacs_exit(0);
}

void rMpiSt::display(FILE* fpOut)
{
  fprintf(fpOut," iam = %d , nprocs = %d , ictxt = %d \n",
	  iam , nprocs,ictxt);
  fprintf(fpOut," myrow = %d , mycol = %d , nprow = %d , npcol = %d \n",
	  myrow,mycol,nprow,npcol);
}
