// clang-format off
/* ----------------------------------------------------------------------
   LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
   https://www.lammps.org/, Sandia National Laboratories
   LAMMPS development team: developers@lammps.org

   Copyright (2003) Sandia Corporation.  Under the terms of Contract
   DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
   certain rights in this software.  This software is distributed under
   the GNU General Public License.

   See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */

#include "remap.h"

#include <cstdlib>
#include <cstring>
#include <exception>
#include <set>

#define PACK_DATA FFT_SCALAR

#include "pack.h"

#define MIN(A,B) ((A) < (B) ? (A) : (B))
#define MAX(A,B) ((A) > (B) ? (A) : (B))

/* ----------------------------------------------------------------------
   Data layout for 3d remaps:

   data set of Nfast x Nmid x Nslow elements is owned by P procs
   each element = nqty contiguous datums
   on input, each proc owns a subsection of the elements
   on output, each proc will own a (presumably different) subsection
   my subsection must not overlap with any other proc's subsection,
     i.e. the union of all proc's input (or output) subsections must
     exactly tile the global Nfast x Nmid x Nslow data set
   when called from C, all subsection indices are
     C-style from 0 to N-1 where N = Nfast or Nmid or Nslow
   when called from F77, all subsection indices are
     F77-style from 1 to N where N = Nfast or Nmid or Nslow
   a proc can own 0 elements on input or output
     by specifying hi index < lo index
   on both input and output, data is stored contiguously on a processor
     with a fast-varying, mid-varying, and slow-varying index
------------------------------------------------------------------------- */

/* ----------------------------------------------------------------------
   Perform 3d remap

   Arguments:
   in           starting address of input data on this proc
   out          starting address of where output data for this proc
                  will be placed (can be same as in)
   buf          extra memory required for remap
                if memory=0 was used in call to remap_3d_create_plan
                  then buf must be big enough to hold output result
                  i.e. nqty * (out_ihi-out_ilo+1) * (out_jhi-out_jlo+1) *
                              (out_khi-out_klo+1)
                if memory=1 was used in call to remap_3d_create_plan
                  then buf is not used, can just be a dummy pointer
   plan         plan returned by previous call to remap_3d_create_plan
------------------------------------------------------------------------- */

void remap_3d(FFT_SCALAR *in, FFT_SCALAR *out, FFT_SCALAR *buf,
              struct remap_plan_3d *plan)
{
  int me;
  MPI_Comm_rank(plan->comm,&me);

  FFT_SCALAR *scratch;
  if (plan->memory == 0)
    scratch = buf;
  else
    scratch = plan->scratch;

  // use point-to-point communication

