/*
    Theseus - maximum likelihood superpositioning of macromolecular structures

    Copyright (C) 2004-2015 Douglas L. Theobald

    This file is part of THESEUS.

    THESEUS is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as
    published by the Free Software Foundation, either version 3 of
    the License, or (at your option) any later version.

    THESEUS is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public
    License along with THESEUS in the file 'COPYING'. If not, see
    <http://www.gnu.org/licenses/>.

    -/_|:|_|_\-
*/

#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <ctype.h>
#include "CovMat.h"
#include "DLTutils.h"
#include "Error.h"
#include "Embed.h"
#include "DLTmath.h"
#include "pdbIO.h"
#include "Threads.h"
#include "pdbUtils.h"


void
CdsCopyXYZ(Cds *cds1, const Cds *cds2) // DLT FIX MAT COORDS
{
    memcpy(cds1->x, cds2->x, cds2->vlen * sizeof(double));
    memcpy(cds1->y, cds2->y, cds2->vlen * sizeof(double));
    memcpy(cds1->z, cds2->z, cds2->vlen * sizeof(double));
}


void
CdsCopy(Cds *cds1, const Cds *cds2) // DLT FIX MAT COORDS
{
    strncpy(cds1->filename, cds2->filename, FILENAME_MAX-1);
    memcpy(cds1->resSeq, cds2->resSeq, cds2->vlen * sizeof(int));
    memcpy(cds1->x, cds2->x, cds2->vlen * sizeof(double));
    memcpy(cds1->y, cds2->y, cds2->vlen * sizeof(double));
    memcpy(cds1->z, cds2->z, cds2->vlen * sizeof(double));
    memcpy(cds1->o, cds2->o, cds2->vlen * sizeof(double));
}


void
CdsArrayCopy(CdsArray *cdsA1, const CdsArray *cdsA2)
{
    int             i;

    cdsA1->vlen = cdsA2->vlen;
    cdsA1->cnum = cdsA2->cnum;
    cdsA1->pdbA = cdsA2->pdbA;

    for (i = 0; i < cdsA2->cnum; ++i)
        CdsCopyAll(cdsA1->cds[i], cdsA2->cds[i]);

    CdsCopyAll(cdsA1->avecds, cdsA2->avecds);

    memcpy(cdsA1->var, cdsA2->var, cdsA2->vlen * sizeof(double));
    memcpy(cdsA1->w, cdsA2->w, cdsA2->vlen * sizeof(double));
}


void
CdsCopyAll(Cds *cds1, const Cds *cds2) // DLT FIX MAT COORDS --- did it
{
    int             i;
    const int       vlen = cds2->vlen;

    cds1->vlen = vlen;
    cds1->aalen = cds2->aalen;
    cds1->model  = cds2->model;

    strncpy(cds1->filename, cds2->filename, FILENAME_MAX - 1);

    memcpy(cds1->resName_space, cds2->resName_space, vlen * 4 * sizeof(char));
    memcpy(cds1->chainID, cds2->chainID, vlen * sizeof(char));
    memcpy(cds1->resSeq, cds2->resSeq, vlen * sizeof(int));
    memcpy(cds1->wc[0], cds2->wc[0], 5 * vlen * sizeof(double));
//     memcpy(cds1->x, cds2->x, vlen * sizeof(double));
//     memcpy(cds1->y, cds2->y, vlen * sizeof(double));
//     memcpy(cds1->z, cds2->z, vlen * sizeof(double));
//     memcpy(cds1->o, cds2->o, vlen * sizeof(double));
//     memcpy(cds1->b, cds2->b, vlen * sizeof(double));
    memcpy(cds1->nu, cds2->nu, vlen * sizeof(int));

    MatCpySqr(cds1->matrix, (const double **) cds2->matrix, 3);

    memcpy(cds1->center, cds2->center, 3 * sizeof(double));
    memcpy(cds1->last_center, cds2->last_center, 3 * sizeof(double));
    memcpy(cds1->translation, cds2->translation, 3 * sizeof(double));

    cds1->RMSD_from_mean  = cds2->RMSD_from_mean;
    cds1->wRMSD_from_mean = cds2->wRMSD_from_mean;

    for (i = 0; i < 4; ++i)
        cds1->evals[i]  = cds2->evals[i];
}


void
PDBCdsCopyAll(PDBCds *cds1, const PDBCds *cds2)
{
    const int       vlen = cds1->vlen = cds2->vlen;

    cds1->model  = cds2->model;
    strncpy(cds1->filename, cds2->filename, FILENAME_MAX-1);

    memcpy(cds1->record_space, cds2->record_space, vlen * 8 * sizeof(char));
    memcpy(cds1->name_space, cds2->name_space, vlen * 4 * sizeof(char));
    memcpy(cds1->resName_space, cds2->resName_space, vlen * 4 * sizeof(char));
    memcpy(cds1->segID_space, cds2->segID_space, vlen * 8 * sizeof(char));
    memcpy(cds1->element_space, cds2->element_space, vlen * 4 * sizeof(char));
    memcpy(cds1->charge_space, cds2->charge_space, vlen * 4 * sizeof(char));

    memcpy(cds1->serial, cds2->serial, vlen * sizeof(int));
    memcpy(cds1->Hnum, cds2->Hnum, vlen * sizeof(char));
    memcpy(cds1->altLoc, cds2->altLoc, vlen * sizeof(char));
    memcpy(cds1->xchainID, cds2->xchainID, vlen * sizeof(char));
    memcpy(cds1->chainID, cds2->chainID, vlen * sizeof(char));
    memcpy(cds1->resSeq, cds2->resSeq, vlen * sizeof(int));
    memcpy(cds1->iCode, cds2->iCode, vlen * sizeof(char));
    memcpy(cds1->c[0], cds2->c[0], 5 * vlen * sizeof(double));

    memcpy(cds1->nu, cds2->nu, vlen * sizeof(int));

    MatCpySqr(cds1->matrix, (const double **) cds2->matrix, 3);
    memcpy(cds1->translation, cds2->translation, 3 * sizeof(double));
}


void
MatMultCdsMultMatDiag(Cds *outcds, const double **matK, const Cds *cds)
{
    int             i, j;
    const int       vlen = cds->vlen;
    const double   *x = (const double *) cds->x,
                   *y = (const double *) cds->y,
                   *z = (const double *) cds->z;
    double          tmpx, tmpy, tmpz;
    double          matKij;


    for (i = 0; i < vlen; ++i)
    {
        tmpx = tmpy = tmpz = 0.0;
        for (j = 0; j < vlen; ++j)
        {
            matKij = matK[i][j];
            tmpx += matKij * x[j];
            tmpy += matKij * y[j];
            tmpz += matKij * z[j];
        }

        outcds->x[i] = tmpx;
        outcds->y[i] = tmpy;
        outcds->z[i] = tmpz;
    }
}


void
MatDiagMultCdsMultMatDiag(Cds *outcds, const double *wtK, const Cds *cds)
{
    int             i;
    double          wtKi;
    const double   *x = (const double *) cds->x,
                   *y = (const double *) cds->y,
                   *z = (const double *) cds->z;

    for (i = 0; i < cds->vlen; ++i)
    {
        wtKi = wtK[i];

        outcds->x[i] = wtKi * x[i];
        outcds->y[i] = wtKi * y[i];
        outcds->z[i] = wtKi * z[i];
    }
}


void
FillSegIDWithResSeq(PDBCds *cds_to, const Cds *cds_from)
{
    int             i, rn;
    char            resnum[5] ;

    for (i = 0; i < cds_to->vlen; ++i)
    {
         rn = cds_from->resSeq[i];

         if (rn != 0)
         {
             sprintf(resnum, "%04d", rn);
             strncpy(cds_to->segID[i], resnum, 4);
         }
    }
}


/* copies the info for a Cds struct to a PDBCds struct,
   for the most part */
void
CopyCds2PDB(PDBCds *pdbcds, const Cds *cds)
{
    int             i;

    pdbcds->vlen = cds->vlen;
    pdbcds->model = cds->model;
    strncpy(pdbcds->filename, cds->filename, FILENAME_MAX-1);

    MatCpySqr(pdbcds->matrix, (const double **) cds->matrix, 3);

    for (i = 0; i < 3; ++i)
        pdbcds->translation[i]  = cds->translation[i];

    for (i = 0; i < cds->vlen; ++i)
    {
        strcpy(pdbcds->record[i], "ATOM");
        pdbcds->serial[i] = i+1;
        pdbcds->Hnum[i] = ' ';

        if (strncmp(cds->resName[i], "ADE", 3) == 0 ||
            strncmp(cds->resName[i], "CYT", 3) == 0 ||
            strncmp(cds->resName[i], "GUA", 3) == 0 ||
            strncmp(cds->resName[i], "THY", 3) == 0 ||
            strncmp(cds->resName[i], "URA", 3) == 0 ||
            strncmp(cds->resName[i], "  A", 3) == 0 ||
            strncmp(cds->resName[i], "  C", 3) == 0 ||
            strncmp(cds->resName[i], "  G", 3) == 0 ||
            strncmp(cds->resName[i], "  T", 3) == 0 ||
            strncmp(cds->resName[i], " DA", 3) == 0 || /* remediated PDB residue names */
            strncmp(cds->resName[i], " DC", 3) == 0 || /* remediated PDB residue names */
            strncmp(cds->resName[i], " DG", 3) == 0 || /* remediated PDB residue names */
            strncmp(cds->resName[i], " DT", 3) == 0 || /* remediated PDB residue names */
            strncmp(cds->resName[i], " DI", 3) == 0 || /* remediated PDB residue names */
            strncmp(cds->resName[i], " DU", 3) == 0 || /* remediated PDB residue names */
            strncmp(cds->resName[i], "  U", 3) == 0)
        {
            strcpy(pdbcds->name[i], "P  ");
        }
        else
        {
            strcpy(pdbcds->name[i], "CA ");
        }

        pdbcds->altLoc[i]     = ' ';
        strncpy(pdbcds->resName[i], cds->resName[i], 3);
        pdbcds->xchainID[i]   = ' ';
        pdbcds->chainID[i]    = cds->chainID[i];
        pdbcds->resSeq[i]     = cds->resSeq[i];
        pdbcds->iCode[i]      = ' ';
        pdbcds->x[i]          = cds->x[i];
        pdbcds->y[i]          = cds->y[i];
        pdbcds->z[i]          = cds->z[i];
        pdbcds->occupancy[i]  = cds->o[i];
        pdbcds->tempFactor[i] = cds->b[i];
        strncpy(pdbcds->segID[i], "    ", 4);
        strncpy(pdbcds->element[i], "  ", 2);
        strncpy(pdbcds->charge[i], "  ", 2);
    }
}


int
NMRValidPDBCdsArray(PDBCdsArray *pdbA)
{
    int             ii, jj;
    int             vlen = pdbA->cds[0]->vlen;
    char            ch0, ch1, ch2;

    // Do they all have the same length? If not, return zero.
    for (ii = 1; ii < pdbA->cnum; ++ii)
        if (pdbA->cds[ii]->vlen != vlen)
        {
            fprintf(stderr,
                    "\n  ERROR20: PDB coordinates 0 and %d are unequal length [%d vs %d]. \n\n",
                    ii, vlen, pdbA->cds[ii]->vlen);
            exit(EXIT_FAILURE);
        }

    // Do they also all have the same sequence? If not, return zero.
    for (ii = 0; ii < vlen; ++ii)
    {
        ch0 = pdbA->cds[0]->resName[ii][0];
        ch1 = pdbA->cds[0]->resName[ii][1];
        ch2 = pdbA->cds[0]->resName[ii][2];
        for (jj = 1; jj < pdbA->cnum; ++jj)
            if((pdbA->cds[jj]->resName[ii][0] != ch0)
            || (pdbA->cds[jj]->resName[ii][1] != ch1)
            || (pdbA->cds[jj]->resName[ii][2] != ch2))
            {
                fprintf(stderr,
                        "\n  ERROR20: sequence %d is different than 0 ['%c%c%c' vs '%c%c%c']. \n\n", jj,
                        pdbA->cds[jj]->resName[ii][0], pdbA->cds[jj]->resName[ii][1], pdbA->cds[jj]->resName[ii][2],
                        ch0, ch1, ch2);
                exit(EXIT_FAILURE);
            }
    }

    return(vlen);
}


int
NMRCheckPDBCdsArray(PDBCdsArray *pdbA)
{
    int             i;
    int             vlen = pdbA->cds[0]->vlen;

    for(i = 1; i < pdbA->cnum; ++i)
    {
        if (pdbA->cds[i]->vlen != vlen)
        {
            fprintf(stderr,
                    "\n  WARNING20: PDB coordinates %d and %d are unequal length [%d vs %d]. \n\n",
                    0, i, vlen, pdbA->cds[i]->vlen);
        }
    }

    return(vlen);
}