  if (!plan->usecollective) {
    int i,isend,irecv;

    for (irecv = 0; irecv < plan->nrecv; irecv++) {
      MPI_Irecv(&scratch[plan->recv_bufloc[irecv]],plan->recv_size[irecv],
                MPI_FFT_SCALAR,plan->recv_proc[irecv],0,
                plan->comm,&plan->request[irecv]);
    }

    // send all messages to other procs

    for (isend = 0; isend < plan->nsend; isend++) {
      int in_offset = plan->send_offset[isend];
      if (plan->usenonblocking) {
        plan->pack(&in[in_offset],
                  &plan->sendbuf[plan->send_bufloc[isend]],
                  &plan->packplan[isend]);
      } else {
        plan->pack(&in[in_offset],
                  plan->sendbuf,
                  &plan->packplan[isend]);
      }

      if (plan->usenonblocking) {
        MPI_Isend(plan->sendbuf + plan->send_bufloc[isend],plan->send_size[isend],MPI_FFT_SCALAR,
                plan->send_proc[isend],0,plan->comm,&plan->isend_reqs[isend]);
      } else {
        MPI_Send(plan->sendbuf,plan->send_size[isend],MPI_FFT_SCALAR,
                plan->send_proc[isend],0,plan->comm);
      }
    }

    // copy in -> scratch -> out for self data

    if (plan->self) {
      isend = plan->nsend;
      irecv = plan->nrecv;

      int in_offset = plan->send_offset[isend];
      int scratch_offset = plan->recv_bufloc[irecv];
      int out_offset = plan->recv_offset[irecv];

      plan->pack(&in[in_offset],
                 &scratch[scratch_offset],
                 &plan->packplan[isend]);
      plan->unpack(&scratch[scratch_offset],
                   &out[out_offset],&plan->unpackplan[irecv]);
    }

    // unpack all messages from scratch -> out

    for (i = 0; i < plan->nrecv; i++) {
      MPI_Waitany(plan->nrecv,plan->request,&irecv,MPI_STATUS_IGNORE);

      int scratch_offset = plan->recv_bufloc[irecv];
      int out_offset = plan->recv_offset[irecv];

      plan->unpack(&scratch[scratch_offset],
                   &out[out_offset],&plan->unpackplan[irecv]);
    }

    if (plan->usenonblocking) {
      // finally, wait for all Isends to be done
      MPI_Waitall(plan->nsend,plan->isend_reqs,MPI_STATUS_IGNORE);
    }
  } else {
    if (plan->commringlen > 0) {
      int isend,irecv;

      // populate send data
      // buffers are allocated and count/displacement buffers
      // are populated in remap_3d_create_plan

      int numpacked = 0;
      for (isend = 0; isend < plan->commringlen; isend++) {
        if (plan->sendcnts[isend]) {
          plan->pack(&in[plan->send_offset[numpacked]],
                      &plan->sendbuf[plan->sdispls[isend]],
                      &plan->packplan[numpacked]);
          numpacked++;
        }
      }

      MPI_Alltoallv(plan->sendbuf, plan->sendcnts, plan->sdispls,
                    MPI_FFT_SCALAR, scratch, plan->rcvcnts,
                    plan->rdispls, MPI_FFT_SCALAR, plan->comm);

      // unpack the data from the recv buffer into out

      numpacked = 0;
      for (irecv = 0; irecv < plan->commringlen; irecv++) {
        if (plan->rcvcnts[irecv]) {
          plan->unpack(&scratch[plan->rdispls[irecv]],
                       &out[plan->recv_offset[numpacked]],
                       &plan->unpackplan[numpacked]);
          numpacked++;
        }
      }
    }
  }
}

/* ----------------------------------------------------------------------
   Create plan for performing a 3d remap

   Arguments:
   comm                 MPI communicator for the P procs which own the data
   in_ilo,in_ihi        input bounds of data I own in fast index
   in_jlo,in_jhi        input bounds of data I own in mid index
   in_klo,in_khi        input bounds of data I own in slow index
   out_ilo,out_ihi      output bounds of data I own in fast index
   out_jlo,out_jhi      output bounds of data I own in mid index
   out_klo,out_khi      output bounds of data I own in slow index
   nqty                 # of datums per element
   permute              permutation in storage order of indices on output
                          0 = no permutation
                          1 = permute once = mid->fast, slow->mid, fast->slow
                          2 = permute twice = slow->fast, fast->mid, mid->slow
   memory               user provides buffer memory for remap or system does
                          0 = user provides memory
                          1 = system provides memory
   precision            precision of data
                          1 = single precision (4 bytes per datum)
                          2 = double precision (8 bytes per datum)
   usecollective        whether to use collective MPI or point-to-point
   usenonblocking       whether to use non-blocking or blocking MPI point-to-point
------------------------------------------------------------------------- */

struct remap_plan_3d *remap_3d_create_plan(
  MPI_Comm comm,
  int in_ilo, int in_ihi, int in_jlo, int in_jhi,
  int in_klo, int in_khi,
  int out_ilo, int out_ihi, int out_jlo, int out_jhi,
  int out_klo, int out_khi, int nqty, int permute,
  int memory, int /*precision*/, int usecollective, int usenonblocking)