/* matrix and translation need to be in PDBCds structure */
void
TransformPDBCdsIp(PDBCds *pdbcds)
{
    int             i;
    double          xt, yt, zt;
    double         *x = pdbcds->x, *y = pdbcds->y, *z = pdbcds->z;
    const double    transx = pdbcds->translation[0];
    const double    transy = pdbcds->translation[1];
    const double    transz = pdbcds->translation[2];
    const double  **rmat = (const double **) pdbcds->matrix;
    const double    rmat00 = rmat[0][0], rmat01 = rmat[0][1], rmat02 = rmat[0][2],
                    rmat10 = rmat[1][0], rmat11 = rmat[1][1], rmat12 = rmat[1][2],
                    rmat20 = rmat[2][0], rmat21 = rmat[2][1], rmat22 = rmat[2][2];

    for (i = 0; i < pdbcds->vlen; ++i)
    {
        xt = x[i] - transx;
        yt = y[i] - transy;
        zt = z[i] - transz;

        x[i] = (xt * rmat00) + (yt * rmat10) + (zt * rmat20);
        y[i] = (xt * rmat01) + (yt * rmat11) + (zt * rmat21);
        z[i] = (xt * rmat02) + (yt * rmat12) + (zt * rmat22);
    }

    if (algo->scale > 0)
    {
        double scale = pdbcds->scale;
        for (i = 0; i < pdbcds->vlen; ++i)
        {
            x[i] *= scale;
            y[i] *= scale;
            z[i] *= scale;
        }
    }
}


void
RotateCdsOp(double **c2, const double **c1, const double **rmat, const int vlen)
{
    int             i;
    double          xt, yt, zt;
    const double   *x1 = c1[0], *y1 = c1[1], *z1 = c1[2];
    double         *x2 = c2[0], *y2 = c2[1], *z2 = c2[2];
    const double    rmat00 = rmat[0][0], rmat01 = rmat[0][1], rmat02 = rmat[0][2],
                    rmat10 = rmat[1][0], rmat11 = rmat[1][1], rmat12 = rmat[1][2],
                    rmat20 = rmat[2][0], rmat21 = rmat[2][1], rmat22 = rmat[2][2];

    for (i = 0; i < vlen; ++i)
    {
        xt = x1[i];
        yt = y1[i];
        zt = z1[i];

        x2[i] = xt * rmat00 + yt * rmat10 + zt * rmat20;
        y2[i] = xt * rmat01 + yt * rmat11 + zt * rmat21;
        z2[i] = xt * rmat02 + yt * rmat12 + zt * rmat22;
    }
}


/* This is equivalent to XR, where X = (k x 3) and R = (3 x 3),
   where the convention is (row x col).
   Recall that x[i] = X[i][0], y[i] = X[i][1], z[i] = X[i][2] */
void
RotateCdsIp(Cds *cds, const double **rmat)
{
    int             i;
    double          xt, yt, zt;
    double         *x = cds->x, *y = cds->y, *z = cds->z;
    const double    rmat00 = rmat[0][0], rmat01 = rmat[0][1], rmat02 = rmat[0][2],
                    rmat10 = rmat[1][0], rmat11 = rmat[1][1], rmat12 = rmat[1][2],
                    rmat20 = rmat[2][0], rmat21 = rmat[2][1], rmat22 = rmat[2][2];

    for (i = 0; i < cds->vlen; ++i)
    {
        xt = x[i];
        yt = y[i];
        zt = z[i];

        x[i] = (xt * rmat00) + (yt * rmat10) + (zt * rmat20);
        y[i] = (xt * rmat01) + (yt * rmat11) + (zt * rmat21);
        z[i] = (xt * rmat02) + (yt * rmat12) + (zt * rmat22);
    }
}


/* This is equivalent to XR, where X = (k x 3) and R = (3 x 3),
   where the convention is (row x col).
   Recall that x[i] = X[i][0], y[i] = X[i][1], z[i] = X[i][2] */
void
RotateCdsIp2(double **c1, const int vlen, const double **rmat)
{
    int             i;
    double          xt, yt, zt;
    double         *x = c1[0], *y = c1[1], *z = c1[2];
    const double    rmat00 = rmat[0][0], rmat01 = rmat[0][1], rmat02 = rmat[0][2],
                    rmat10 = rmat[1][0], rmat11 = rmat[1][1], rmat12 = rmat[1][2],
                    rmat20 = rmat[2][0], rmat21 = rmat[2][1], rmat22 = rmat[2][2];

    for (i = 0; i < vlen; ++i)
    {
        xt = x[i];
        yt = y[i];
        zt = z[i];

        x[i] = (xt * rmat00) + (yt * rmat10) + (zt * rmat20);
        y[i] = (xt * rmat01) + (yt * rmat11) + (zt * rmat21);
        z[i] = (xt * rmat02) + (yt * rmat12) + (zt * rmat22);
    }
}


void
TransformCdsIp(Cds *cds)
{
    const double  **rmat = (const double **) cds->matrix;
    const double    transx = cds->center[0];
    const double    transy = cds->center[1];
    const double    transz = cds->center[2];
    int             i;
    double          xt, yt, zt;
    double         *x = cds->x, *y = cds->y, *z = cds->z;
    const double    rmat00 = rmat[0][0], rmat01 = rmat[0][1], rmat02 = rmat[0][2],
                    rmat10 = rmat[1][0], rmat11 = rmat[1][1], rmat12 = rmat[1][2],
                    rmat20 = rmat[2][0], rmat21 = rmat[2][1], rmat22 = rmat[2][2];

    for (i = 0; i < cds->vlen; ++i)
    {
        xt = x[i] + transx;
        yt = y[i] + transy;
        zt = z[i] + transz;

        x[i] = (xt * rmat00) + (yt * rmat10) + (zt * rmat20);
        y[i] = (xt * rmat01) + (yt * rmat11) + (zt * rmat21);
        z[i] = (xt * rmat02) + (yt * rmat12) + (zt * rmat22);
    }
}


void
ScaleCds(Cds *cds, const double scale)
{
    int             i;
    double         *x = cds->x, *y = cds->y, *z = cds->z;

    for (i = 0; i < cds->vlen; ++i)
    {
        x[i] *= scale;
        y[i] *= scale;
        z[i] *= scale;
    }
}


void
CenMass(Cds *cds)
{
    int             i;
    const int       vlen = cds->vlen;
    double          xsum, ysum, zsum;
    const double   *x = (const double *) cds->x,
                   *y = (const double *) cds->y,
                   *z = (const double *) cds->z;

    xsum = ysum = zsum = 0.0;
    for (i = 0; i < vlen; ++i)
    {
        xsum += x[i];
        ysum += y[i];
        zsum += z[i];
    }

    cds->center[0] = xsum / vlen;
    cds->center[1] = ysum / vlen;
    cds->center[2] = zsum / vlen;
}


void
CenMass2(const double **cds, const int vlen, double *center)
{
    int             i;
    double          tempx, tempy, tempz;
    const double   *x = cds[0],
                   *y = cds[1],
                   *z = cds[2];

    tempx = tempy = tempz = 0.0;
    for (i = 0; i < vlen; ++i)
    {
        tempx += x[i];
        tempy += y[i];
        tempz += z[i];
    }

    center[0] = tempx / vlen;
    center[1] = tempy / vlen;
    center[2] = tempz / vlen;
}


void
CenMassWt2(const double **cds, const double *wts, const int vlen, double *center)
{
    int             i;
    double          tempx, tempy, tempz;
    double          wti, wtsum;
    const double   *x = cds[0],
                   *y = cds[1],
                   *z = cds[2];

    tempx = tempy = tempz = wtsum = 0.0;
    for (i = 0; i < vlen; ++i)
    {
        wti = wts[i];
        wtsum += wti;
        tempx += (wti * x[i]);
        tempy += (wti * y[i]);
        tempz += (wti * z[i]);
    }

    center[0] = tempx / wtsum;
    center[1] = tempy / wtsum;
    center[2] = tempz / wtsum;
}


void
CenMassWtNu2(const double **cds, const double **ave, const int *nu, const double *wts, const int vlen, const double **rmat, double *center)
{
    int             i, nui;
    double          tempx, tempy, tempz;
    double          wti, wtsum;
    const double   *x = cds[0],
                   *y = cds[1],
                   *z = cds[2];
    const double   *ax = ave[0],
                   *ay = ave[1],
                   *az = ave[2];
    const double    rmat00 = rmat[0][0], rmat01 = rmat[0][1], rmat02 = rmat[0][2],
                    rmat10 = rmat[1][0], rmat11 = rmat[1][1], rmat12 = rmat[1][2],
                    rmat20 = rmat[2][0], rmat21 = rmat[2][1], rmat22 = rmat[2][2];

    tempx = tempy = tempz = wtsum = 0.0;
    for (i = 0; i < vlen; ++i)
    {
        wti = wts[i];
        nui = nu[i];
        wtsum += wti * nui;
        // DLT OP this is inefficient as hell
        tempx += wti * (nui*x[i] + (1-nui) * ((ax[i]*rmat00) + (ay[i]*rmat01) + (az[i]*rmat02)));
        tempy += wti * (nui*y[i] + (1-nui) * ((ax[i]*rmat10) + (ay[i]*rmat11) + (az[i]*rmat12)));
        tempz += wti * (nui*z[i] + (1-nui) * ((ax[i]*rmat20) + (ay[i]*rmat21) + (az[i]*rmat22)));
    }

    center[0] = tempx / wtsum;
    center[1] = tempy / wtsum;
    center[2] = tempz / wtsum;
}


void
CenMassWtIp(Cds *cds, const double *wts)
{
    int             i;
    double          tempx, tempy, tempz;
    double          wti, wtsum;
    const double   *x = (const double *) cds->x,
                   *y = (const double *) cds->y,
                   *z = (const double *) cds->z;

    tempx = tempy = tempz = wtsum = 0.0;
    for (i = 0; i < cds->vlen; ++i)
    {
        wti = wts[i];
//        printf("wt[%3d] = %8.3f\n", i, wti);

        wtsum += wti;
        tempx += (wti * x[i]);
        tempy += (wti * y[i]);
        tempz += (wti * z[i]);
    }

    cds->center[0] = tempx / wtsum;
    cds->center[1] = tempy / wtsum;
    cds->center[2] = tempz / wtsum;

/*     printf("wtsum = %8.3f\n", wtsum); */
/*     fflush(NULL); */

/*      printf("\nDT: % 8.3f % 8.3f % 8.3f\n",  */
/*            cds->center[0], cds->center[1], cds->center[2]);  */
/*      fflush(NULL);  */
}


void
CenMassCovOp(Cds *cds, const CdsArray *weights)
{
    double          tempx, tempy, tempz;
    int             i, j;
    double         *covx = cds->covx,
                   *covy = cds->covy,
                   *covz = cds->covz;
    double          wtsum;

/* #include "internmat.h" */
/* for (i = 0; i < cds->vlen; ++i) */
/*     for (j = 0; j < cds->vlen; ++j) */
/*         weights->CovMat[i][j] = internmat[i][j]; */
/*  */
/* CovInvWeightLAPACK((CdsArray *) weights); */

    wtsum = 0.0;
    for (i = 0; i < cds->vlen; ++i)
        for (j = 0; j < cds->vlen; ++j)
            wtsum += weights->WtMat[i][j];

    tempx = tempy = tempz = 0.0;
    for (i = 0; i < cds->vlen; ++i)
    {
        tempx += covx[i];
        tempy += covy[i];
        tempz += covz[i];
    }

    cds->center[0] = tempx / wtsum;
    cds->center[1] = tempy / wtsum;
    cds->center[2] = tempz / wtsum;

/*     printf("\n% f % f % f", */
/*            cds->center[0], cds->center[1], cds->center[2]); */
/*     fflush(NULL); */
}


/* calculate inv covariance matrix weighted cds
   \Sigma^-1 * \CdsMat */
void
CalcCovCds(Cds *cds, const double **wtmat)
{
    int             i, k;
    double         *covx = cds->covx,
                   *covy = cds->covy,
                   *covz = cds->covz;
    const double   *x = (const double *) cds->x,
                   *y = (const double *) cds->y,
                   *z = (const double *) cds->z;
    double          wtmatik;

    for (i = 0; i < cds->vlen; ++i)
    {
        covx[i] = covy[i] = covz[i] = 0.0;

        for (k = 0; k < cds->vlen; ++k)
        {
            wtmatik = wtmat[i][k];

            covx[i] += (wtmatik * x[k]);
            covy[i] += (wtmatik * y[k]);
            covz[i] += (wtmatik * z[k]);
        }
    }
}