{

  struct remap_plan_3d *plan;
  struct extent_3d *inarray, *outarray;
  struct extent_3d in,out,overlap;
  int i,j,iproc,nsend,nrecv,ibuf,size,me,nprocs;

  // query MPI info

  MPI_Comm_rank(comm,&me);
  MPI_Comm_size(comm,&nprocs);

  // allocate memory for plan data struct

  try {
    plan = new remap_plan_3d(usecollective, usenonblocking);
  } catch (std::bad_alloc &) {
    return nullptr;
  }

  // store parameters in local data structs

  in.ilo = in_ilo;
  in.ihi = in_ihi;
  in.isize = in.ihi - in.ilo + 1;

  in.jlo = in_jlo;
  in.jhi = in_jhi;
  in.jsize = in.jhi - in.jlo + 1;

  in.klo = in_klo;
  in.khi = in_khi;
  in.ksize = in.khi - in.klo + 1;

  out.ilo = out_ilo;
  out.ihi = out_ihi;
  out.isize = out.ihi - out.ilo + 1;

  out.jlo = out_jlo;
  out.jhi = out_jhi;
  out.jsize = out.jhi - out.jlo + 1;

  out.klo = out_klo;
  out.khi = out_khi;
  out.ksize = out.khi - out.klo + 1;

  // combine output extents across all procs

  inarray = (struct extent_3d *) malloc(nprocs*sizeof(struct extent_3d));
  if (inarray == nullptr) {
    delete plan;
    return nullptr;
  }

  outarray = (struct extent_3d *) malloc(nprocs*sizeof(struct extent_3d));
  if (outarray == nullptr) {
    free(inarray);
    delete plan;
    return nullptr;
  }

  // combine input & output extents across all procs

  MPI_Allgather(&in,sizeof(struct extent_3d),MPI_BYTE,
                inarray,sizeof(struct extent_3d),MPI_BYTE,comm);
  MPI_Allgather(&out,sizeof(struct extent_3d),MPI_BYTE,
                outarray,sizeof(struct extent_3d),MPI_BYTE,comm);

  // for efficiency, handle collective & non-collective setup separately

  if (!plan->usecollective) {
    // count send & recv collides, including self
    nsend = 0;
    nrecv = 0;
    for (i = 0; i < nprocs; i++) {
      nsend += remap_3d_collide(&in,&outarray[i],&overlap);
      nrecv += remap_3d_collide(&out,&inarray[i],&overlap);
    }

    // malloc space for send & recv info

    if (nsend) {
      plan->pack = pack_3d;

      plan->send_offset = (int *) malloc(nsend*sizeof(int));
      plan->send_size = (int *) malloc(nsend*sizeof(int));
      plan->send_proc = (int *) malloc(nsend*sizeof(int));
      plan->packplan = (struct pack_plan_3d *) malloc(nsend*sizeof(struct pack_plan_3d));

      if (plan->usenonblocking)
        plan->isend_reqs = (MPI_Request *) malloc(nsend*sizeof(MPI_Request));
      plan->send_bufloc = (int *) malloc(nsend*sizeof(int));

      if (plan->send_offset == nullptr || plan->send_size == nullptr ||
          plan->send_proc == nullptr || plan->packplan == nullptr ||
          (plan->usenonblocking && (plan->isend_reqs == nullptr)) || plan->send_bufloc == nullptr) {
        delete plan;
        return nullptr;
      }
    }

    if (nrecv) {
      if (permute == 0)
        plan->unpack = unpack_3d;
      else if (permute == 1) {
        if (nqty == 1)
          plan->unpack = unpack_3d_permute1_1;
        else if (nqty == 2)
          plan->unpack = unpack_3d_permute1_2;
        else
          plan->unpack = unpack_3d_permute1_n;
      }
      else if (permute == 2) {
        if (nqty == 1)
          plan->unpack = unpack_3d_permute2_1;
        else if (nqty == 2)
          plan->unpack = unpack_3d_permute2_2;
        else
          plan->unpack = unpack_3d_permute2_n;
      }

      plan->recv_offset = (int *) malloc(nrecv*sizeof(int));
      plan->recv_size = (int *) malloc(nrecv*sizeof(int));
      plan->recv_proc = (int *) malloc(nrecv*sizeof(int));
      plan->recv_bufloc = (int *) malloc(nrecv*sizeof(int));
      plan->request = (MPI_Request *) malloc(nrecv*sizeof(MPI_Request));
      plan->unpackplan = (struct pack_plan_3d *) malloc(nrecv*sizeof(struct pack_plan_3d));

      if (plan->recv_offset == nullptr || plan->recv_size == nullptr ||
          plan->recv_proc == nullptr || plan->recv_bufloc == nullptr ||
          plan->request == nullptr || plan->unpackplan == nullptr) {
        delete plan;
        return nullptr;
      }
    }

    // store send info, with self as last entry

    nsend = 0;
    iproc = me;
    ibuf = 0;
    for (i = 0; i < nprocs; i++) {
      iproc++;
      if (iproc == nprocs) iproc = 0;
      if (remap_3d_collide(&in,&outarray[iproc],&overlap)) {
        plan->send_proc[nsend] = iproc;
        plan->send_offset[nsend] = nqty *
          ((overlap.klo-in.klo)*in.jsize*in.isize +
          ((overlap.jlo-in.jlo)*in.isize + overlap.ilo-in.ilo));
        plan->packplan[nsend].nfast = nqty*overlap.isize;
        plan->packplan[nsend].nmid = overlap.jsize;
        plan->packplan[nsend].nslow = overlap.ksize;
        plan->packplan[nsend].nstride_line = nqty*in.isize;
        plan->packplan[nsend].nstride_plane = nqty*in.jsize*in.isize;
        plan->packplan[nsend].nqty = nqty;
        plan->send_size[nsend] = nqty*overlap.isize*overlap.jsize*overlap.ksize;
        plan->send_bufloc[nsend] = ibuf;
        ibuf += plan->send_size[nsend];
        nsend++;
      }
    }

    // plan->nsend = # of sends not including self

    if (nsend && plan->send_proc[nsend-1] == me) plan->nsend = nsend - 1;
    else plan->nsend = nsend;

    // store recv info, with self as last entry

    ibuf = 0;
    nrecv = 0;
    iproc = me;

    for (i = 0; i < nprocs; i++) {
      iproc++;
      if (iproc == nprocs) iproc = 0;
      if (remap_3d_collide(&out,&inarray[iproc],&overlap)) {
        plan->recv_proc[nrecv] = iproc;
        plan->recv_bufloc[nrecv] = ibuf;

        if (permute == 0) {
          plan->recv_offset[nrecv] = nqty *
            ((overlap.klo-out.klo)*out.jsize*out.isize +
            (overlap.jlo-out.jlo)*out.isize + (overlap.ilo-out.ilo));
          plan->unpackplan[nrecv].nfast = nqty*overlap.isize;
          plan->unpackplan[nrecv].nmid = overlap.jsize;
          plan->unpackplan[nrecv].nslow = overlap.ksize;
          plan->unpackplan[nrecv].nstride_line = nqty*out.isize;
          plan->unpackplan[nrecv].nstride_plane = nqty*out.jsize*out.isize;
          plan->unpackplan[nrecv].nqty = nqty;
        }
        else if (permute == 1) {
          plan->recv_offset[nrecv] = nqty *
            ((overlap.ilo-out.ilo)*out.ksize*out.jsize +
            (overlap.klo-out.klo)*out.jsize + (overlap.jlo-out.jlo));
          plan->unpackplan[nrecv].nfast = overlap.isize;
          plan->unpackplan[nrecv].nmid = overlap.jsize;
          plan->unpackplan[nrecv].nslow = overlap.ksize;
          plan->unpackplan[nrecv].nstride_line = nqty*out.jsize;
          plan->unpackplan[nrecv].nstride_plane = nqty*out.ksize*out.jsize;
          plan->unpackplan[nrecv].nqty = nqty;
        }
        else {
          plan->recv_offset[nrecv] = nqty *
            ((overlap.jlo-out.jlo)*out.isize*out.ksize +
            (overlap.ilo-out.ilo)*out.ksize + (overlap.klo-out.klo));
          plan->unpackplan[nrecv].nfast = overlap.isize;
          plan->unpackplan[nrecv].nmid = overlap.jsize;
          plan->unpackplan[nrecv].nslow = overlap.ksize;
          plan->unpackplan[nrecv].nstride_line = nqty*out.ksize;
          plan->unpackplan[nrecv].nstride_plane = nqty*out.isize*out.ksize;
          plan->unpackplan[nrecv].nqty = nqty;
        }

        plan->recv_size[nrecv] = nqty*overlap.isize*overlap.jsize*overlap.ksize;
        ibuf += plan->recv_size[nrecv];
        nrecv++;
      }
    }

    // plan->nrecv = # of recvs not including self

    if (nrecv && plan->recv_proc[nrecv-1] == me) plan->nrecv = nrecv - 1;
    else plan->nrecv = nrecv;

    // init remaining fields in remap plan

    plan->memory = memory;

    if (nrecv == plan->nrecv) plan->self = 0;
    else plan->self = 1;

    // plan->sendbuf is used by both the collective & non-collective implementations.
    // For non-collective and blocking, the buffer size is MAX(send_size) for any one send

    // find biggest send message (not including self) and malloc space for it

    size = 0;
    if (plan->usenonblocking) {
      for (nsend = 0; nsend < plan->nsend; nsend++)
        size += plan->send_size[nsend];
    } else {
      for (nsend = 0; nsend < plan->nsend; nsend++)
        size = MAX(size,plan->send_size[nsend]);
    }

    if (size) {
      plan->sendbuf = (FFT_SCALAR*) malloc(sizeof(FFT_SCALAR) * size);
      if (plan->sendbuf == nullptr) {
        delete plan;
        return nullptr;
      }
    }

    // if requested, allocate internal scratch space for recvs,
    // only need it if I will receive any data (including self)

    if (memory == 1) {
      if (nrecv > 0) {
        plan->scratch = (FFT_SCALAR*) malloc(sizeof(FFT_SCALAR) * nqty*out.isize*out.jsize*out.ksize);
        if (plan->scratch == nullptr) {
          delete plan;
          return nullptr;
        }
      }
    }

    // Non-collectives do not use MPI Communicator Groups

    MPI_Comm_dup(comm,&plan->comm);

  } else {
    int *commringlist;
    int commringlen = 0;
    // use a C++ set to organize the commringlist (C++17)
    std::set<int> commringset;

    nsend = 0;
    nrecv = 0;
    for (i = 0; i < nprocs; i++) {
      if (remap_3d_collide(&in,&outarray[i],&overlap)) {
        commringset.insert(i);
        nsend++;
      }
      if (remap_3d_collide(&out,&inarray[i],&overlap)) {
        commringset.insert(i);
        nrecv++;
      }
    }

    int commringappend = 1;
    while (commringappend) {
      commringappend = 0;
      for (int setproci : commringset) {
        for (j = 0; j < nprocs; j++) {
          // short-circuit if already in commring
          if (commringset.find(j) != commringset.end())
            continue;
          if (remap_3d_collide(&inarray[setproci],&outarray[j],&overlap)) {
            auto set_insert_result = commringset.insert(j);
            if (set_insert_result.second) {
              commringappend++;
            }
          }
          if (remap_3d_collide(&outarray[setproci],&inarray[j],&overlap)) {
            auto set_insert_result = commringset.insert(j);
            if (set_insert_result.second) {
              commringappend++;
            }
          }
        }
      }
    }

    // build already-sorted commringlist as an array
    commringlist = (int*) malloc(commringset.size() * sizeof(int));
    commringlen = 0;

    for (int setproci : commringset) {
      commringlist[commringlen] = setproci;
      commringlen++;
    }

    // set the plan->commringlist

    plan->commringlen = commringlen;
    plan->commringlist = commringlist;

    // malloc space for send & recv info
    // if the current proc is involved in any way in the communication, allocate space
    // because of the Alltoallv, both send and recv have to be initialized even if
    // only one of those is performed

    if (nsend || nrecv) {

      // send space

      plan->nsend = nsend;
      plan->pack = pack_3d;

      plan->send_offset = (int *) malloc(nsend*sizeof(int));
      plan->send_size = (int *) malloc(plan->commringlen*sizeof(int) + 1);

      plan->sendcnts = (int *) malloc(plan->commringlen*sizeof(int) + 1);
      plan->sdispls = (int *) malloc(plan->commringlen*sizeof(int) + 1);

      // only used when sendcnt > 0

      plan->packplan = (struct pack_plan_3d *)
        malloc(nsend*sizeof(struct pack_plan_3d));

      if (plan->send_offset == nullptr || plan->send_size == nullptr ||
          plan->sendcnts == nullptr || plan->sdispls == nullptr ||
          plan->packplan == nullptr) {
        delete plan;
        return nullptr;
      }

      // recv space

      plan->nrecv = nrecv;

      if (permute == 0)
        plan->unpack = unpack_3d;
      else if (permute == 1) {
        if (nqty == 1)
          plan->unpack = unpack_3d_permute1_1;
        else if (nqty == 2)
          plan->unpack = unpack_3d_permute1_2;
        else
          plan->unpack = unpack_3d_permute1_n;
      }
      else if (permute == 2) {
        if (nqty == 1)
          plan->unpack = unpack_3d_permute2_1;
        else if (nqty == 2)
          plan->unpack = unpack_3d_permute2_2;
        else
          plan->unpack = unpack_3d_permute2_n;
      }

      plan->recv_offset = (int *) malloc(nrecv*sizeof(int));
      plan->recv_size = (int *) malloc(plan->commringlen*sizeof(int) + 1);

      plan->rcvcnts = (int *) malloc(plan->commringlen*sizeof(int) + 1);
      plan->rdispls = (int *) malloc(plan->commringlen*sizeof(int) + 1);

      // only used when recvcnt > 0

      plan->unpackplan = (struct pack_plan_3d *)
        malloc(nrecv*sizeof(struct pack_plan_3d));

      if (plan->recv_offset == nullptr || plan->recv_size == nullptr ||
          plan->rcvcnts == nullptr || plan->rdispls == nullptr ||
          plan->unpackplan == nullptr) {
        delete plan;
        return nullptr;
      }
    }

    // store send info, with self as last entry

    nsend = 0;
    ibuf = 0;
    int total_send_size = 0;
    for (i = 0; i < plan->commringlen; i++) {
      iproc = plan->commringlist[i];
      if (remap_3d_collide(&in,&outarray[iproc],&overlap)) {
        // number of entries required for this pack's 3-d coords
        plan->send_offset[nsend] = nqty *
          ((overlap.klo-in.klo)*in.jsize*in.isize +
            ((overlap.jlo-in.jlo)*in.isize + overlap.ilo-in.ilo));
        plan->packplan[nsend].nfast = nqty*overlap.isize;
        plan->packplan[nsend].nmid = overlap.jsize;
        plan->packplan[nsend].nslow = overlap.ksize;
        plan->packplan[nsend].nstride_line = nqty*in.isize;
        plan->packplan[nsend].nstride_plane = nqty*in.jsize*in.isize;
        plan->packplan[nsend].nqty = nqty;
        // total amount of overlap
        plan->send_size[i] = nqty*overlap.isize*overlap.jsize*overlap.ksize;
        plan->sendcnts[i] = plan->send_size[i];
        plan->sdispls[i] = ibuf;
        ibuf += plan->send_size[i];
        nsend++;
      } else {
        plan->send_size[i] = 0;
        plan->sdispls[i] = ibuf;
        plan->sendcnts[i] = 0;
      }
      total_send_size += plan->send_size[i];
    }

    if (total_send_size) {
      plan->sendbuf = (FFT_SCALAR*) malloc(total_send_size * sizeof(FFT_SCALAR));
      if (plan->sendbuf == nullptr) return nullptr;
    }

    // store recv info, with self as last entry

    ibuf = 0;
    nrecv = 0;

    for (i = 0; i < plan->commringlen; i++) {
      iproc = plan->commringlist[i];
      if (remap_3d_collide(&out,&inarray[iproc],&overlap)) {
        if (permute == 0) {
          plan->recv_offset[nrecv] = nqty *
            ((overlap.klo-out.klo)*out.jsize*out.isize +
              (overlap.jlo-out.jlo)*out.isize + (overlap.ilo-out.ilo));
          plan->unpackplan[nrecv].nfast = nqty*overlap.isize;
          plan->unpackplan[nrecv].nmid = overlap.jsize;
          plan->unpackplan[nrecv].nslow = overlap.ksize;
          plan->unpackplan[nrecv].nstride_line = nqty*out.isize;
          plan->unpackplan[nrecv].nstride_plane = nqty*out.jsize*out.isize;
          plan->unpackplan[nrecv].nqty = nqty;
        }
        else if (permute == 1) {
          plan->recv_offset[nrecv] = nqty *
            ((overlap.ilo-out.ilo)*out.ksize*out.jsize +
              (overlap.klo-out.klo)*out.jsize + (overlap.jlo-out.jlo));
          plan->unpackplan[nrecv].nfast = overlap.isize;
          plan->unpackplan[nrecv].nmid = overlap.jsize;
          plan->unpackplan[nrecv].nslow = overlap.ksize;
          plan->unpackplan[nrecv].nstride_line = nqty*out.jsize;
          plan->unpackplan[nrecv].nstride_plane = nqty*out.ksize*out.jsize;
          plan->unpackplan[nrecv].nqty = nqty;
        }
        else {
          plan->recv_offset[nrecv] = nqty *
            ((overlap.jlo-out.jlo)*out.isize*out.ksize +
              (overlap.ilo-out.ilo)*out.ksize + (overlap.klo-out.klo));
          plan->unpackplan[nrecv].nfast = overlap.isize;
          plan->unpackplan[nrecv].nmid = overlap.jsize;
          plan->unpackplan[nrecv].nslow = overlap.ksize;
          plan->unpackplan[nrecv].nstride_line = nqty*out.ksize;
          plan->unpackplan[nrecv].nstride_plane = nqty*out.isize*out.ksize;
          plan->unpackplan[nrecv].nqty = nqty;
        }

        plan->recv_size[i] = nqty*overlap.isize*overlap.jsize*overlap.ksize;
        plan->rcvcnts[i] = plan->recv_size[i];
        plan->rdispls[i] = ibuf;
        ibuf += plan->recv_size[i];
        nrecv++;
      } else {
        plan->recv_size[i] = 0;
        plan->rcvcnts[i] = 0;
        plan->rdispls[i] = ibuf;
      }
    }

    // init remaining fields in remap plan

    plan->memory = memory;
    plan->self = 0;

    // if requested, allocate internal scratch space for recvs,
    // only need it if I will receive any data (including self)

    if (memory == 1) {
      if (nrecv > 0) {
        plan->scratch = (FFT_SCALAR*) malloc(nqty*out.isize*out.jsize*out.ksize*sizeof(FFT_SCALAR));
        if (plan->scratch == nullptr) {
          delete plan;
          return nullptr;
        }
      }
    }

    // if using collective and the commringlist is NOT empty create a
    // communicator for the plan based off an MPI_Group created with
    // ranks from the commringlist

    if (plan->commringlen > 0) {
      MPI_Group orig_group, new_group;
      MPI_Comm_group(comm, &orig_group);
      MPI_Group_incl(orig_group, plan->commringlen,
                      plan->commringlist, &new_group);
      MPI_Comm_create(comm, new_group, &plan->comm);
    }

    // if using collective and the comm ring list is empty create
    // a communicator for the plan with an empty group

    else
      MPI_Comm_create(comm, MPI_GROUP_EMPTY, &plan->comm);
  }

  // free locally malloced space

  free(inarray);
  free(outarray);

  // return pointer to plan

  return plan;
}

/* ----------------------------------------------------------------------
   Destroy a 3d remap plan
------------------------------------------------------------------------- */

void remap_3d_destroy_plan(struct remap_plan_3d *plan)
{
  if (plan == nullptr) return;

  // free MPI communicator

  if (!((plan->usecollective) && (plan->commringlen == 0)))
    MPI_Comm_free(&plan->comm);

  // free the plan itself

  delete plan;
}

/* ----------------------------------------------------------------------
   collide 2 sets of indices to determine overlap
   compare bounds of block1 with block2 to see if they overlap
   return 1 if they do and put bounds of overlapping section in overlap
   return 0 if they do not overlap
------------------------------------------------------------------------- */

int remap_3d_collide(struct extent_3d *block1, struct extent_3d *block2,
                     struct extent_3d *overlap)

{
  overlap->ilo = MAX(block1->ilo,block2->ilo);
  overlap->ihi = MIN(block1->ihi,block2->ihi);
  overlap->jlo = MAX(block1->jlo,block2->jlo);
  overlap->jhi = MIN(block1->jhi,block2->jhi);
  overlap->klo = MAX(block1->klo,block2->klo);
  overlap->khi = MIN(block1->khi,block2->khi);

  if (overlap->ilo > overlap->ihi ||
      overlap->jlo > overlap->jhi ||
      overlap->klo > overlap->khi) return 0;