void
CenMassCov(Cds *cds, const double **wtmat)
{
    double          tempx, tempy, tempz;
    int             i, j;
    double         *covx = cds->covx,
                   *covy = cds->covy,
                   *covz = cds->covz;
    double          vlen = cds->vlen;
    double          wtsum;

    CalcCovCds(cds, wtmat);

    wtsum = 0.0;
    for (i = 0; i < vlen; ++i)
        for (j = 0; j < vlen; ++j)
            wtsum += wtmat[i][j];

    tempx = tempy = tempz = 0.0;
    for (i = 0; i < vlen; ++i)
    {
        tempx += covx[i];
        tempy += covy[i];
        tempz += covz[i];
    }

    cds->center[0] = tempx / wtsum;
    cds->center[1] = tempy / wtsum;
    cds->center[2] = tempz / wtsum;
}


/* calculate inv covariance matrix weighted cds
   \Sigma^-1 * \CdsMat */
static void
CalcCovCds2(double **cc, const double **c, const double **wtmat, const int vlen)
{
    int             i, k;
    double         *covx = cc[0],
                   *covy = cc[1],
                   *covz = cc[2];
    const double   *x = c[0],
                   *y = c[1],
                   *z = c[2];
    double          wtmatik;
    //double          xk, yk, zk;
    double          covxi, covyi, covzi;

    for (i = 0; i < vlen; ++i)
    {
        covxi = covyi = covzi = 0.0;
        for (k = 0; k < vlen; ++k)
        {
            wtmatik = wtmat[i][k];

            covxi += wtmatik * x[k];
            covyi += wtmatik * y[k];
            covzi += wtmatik * z[k];
        }

        covx[i] = covxi;
        covy[i] = covyi;
        covz[i] = covzi;
    }
}


void
CenMassCov2(const double **c, double **cc, const double **wtmat, const int vlen, double *center)
{
    double          tempx, tempy, tempz;
    int             i, j;
    double         *covx = cc[0],
                   *covy = cc[1],
                   *covz = cc[2];
    double          wtsum;

    CalcCovCds2(cc, c, wtmat, vlen);

    // Alternatively, we could normalize only once in HierarchVars
    wtsum = 0.0;
    for (i = 0; i < vlen; ++i)
        for (j = 0; j < vlen; ++j)
            wtsum += wtmat[i][j];

    //printf("wtsum: %f\n", wtsum);

    tempx = tempy = tempz = 0.0;
    for (i = 0; i < vlen; ++i)
    {
        tempx += covx[i];
        tempy += covy[i];
        tempz += covz[i];
    }

    center[0] = tempx / wtsum;
    center[1] = tempy / wtsum;
    center[2] = tempz / wtsum;
}


void
CenMassNuVec(const double **c, const int *nu, double *cenmass, const int vlen)
{
    int             i;
    double          tempx, tempy, tempz, nui, nusum;
    const double   *x = (const double *) c[0],
                   *y = (const double *) c[1],
                   *z = (const double *) c[2];

    tempx = tempy = tempz = nusum = 0.0;
    for (i = 0; i < vlen; ++i)
    {
        nui = nu[i];
        nusum += nui;
        tempx += (nui * x[i]);
        tempy += (nui * y[i]);
        tempz += (nui * z[i]);
    }

    cenmass[0] = tempx / nusum;
    cenmass[1] = tempy / nusum;
    cenmass[2] = tempz / nusum;
}


void
CenMassWtIpNu(Cds *cds, const double *wts)
{
    int             i;
    double          tempx, tempy, tempz;
    double          wti, wtsum;
    const double   *x = (const double *) cds->x,
                   *y = (const double *) cds->y,
                   *z = (const double *) cds->z;
    const int      *nu = (const int *) cds->nu;

    tempx = tempy = tempz = wtsum = 0.0;
    for (i = 0; i < cds->vlen; ++i)
    {
        wti = wts[i] * nu[i];
        wtsum += wti;
        tempx += (wti * x[i]);
        tempy += (wti * y[i]);
        tempz += (wti * z[i]);
    }

    cds->center[0] = tempx / wtsum;
    cds->center[1] = tempy / wtsum;
    cds->center[2] = tempz / wtsum;
}


void
ApplyCenter(Cds *cds, const double cenx, const double ceny, const double cenz)
{
    int             i;
    double         *x = cds->x, *y = cds->y, *z = cds->z;

    for (i = 0; i < cds->vlen; ++i)
    {
        x[i] -= cenx;
        y[i] -= ceny;
        z[i] -= cenz;
    }
}


void
ApplyCenterIp(Cds *cds)
{
    int             i;
    double         *x = cds->x, *y = cds->y, *z = cds->z;
    const double    cenx = cds->center[0],
                    ceny = cds->center[1],
                    cenz = cds->center[2];

    for (i = 0; i < cds->vlen; ++i)
    {
        x[i] -= cenx;
        y[i] -= ceny;
        z[i] -= cenz;
    }
}


void
ApplyNegCenterIp(Cds *cds)
{
    int             i;
    double         *x = cds->x, *y = cds->y, *z = cds->z;
    const double    cenx = cds->center[0],
                    ceny = cds->center[1],
                    cenz = cds->center[2];

    for (i = 0; i < cds->vlen; ++i)
    {
        x[i] += cenx;
        y[i] += ceny;
        z[i] += cenz;
    }
}


/* apply the center from 'cds_base' to 'cds' */
void
ApplyCenterOp(Cds *cds1, const Cds *cds2)
{
    int             i;
    double         *x1 = cds1->x, *y1 = cds1->y, *z1 = cds1->z;
    const double   *x2 = cds2->x, *y2 = cds2->y, *z2 = cds2->z;
    const double    cenx = cds2->center[0],
                    ceny = cds2->center[1],
                    cenz = cds2->center[2];

    for (i = 0; i < cds1->vlen; ++i)
    {
        x1[i] = x2[i] - cenx;
        y1[i] = y2[i] - ceny;
        z1[i] = z2[i] - cenz;
    }
}


void
TranslateCdsOp2(double **cds2, const double **cds1, const int vlen, const double *center)
{
    int             i;
    const double   *x1 = cds1[0], *y1 = cds1[1], *z1 = cds1[2];
    double         *x2 = cds2[0], *y2 = cds2[1], *z2 = cds2[2];
    const double    cenx = center[0],
                    ceny = center[1],
                    cenz = center[2];

    for (i = 0; i < vlen; ++i)
    {
        x2[i] = x1[i] - cenx;
        y2[i] = y1[i] - ceny;
        z2[i] = z1[i] - cenz;
    }
}


void
TransCdsIp(double **c, const double *trans, const int vlen)
{
    int             i;
    double         *x = c[0], *y = c[1], *z = c[2];
    const double    transx = trans[0],
                    transy = trans[1],
                    transz = trans[2];

    for (i = 0; i < vlen; ++i)
    {
        x[i] += transx;
        y[i] += transy;
        z[i] += transz;
    }
}


void
NegTransCdsIp(double **c, const double *trans, const int vlen)
{
    int             i;
    double         *x = c[0], *y = c[1], *z = c[2];
    const double    transx = trans[0],
                    transy = trans[1],
                    transz = trans[2];

    for (i = 0; i < vlen; ++i)
    {
        x[i] -= transx;
        y[i] -= transy;
        z[i] -= transz;
    }
}


/* Copy average cds to atoms with 0 occupancy, part of the EM algorithm's
   E-step for estimating missing data */
void
EM_MissingCds(CdsArray *cdsA)
{
    int             i, j;
    double         *avex = cdsA->avecds->x, *avey = cdsA->avecds->y,
                   *avez = cdsA->avecds->z;
    const Cds     **cds = (const Cds **) cdsA->cds;
    Cds            *cdsi = NULL;

    for (i = 0; i < cdsA->cnum; ++i)
    {
        cdsi = (Cds *) cds[i];

        for (j = 0; j < cdsA->vlen; ++j)
        {
            if (cdsi->nu[j] == 0)
            {
                cdsi->x[j] = avex[j];
                cdsi->y[j] = avey[j];
                cdsi->z[j] = avez[j];
            }
        }
    }
}


void
EM_MissingCdsOp(CdsArray *baseA, CdsArray *scratchA)
{
    int             i, j;
    double        **rmat = NULL;
    double         *avex = scratchA->avecds->x,
                   *avey = scratchA->avecds->y,
                   *avez = scratchA->avecds->z;
    const Cds     **cds = (const Cds **) baseA->cds;
    Cds            *cdsi = NULL;

    double          rmat00, rmat01, rmat02,
                    rmat10, rmat11, rmat12,
                    rmat20, rmat21, rmat22;

    for (i = 0; i < baseA->cnum; ++i)
    {
        cdsi = (Cds *) cds[i];

        rmat = scratchA->cds[i]->matrix;

        rmat00 = rmat[0][0], rmat01 = rmat[0][1], rmat02 = rmat[0][2],
        rmat10 = rmat[1][0], rmat11 = rmat[1][1], rmat12 = rmat[1][2],
        rmat20 = rmat[2][0], rmat21 = rmat[2][1], rmat22 = rmat[2][2];

        for (j = 0; j < baseA->vlen; ++j)
        {
            if (cdsi->nu[j] == 0)
            {
                cdsi->x[j] = avex[j]*rmat00 + avey[j]*rmat01 + avez[j]*rmat02;
                cdsi->y[j] = avex[j]*rmat10 + avey[j]*rmat11 + avez[j]*rmat12;
                cdsi->z[j] = avex[j]*rmat20 + avey[j]*rmat21 + avez[j]*rmat22;

                cdsi->x[j] -= scratchA->cds[i]->translation[0];
                cdsi->y[j] -= scratchA->cds[i]->translation[1];
                cdsi->z[j] -= scratchA->cds[i]->translation[2];
            }
        }
    }
}


/* Calculate the ML estimate of a hierarchical mean, where the atoms
   are normally distributed with hyper-mean zero */
/* See also below, which is probably more valid (only the weighted mean has zero centroid) */
/* 2009-06-11 */
double
HierAveCds2(CdsArray *cdsA)
{
    int             i, j;
    double         *avex = cdsA->avecds->x,
                   *avey = cdsA->avecds->y,
                   *avez = cdsA->avecds->z;
    const int       cnum = cdsA->cnum, vlen = cdsA->vlen;
    const Cds     **cds = (const Cds **) cdsA->cds;
    Cds            *cdsj = NULL;
    double          invcnum, psi;


    psi = 0.0;
    for (i = 0; i < vlen; ++i)
        psi += (avex[i]*avex[i] + avey[i]*avey[i] + avez[i]*avez[i]);
    psi /= (3.0 * vlen);

    memset(avex, 0, vlen * sizeof(double));
    memset(avey, 0, vlen * sizeof(double));
    memset(avez, 0, vlen * sizeof(double));

    for (j = 0; j < cnum; ++j)
    {
        cdsj = (Cds *) cds[j];

        for (i = 0; i < vlen; ++i)
        {
            avex[i] += cdsj->x[i];
            avey[i] += cdsj->y[i];
            avez[i] += cdsj->z[i];
        }
    }

    for (i = 0; i < vlen; ++i)
    {
        invcnum = 1.0 / ((double) cnum + cdsA->var[i] / psi);
        //printf("\ninvcnum = %e  %e", invcnum, 1.0/cnum);

        avex[i] *= invcnum;
        avey[i] *= invcnum;
        avez[i] *= invcnum;
    }

    return(psi);
}


/* Calculate the ML estimate of a hierarchical mean, where the variance-weighted atoms
   are normally distributed with hyper-mean zero */
/* 2009-06-11 */
double
HierAveCds(CdsArray *cdsA)
{
    int             i, j;
    double         *avex = cdsA->avecds->x,
                   *avey = cdsA->avecds->y,
                   *avez = cdsA->avecds->z;
    const int       cnum = cdsA->cnum, vlen = cdsA->vlen;
    const Cds     **cds = (const Cds **) cdsA->cds;
    Cds            *cdsj = NULL;
    double          invcnum, psi, norm;


    psi = norm = 0.0;
    for (i = 0; i < vlen; ++i)
    {
        norm += 1.0 / cdsA->var[i];
        psi += (avex[i]*avex[i]/cdsA->var[i] +
                avey[i]*avey[i]/cdsA->var[i] +
                avez[i]*avez[i]/cdsA->var[i]);
    }
    psi /= (3.0 * norm);

    memset(avex, 0, vlen * sizeof(double));
    memset(avey, 0, vlen * sizeof(double));
    memset(avez, 0, vlen * sizeof(double));

    for (j = 0; j < cnum; ++j)
    {
        cdsj = (Cds *) cds[j];

        for (i = 0; i < vlen; ++i)
        {
            avex[i] += cdsj->x[i];
            avey[i] += cdsj->y[i];
            avez[i] += cdsj->z[i];
        }
    }

    for (i = 0; i < vlen; ++i)
    {
        invcnum = 1.0 / ((double) cnum + 1.0 / psi);
        //printf("\ninvcnum = %e  %e", invcnum, 1.0/cnum);

        avex[i] *= invcnum;
        avey[i] *= invcnum;
        avez[i] *= invcnum;
    }

    return(psi);
}