  overlap->isize = overlap->ihi - overlap->ilo + 1;
  overlap->jsize = overlap->jhi - overlap->jlo + 1;
  overlap->ksize = overlap->khi - overlap->klo + 1;

  return 1;
}

// clang-format on
/* 3d remap plan custom constructor. must make certain all pointers are initialized to null */

remap_plan_3d::remap_plan_3d(int _usecollective, int _usenonblocking) :
    sendbuf(nullptr), scratch(nullptr), pack(nullptr), unpack(nullptr), send_offset(nullptr),
    send_size(nullptr), send_proc(nullptr), send_bufloc(nullptr), isend_reqs(nullptr),
    packplan(nullptr), recv_offset(nullptr), recv_size(nullptr), recv_proc(nullptr),
    recv_bufloc(nullptr), request(nullptr), unpackplan(nullptr), commringlist(nullptr),
    sendcnts(nullptr), rcvcnts(nullptr), sdispls(nullptr), rdispls(nullptr)
{
  usecollective = _usecollective;
  usenonblocking = _usenonblocking;
  nrecv = nsend = self = memory = usecollective = usenonblocking = commringlen = 0;
  comm = MPI_COMM_NULL;
}

/* 3d remap plan destructor. free all allocated storage */
remap_plan_3d::~remap_plan_3d()
{
  // free any allocated (= non-null) buffers
#define SAFE_FREE(ptr) \
  if (ptr) free(ptr)

  SAFE_FREE(sendbuf);
  SAFE_FREE(scratch);
  SAFE_FREE(send_offset);
  SAFE_FREE(send_size);
  SAFE_FREE(send_proc);
  SAFE_FREE(send_bufloc);
  SAFE_FREE(isend_reqs);
  SAFE_FREE(packplan);
  SAFE_FREE(recv_offset);
  SAFE_FREE(recv_size);
  SAFE_FREE(recv_proc);
  SAFE_FREE(recv_bufloc);
  SAFE_FREE(request);
  SAFE_FREE(unpackplan);
  SAFE_FREE(commringlist);
  SAFE_FREE(sendcnts);
  SAFE_FREE(rcvcnts);
  SAFE_FREE(rdispls);
  SAFE_FREE(sdispls);
#undef SAFE_FREE
}