void
AveCds(CdsArray *cdsA)
{
    int             i, j;
    double         *avex = cdsA->avecds->x,
                   *avey = cdsA->avecds->y,
                   *avez = cdsA->avecds->z;
    const int       cnum = cdsA->cnum, vlen = cdsA->vlen;
    const Cds     **cds = (const Cds **) cdsA->cds;
    Cds            *cdsj = NULL;
    double          invcnum = 1.0 / (double) cnum;

    memset(avex, 0, vlen * sizeof(double));
    memset(avey, 0, vlen * sizeof(double));
    memset(avez, 0, vlen * sizeof(double));

    for (j = 0; j < cnum; ++j)
    {
        cdsj = (Cds *) cds[j];

        for (i = 0; i < vlen; ++i)
        {
            avex[i] += cdsj->x[i];
            avey[i] += cdsj->y[i];
            avez[i] += cdsj->z[i];
        }
    }

    for (i = 0; i < vlen; ++i)
    {
        avex[i] *= invcnum;
        avey[i] *= invcnum;
        avez[i] *= invcnum;
    }
}


void
AveCdsTB(CdsArray *cdsA, int omit)
{
    int             i, j;
    double         *avex = cdsA->avecds->x,
                   *avey = cdsA->avecds->y,
                   *avez = cdsA->avecds->z;
    const int       cnum = cdsA->cnum, vlen = cdsA->vlen;
    const Cds     **cds = (const Cds **) cdsA->cds;
    Cds            *cdsj = NULL;
    double          invcnum = 1.0 / (double) (cnum-1.0);

    memset(avex, 0, vlen * sizeof(double));
    memset(avey, 0, vlen * sizeof(double));
    memset(avez, 0, vlen * sizeof(double));

    for (j = 0; j < cnum; ++j)
    {

        if (j == omit)
            continue;

        cdsj = (Cds *) cds[j];

        for (i = 0; i < vlen; ++i)
        {
            avex[i] += cdsj->x[i];
            avey[i] += cdsj->y[i];
            avez[i] += cdsj->z[i];
        }
    }

    for (i = 0; i < vlen; ++i)
    {
        avex[i] *= invcnum;
        avey[i] *= invcnum;
        avez[i] *= invcnum;
    }
}


static void
*AveCdsPth(void *avedata_ptr)
{
    AveData        *avedata = (AveData *) avedata_ptr;
    int             i, j;
    double          xtmp, ytmp, ztmp;
    double         *avex = avedata->cdsA->avecds->x,
                   *avey = avedata->cdsA->avecds->y,
                   *avez = avedata->cdsA->avecds->z;
    const int       cnum = avedata->cnum;
    double          invcnum = 1.0 / cnum;
    const Cds     **cds = (const Cds **) avedata->cdsA->cds;
    Cds            *cdsj = NULL;

    for (i = avedata->start; i < avedata->end; ++i)
    {
        xtmp = ytmp = ztmp = 0.0;
        for (j = 0; j < cnum; ++j)
        {
            cdsj = (Cds *) cds[j];
            xtmp += cdsj->x[i];
            ytmp += cdsj->y[i];
            ztmp += cdsj->z[i];
        }

        avex[i] = xtmp * invcnum;
        avey[i] = ytmp * invcnum;
        avez[i] = ztmp * invcnum;
    }

    pthread_exit((void *) 0);
}


void
AveCds_pth(CdsArray *cdsA, AveData **avedata, pthread_t *callThd,
           pthread_attr_t *attr, const int thrdnum)
{
    const int       cnum = cdsA->cnum, vlen = cdsA->vlen;
    int             i, rc = 0, incr;

    incr = vlen / thrdnum;

    for (i = 0; i < thrdnum - 1; ++i)
    {
        avedata[i]->cdsA = cdsA;
        avedata[i]->start = i * incr;
        avedata[i]->end = i*incr + incr;
        avedata[i]->vlen = vlen;
        avedata[i]->cnum = cnum;

        rc = pthread_create(&callThd[i], attr, AveCdsPth, (void *) avedata[i]);

        if (rc)
        {
            printf("ERROR811: return code from pthread_create() %d is %d\n", i, rc);
            exit(EXIT_FAILURE);
        }
    }

    avedata[thrdnum - 1]->cdsA = cdsA;
    avedata[thrdnum - 1]->start = (thrdnum - 1) * incr;
    avedata[thrdnum - 1]->end = vlen;
    avedata[thrdnum - 1]->vlen = vlen;
    avedata[thrdnum - 1]->cnum = cnum;

    rc = pthread_create(&callThd[thrdnum - 1], attr, AveCdsPth, (void *) avedata[thrdnum - 1]);

    if (rc)
    {
        printf("ERROR811: return code from pthread_create() %d is %d\n", i, rc);
        exit(EXIT_FAILURE);
    }

    for (i = 0; i < thrdnum; ++i)
    {
        rc = pthread_join(callThd[i], (void **) NULL);

        if (rc)
        {
            printf("ERROR812: return code from pthread_join() %d is %d\n", i, rc);
            exit(EXIT_FAILURE);
        }
    }

    return;
}


void
AveCdsNu2(CdsArray *cdsA)
{
    int             i, j;
    double         *avex = cdsA->avecds->x,
                   *avey = cdsA->avecds->y,
                   *avez = cdsA->avecds->z;
    const int       cnum = cdsA->cnum, vlen = cdsA->vlen;
    const Cds     **cds = (const Cds **) cdsA->cds;
    Cds            *cdsj = NULL;
    double          nu, nusum, invnu;

    memset(avex, 0, vlen * sizeof(double));
    memset(avey, 0, vlen * sizeof(double));
    memset(avez, 0, vlen * sizeof(double));

    for (i = 0; i < vlen; ++i)
    {
        nusum = 0.0;
        for (j = 0; j < cnum; ++j)
        {
            cdsj = (Cds *) cds[j];
            nu = cdsj->nu[i];
            if (nu > 0.0)
            {
                nusum += nu;
                avex[i] += cdsj->x[i];
                avey[i] += cdsj->y[i];
                avez[i] += cdsj->z[i];
            }
        }

        invnu = 1.0 / nusum;

//printf("nusum[%3d]: %f\n", i, nusum);

        avex[i] *= invnu;
        avey[i] *= invnu;
        avez[i] *= invnu;
    }
}


//  More efficient version than above (~5X as fast?)
void
AveCdsNu(CdsArray *cdsA)
{
    int             i, j;
    double         *avex = cdsA->avecds->x,
                   *avey = cdsA->avecds->y,
                   *avez = cdsA->avecds->z;
    const int       cnum = cdsA->cnum, vlen = cdsA->vlen;
    const Cds     **cds = (const Cds **) cdsA->cds;
    Cds            *cdsj = NULL;
    double          nu, invnu;
    const int      *df = (const int *) cdsA->df;

    memset(avex, 0, vlen * sizeof(double));
    memset(avey, 0, vlen * sizeof(double));
    memset(avez, 0, vlen * sizeof(double));

    for (j = 0; j < cnum; ++j)
    {
        cdsj = (Cds *) cds[j];

        for (i = 0; i < vlen; ++i)
        {
            nu = cdsj->nu[i];
            if (nu > 0.0)
            {
                avex[i] += cdsj->x[i];
                avey[i] += cdsj->y[i];
                avez[i] += cdsj->z[i];
            }
        }
    }

    for (i = 0; i < vlen; ++i)
    {
        invnu = 1.0 / df[i];

//printf("nusum[%3d]: %f\n", i, nusum);

        avex[i] *= invnu;
        avey[i] *= invnu;
        avez[i] *= invnu;
    }
}


static void
CdsInnProd(Cds *cds)
{
    /* (i x k)(k x j) = (i x j) */
    /* (3 x N)(N x 3) = (3 x 3) */
    int             k;
    double        **ip = NULL;
    const double   *x = (const double *) cds->x,
                   *y = (const double *) cds->y,
                   *z = (const double *) cds->z;
    double          xk, yk, zk;

    ip = cds->innerprod;

    memset(ip[0], 0, 9 * sizeof(double));

    for (k = 0; k < cds->vlen; ++k)
    {
        xk = x[k];
        yk = y[k];
        zk = z[k];

        ip[0][0] += (xk * xk);
        ip[1][1] += (yk * yk);
        ip[2][2] += (zk * zk);
        ip[0][1] += (xk * yk);
        ip[0][2] += (xk * zk);
        ip[1][2] += (yk * zk);
    }

    ip[1][0] = ip[0][1];
    ip[2][0] = ip[0][2];
    ip[2][1] = ip[1][2];

    //printf("tr(X'X) = % e\n", ip[0][0] + ip[1][1] + ip[2][2]);

    /* Mat3Print(ip2); */
}


static void
CdsInnProdWt(Cds *cds, const double *wts)
{
    /* (i x k)(k x j) = (i x j) */
    /* (3 x N)(N x 3) = (3 x 3) */
    int             k;
    double        **ip = NULL;
    const double   *x = (const double *) cds->x,
                   *y = (const double *) cds->y,
                   *z = (const double *) cds->z;
    double          xk, yk, zk, wtsi;

    ip = cds->innerprod;

    memset(ip[0], 0, 9 * sizeof(double));

    for (k = 0; k < cds->vlen; ++k)
    {
        wtsi = wts[k];

        xk = x[k];
        yk = y[k];
        zk = z[k];

        ip[0][0] += (xk * xk) * wtsi;
        ip[1][1] += (yk * yk) * wtsi;
        ip[2][2] += (zk * zk) * wtsi;
        ip[0][1] += (xk * yk) * wtsi;
        ip[0][2] += (xk * zk) * wtsi;
        ip[1][2] += (yk * zk) * wtsi;
    }

    ip[1][0] = ip[0][1];
    ip[2][0] = ip[0][2];
    ip[2][1] = ip[1][2];

    //printf("tr(X'X) = % e\n", ip[0][0] + ip[1][1] + ip[2][2]);

    /* Mat3Print(ip2); */
}


void
CalcCdsPrincAxes(Cds *cds, double **r, double **u, double **vt, double *lambda, const double *wts)
{
    int             j;
    double          det;

    if (algo->leastsquares)
        CdsInnProd(cds);
    else
        CdsInnProdWt(cds, wts);

    CalcGSLSVD3(cds->innerprod, u, lambda, vt);

    det = Mat3Det((const double **) u);
//        printf("\n * determinant of SVD UVt matrix = %f\n", det);

    if (det < 0)
    {
//            printf("\nlambda: % f % f % f\n", lambda[0], lambda[1], lambda[2]);
        printf("\nNEGATIVE DETERMINANT\n");
        lambda[2] = -lambda[2];

        for (j = 0; j < 3; ++j)
            u[j][2] = -u[j][2];
    }

    Mat3Cpy(r, (const double **) u);

    if (VerifyRotMat(r, 1e-8) == 0)
    {
        printf("\nWARNING_772: BAD ROTATION MATRIX U\n\n");
        //exit(EXIT_FAILURE);
    }
}


void
SumCdsTB(CdsArray *cdsA, const int exclude)
{
    int             i, j;
    double          xtmp, ytmp, ztmp, otmp, btmp;
    const Cds     **cds = (const Cds **) cdsA->cds;

    for (i = 0; i < cdsA->vlen; ++i)
    {
        xtmp = ytmp = ztmp = otmp = btmp = 0.0;
        for (j = 0; j < exclude; ++j)
        {
            xtmp += cds[j]->x[i];
            ytmp += cds[j]->y[i];
            ztmp += cds[j]->z[i];
            otmp += cds[j]->o[i];
            btmp += cds[j]->b[i];
        }

        for (j = exclude + 1; j < cdsA->cnum; ++j)
        {
            xtmp += cds[j]->x[i];
            ytmp += cds[j]->y[i];
            ztmp += cds[j]->z[i];
            otmp += cds[j]->o[i];
            btmp += cds[j]->b[i];
        }
    }
}
