/*---------------------------------------------------------------------------*\
  ==  == ====== ====   ====    |
                    \\     ||  | Multiphase Code Repository by HZDR
  ======   //   ||  || ===//   | Website: https://doi.org/10.14278/rodare.767
  ||  ||  //    ||  // || \\   | License: GPL-3.0-or-later
  ==  == ====== ====   ==  ==  |
-------------------------------------------------------------------------------
License
    This file is part of the Multiphase Code Repository by HZDR.

    Copyright (C) 2025 by Helmholtz-Zentrum Dresden-Rossendorf e.V. (HZDR),
    Website: https://hzdr.de

    Copyright (C) 2025 by Technische Universitaet Darmstadt,
    Website: https://www.tu-darmstadt.de

    Copyright (C) 2025 by Technische Universitaet Muenchen,
    Website: https://www.tum.de

    Multiphase Code Repository by HZDR is based on the free software for
    computational fluid dynamics (CFD) from the OpenFOAM Foundation.
    Copyright (C) 2025 by OpenFOAM Foundation, Website: https://openfoam.org

    If you are interested in which files are original OpenFOAM Foundation
    files, which OpenFOAM Foundation files were modified, and which files were
    newly created, see FILES.md.

    Multiphase Code Repository by HZDR 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.

    Multiphase Code Repository by HZDR 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 the Multiphase Code Repository by HZDR. If not, see
    <http://www.gnu.org/licenses/>.

\*---------------------------------------------------------------------------*/

#include "trackPhaseStructures.H"
#include "addToRunTimeSelectionTable.H"
#include "syncTools.H"

#include "cyclicFvPatchFields.H"
#include "processorCyclicFvPatch.H"
#include "nonConformalCyclicFvPatchFields.H"
#include "nonConformalProcessorCyclicFvPatchFields.H"

// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //

namespace Foam
{
    namespace functionObjects
    {
        defineTypeNameAndDebug(trackPhaseStructures, 0);

        addToRunTimeSelectionTable
        (
            functionObject,
            trackPhaseStructures,
            dictionary
        );
    }
}


// * * * * * * * * * * * * * Private Member Functions  * * * * * * * * * * * //

Foam::Map<Foam::label>
Foam::functionObjects::trackPhaseStructures::findPatchRegions
(
    const regionSplit& regions
) const
{
    // Count number of patch faces (just for initial sizing)
    const labelHashSet patchIDs(mesh_.boundaryMesh().patchSet(patchNames_));

    label nPatchFaces = 0;
    forAllConstIter(labelHashSet, patchIDs, iter)
    {
        nPatchFaces += mesh_.boundaryMesh()[iter.key()].size();
    }


    Map<label> patchRegions(nPatchFaces);
    forAllConstIter(labelHashSet, patchIDs, iter)
    {
        const polyPatch& pp = mesh_.boundaryMesh()[iter.key()];

        // Collect all regions on the patch
        const labelList& faceCells = pp.faceCells();

        forAll(faceCells, i)
        {
            patchRegions.insert
            (
                regions[faceCells[i]],
                Pstream::myProcNo()     // dummy value
            );
        }
    }

    // Make sure all the processors have the same set of regions
    Pstream::mapCombineGather(patchRegions, minEqOp<label>());
    Pstream::mapCombineScatter(patchRegions);

    return patchRegions;
}


Foam::boolList
Foam::functionObjects::trackPhaseStructures::getBlockedFaces
(
    const volScalarField& vsf
) const
{
    boolList blockedFace(mesh_.nFaces(), false);

    {
        for (label facei = 0; facei < mesh_.nInternalFaces(); facei++)
        {
            scalar ownVal = vsf[mesh_.faceOwner()[facei]];
            scalar neiVal = vsf[mesh_.faceNeighbour()[facei]];

            if
            (
                (ownVal < threshold_ && neiVal > threshold_)
             || (ownVal > threshold_ && neiVal < threshold_)
            )
            {
                blockedFace[facei] = true;
            }
        }

        // Block coupled faces
        forAll(vsf.boundaryField(), patchi)
        {
            const fvPatchScalarField& fvp(vsf.boundaryField()[patchi]);

            if (fvp.coupled())
            {
                tmp<scalarField> townFld(fvp.patchInternalField());
                const scalarField& ownFld = townFld();

                label start = fvp.patch().patch().start();

                // Cut at cyclic patch
                if
                (
                    cutAtCyclicPatch_
                 && (
                        isType<cyclicFvPatch>(fvp.patch())
                     || isType<processorCyclicFvPatch>(fvp.patch())
                     || isType<nonConformalCyclicFvPatch>(fvp.patch())
                     || isType<nonConformalProcessorCyclicFvPatch>(fvp.patch())
                    )
                )
                {
                    forAll(ownFld, i)
                    {
                        blockedFace[start+i] = true;
                    }
                }
                else
                {
                    tmp<scalarField> tnbrFld(fvp.patchNeighbourField());
                    const scalarField& nbrFld = tnbrFld();

                    forAll(ownFld, i)
                    {
                        scalar ownVal = ownFld[i];
                        scalar neiVal = nbrFld[i];

                        if
                        (
                            (ownVal < threshold_ && neiVal > threshold_)
                         || (ownVal > threshold_ && neiVal < threshold_)
                        )
                        {
                            blockedFace[start+i] = true;
                        }
                    }
                }
            }
        }
    }

    return blockedFace;
}


Foam::tmp<Foam::scalarField>
Foam::functionObjects::trackPhaseStructures::interpolateCellDataToPointData
(
    const scalarField & alpha
) const
{
    scalarField alphaP(mesh_.nPoints(), Zero);
    scalarField sumP(mesh_.nPoints(), Zero);

    // Interpolation of volume fraction from cells centres to the points
    // (could in general also be done by volPointInterpolate, however we
    // encountered some problems when using volPointInterpolate and
    // dynamicRefineFvMesh)
    forAll(mesh_.cells(), cellI)
    {
        const cell faces(mesh_.cells()[cellI]);
        forAll(faces, J)
        {
            const face points(mesh_.faces()[faces[J]]);
            forAll(points, K)
            {
                const label pointK = points[K];

                const scalar d
                (
                    mag(mesh_.C()[cellI] - mesh_.points()[pointK])
                );
                alphaP[pointK] += alpha[cellI]/max(d, small);
                sumP[pointK] += 1/max(d, small);
            }
        }
    }

    // Synchronise values on selected mesh points.
    syncTools::syncPointList(mesh_, alphaP, plusEqOp<scalar>(), scalar(0.0));
    syncTools::syncPointList(mesh_, sumP, plusEqOp<scalar>(), scalar(0.0));

    return alphaP/sumP;
}


Foam::scalarField Foam::functionObjects::trackPhaseStructures::surfaceArea
(
    const scalarField& pField,
    const scalar crit
)
{
    scalarField SField(mesh_.nCells(), Zero);
    scalarField cutContour(mesh_.nCells(), Zero);

    forAll(mesh_.cells(), cellI)
    {
        // Determine the number of faces which are cut by the interface and the
        // face which will be visited first during the reconstruction
        int startFace = -1;
        int cutFaces = 0;

        const cell faces = mesh_.cells()[cellI];
        forAll(faces, j)
        {
            const label faceI = faces[j];

            face points = mesh_.faces()[faceI];

            if (mesh_.isInternalFace(faceI))
            {
                // Keep or reverse numbering of points such that the face vector
                // points out of the face (right hand rule)
                const label own = mesh_.owner()[faceI];
                if (own != cellI)
                {
                    face pointsTmp(points.size());
                    pointsTmp = points;
                    for (int i = 0; i < points.size(); i++)
                    {
                        points[i] = pointsTmp[points.size()-1-i];
                    }
                }
            }

            // Check if face is cut by the interface
            bool cutFound = 0;
            int i = 0;
            while ((!cutFound) && (i < points.size()))
            {
                label ip1 = i+1;
                if (ip1 == points.size())
                {
                    ip1 = 0;
                }

                // Check if volume fraction change from below to above the
                // criterion along the edge between point xi and xip1
                const scalar di = pField[points[i]];
                const scalar dip1 = pField[points[ip1]];
                if
                (
                    ((di <= crit) && (dip1 >  crit))
                 || ((di <  crit) && (dip1 == crit))
                )
                {
                    cutFound = 1;

                    if (startFace == -1)
                    {
                        startFace = j;
                    }
                }
                i += 1;
            }

            if (cutFound)
            {
                cutFaces += 1;
            }
        }

        // Find corner points of the cutting polygon in right order
        // (start with startFace, see above)
        DynamicList<vector> xCuttingPlane;
        // contains the points of the cutting polygon; DynamicList since we
        // never know the actual number of cutting points a priori; one cutting
        // plane for every cell

        label nextFace = startFace;
        int N = 0;
        while (N < cutFaces)
        {
            label j = nextFace;
            label faceI = faces[j];
            face points = mesh_.faces()[faceI];

            if (mesh_.isInternalFace(faceI))
            {
                // Keep or reverse numbering of points such that the face vector
                // points out of the face (right hand rule); depends on the fact
                // if faces are internal or external faces
                label own = mesh_.owner()[faceI];
                if (own != cellI)
                {
                    face pointsTmp(points.size());
                    pointsTmp = points;
                    for (int i = 0; i < points.size(); i++)
                    {
                        points[i] = pointsTmp[points.size()-1-i];
                    }
                }
            }

            // Loop over all mesh points of one face
            for (int i = 0; i < points.size(); i++)
            {
                label ip1 = i+1;

                //closed loop condition
                if (ip1 == points.size())
                {
                    ip1 = 0;
                }

                // Check, if volume fraction change from below to above
                // crit along the edge between point xi and xip1
                const vector xi = mesh_.points()[points[i]];
                const vector xip1 = mesh_.points()[points[ip1]];
                const scalar di = pField[points[i]];
                const scalar dip1 = pField[points[ip1]];

                if
                (
                    ((di <= crit) && (dip1 >  crit))
                 || ((di <  crit) && (dip1 == crit))
                ) //First possibility
                {
                    N += 1;

                    // Interpolate position along edge where volume fraction
                    // equals crit
                    const vector xNew = xi+(crit-di)/(dip1-di)*(xip1-xi);
                    bool exists = 0;

                    // Check if coordinate already exists in xCuttingPlane (can
                    // happen when volume fraction is exactly crit at one
                    // point of the cell)
                    for (int n = 0; n < xCuttingPlane.size(); n++)
                    {
                        if (xNew == xCuttingPlane[n])
                        {
                            exists = 1;
                            break;
                        }
                    }

                    // If coordinate does not yet exist, append it to
                    // xCuttingPlane
                    if (!exists)
                    {
                        xCuttingPlane.append(xNew);

                        if (cutContour[cellI] == 0)
                        {
                            cutContour[cellI] = 1;
                        }
                    }

                    bool found = 0;
                    int j2 = -1;

                    // Find the second face of the cell which shares the edge
                    // where we just obtained a new coordinate of the cutting
                    // polygon and make this the next face to visit (this
                    // ensures that the coordinates of the corner points are
                    // found according to the right hand rule) Loop over all
                    // faces of the cell OR until the face with sharing edge is
                    // found
                    while (!found)
                    {
                        j2 += 1;
                        label faceI2 = faces[j2];
                        face points2 = mesh_.faces()[faceI2];

                        if (mesh_.isInternalFace(faceI2))
                        {
                            label own2 = mesh_.owner()[faceI2];
                            if (own2 != cellI)
                            {
                                face pointsTmp(points2.size());
                                pointsTmp = points2;
                                for (int i = 0; i < points2.size(); i++)
                                {
                                    points2[i] = pointsTmp[points2.size()-1-i];
                                }
                            }
                        }

                        for (int i2 = 0; i2 < points2.size(); i2++)
                        {
                            label i2p1 = i2+1;
                            if (i2p1 == points2.size())
                            {
                                i2p1 = 0;
                            }

                            if
                            (
                                (points2[i2] == points[ip1])
                             && (points2[i2p1] == points[i])
                            )
                            {
                                nextFace = j2;
                                found = 1;
                            }
                        }
                    }
                }
            }
        }

        // Calculate area vector
        if (cutContour[cellI])
        {
            vector SVec(Zero);

            for (int i = 0; i < xCuttingPlane.size(); i++)
            {
                label ip1 = i+1;
                //closed loop condition
                if (ip1 == xCuttingPlane.size())
                {
                    ip1 = 0;
                }
                const vector xi = xCuttingPlane[i];
                const vector xip1 = xCuttingPlane[ip1];
                SVec -= 0.5*(xi^xip1);
            }

            SField[cellI] = mag(SVec);
        }
    }

    return SField;
}


void Foam::functionObjects::trackPhaseStructures::updateRegionProperties
(
    const regionSplit& regions
)
{
    allRegionVolume_ = regionSum(regions, mesh_.V());

    allRegionCentreOfGravity_.clear();
    allRegionVelocity_.clear();
    allRegionSurfaceArea_.clear();
    allRegionSphericity_.clear();

    if (allRegionVolume_.size())
    {
        autoPtr<volVectorField> UPtr;
        const volVectorField& U(lookupOrRead<volVectorField>(UPtr, UName_));

        forAllIter(Map<scalar>, allRegionVolume_, vIter)
        {
            allRegionVolume_[vIter.key()] /= thickness_;

            if
            (
                allRegionVolume_[vIter.key()] < minVol_
             || allRegionVolume_[vIter.key()] > maxVol_
            )
            {
                continue;
            }

            scalarField weightField(mesh_.nCells(), Zero);
            forAll(weightField, celli)
            {
                if (allRegionVolume_.find(regions[celli]) == vIter)
                {
                    weightField[celli] = 1.0;
                }
            }

            vectorField cellCentres(mesh_.C());
            scalarField cellVolumes(mesh_.V());
            vectorField cellVelocities(U.primitiveField());
            scalarField cellAreas(mesh_.nCells(), Zero);
            if (calcSphericity_)
            {
                autoPtr<volScalarField> alphaPtr;
                const scalarField& alpha
                (
                    lookupOrRead<volScalarField>
                    (
                        alphaPtr,
                        alphaName_
                    ).internalField()
                );

                cellAreas =
                    surfaceArea
                    (
                        interpolateCellDataToPointData
                        (
                            weightField*alpha + alpha*neg(alpha - threshold_)
                        ),
                        threshold_
                    );
            }

            // Combine onto master
            combineFields(weightField);
            combineFields(cellCentres);
            combineFields(cellVolumes);
            combineFields(cellVelocities);
            if (calcSphericity_)
            {
                combineFields(cellAreas);
            }

            if (Pstream::master())
            {
                scalar phaseSum(sum(scalarField(weightField*cellVolumes)));
                vector phaseByCSum
                (
                    sum(vectorField(weightField*cellCentres*cellVolumes))
                );
                vector phaseByUSum
                (
                    sum(vectorField(weightField*cellVelocities*cellVolumes))
                );

                allRegionCentreOfGravity_.insert
                (
                    vIter.key(),
                    phaseByCSum/phaseSum
                );

                allRegionVelocity_.insert
                (
                    vIter.key(),
                    phaseByUSum/phaseSum
                );

                if (calcSphericity_)
                {
                    allRegionSurfaceArea_.insert
                    (
                        vIter.key(),
                        sum(cellAreas)/thickness_
                    );

                    const scalar& pi(constant::mathematical::pi);
                    const scalar& volume(allRegionVolume_[vIter.key()]);
                    const scalar& surfaceA(allRegionSurfaceArea_[vIter.key()]);

                    if (twoDimensional_)
                    {
                        // volume translates to surface area and
                        // surfaceArea translates to perimeter
                        const scalar dEquivalent(2*Foam::sqrt(volume/pi));

                        allRegionSphericity_.insert
                        (
                            vIter.key(),
                            pi*dEquivalent/max(surfaceA, small)
                        );
                    }
                    else
                    {
                        const scalar dEquivalent
                        (
                            pow(6*volume/pi, 1.0/3.0)
                        );

                        allRegionSphericity_.insert
                        (
                            vIter.key(),
                            pi*Foam::sqr(dEquivalent)/max(surfaceA, small)
                        );
                    }
                }
            }
        }

        Pstream::mapCombineScatter(allRegionCentreOfGravity_);
        Pstream::mapCombineScatter(allRegionVelocity_);
        Pstream::mapCombineScatter(allRegionSurfaceArea_);
        Pstream::mapCombineScatter(allRegionSphericity_);
    }
}


void Foam::functionObjects::trackPhaseStructures::updateTrackedIndices
(
    const regionSplit& regions,
    const Map<vector>& allRegionCentreOfGravity0
)
{
    const Map<label> patchRegions(findPatchRegions(regions));

    if (Pstream::master())
    {
        // Save old indices
        Map<label> allRegionIndex0(0);
        if (allRegionIndex_.size())
        {
            allRegionIndex0 = allRegionIndex_;
            allRegionIndex_.clear();
        }

        forAllIter(Map<vector>, allRegionCentreOfGravity_, cIter)
        {
            const label regionI = cIter.key();

            // Exclude liquid core region
            // or regions with volume greater than maxVol
            // or regions with volume smaller than minVol
            // or regions, which are already in map
            if
            (
                patchRegions.found(regionI)
             || allRegionVolume_[regionI] > maxVol_
             || allRegionVolume_[regionI] < minVol_
             || allRegionIndex_.found(regionI)
            )
            {
                continue;
            }

            if
            (
                allRegionCentreOfGravity0.size()
             && allRegionIndex0.size()
            )
            {
                const vector cog(allRegionCentreOfGravity_[regionI]);

                scalar minDist(great);
                label c0key(-1);

                // Find closest of old structures
                forAllConstIter(Map<vector>, allRegionCentreOfGravity0, c0Iter)
                {
                    const vector cog0(allRegionCentreOfGravity0[c0Iter.key()]);
                    const scalar dist(mag(cog - cog0));

                    if
                    (
                        dist < minDist
                     && dist < tolerance_
                     && allRegionIndex0.found(c0Iter.key())
                    )
                    {
                        minDist = dist;
                        c0key = c0Iter.key();
                    }
                }

                if (c0key >= 0)
                {
                    allRegionIndex_.insert(regionI, allRegionIndex0[c0key]);
                }
                else
                {
                    allRegionIndex_.insert(regionI, index_);
                    ++index_;
                }
            }
            else
            {
                allRegionIndex_.insert(regionI, index_);
                ++index_;
            }
        }
    }

    Pstream::mapCombineScatter(allRegionIndex_);
}


void Foam::functionObjects::trackPhaseStructures::writeFileHeader
(
    const label i
)
{
    OFstream& file = this->file(i);

    writeHeader(file, "Tracked structure properties");
    file<<"# "
        << setw(IOstream::defaultPrecision() + 6) << "ID"
        << setw(IOstream::defaultPrecision() + 8) << "Time"
        << setw(IOstream::defaultPrecision() + 8) << "X"
        << setw(IOstream::defaultPrecision() + 8) << "Y"
        << setw(IOstream::defaultPrecision() + 8) << "Z"
        << setw(IOstream::defaultPrecision() + 8) << "U"
        << setw(IOstream::defaultPrecision() + 8) << "V"
        << setw(IOstream::defaultPrecision() + 8) << "W";

    if (calcSphericity_)
    {
        file<< setw(IOstream::defaultPrecision() + 8) << "Volume"
            << setw(IOstream::defaultPrecision() + 8) << "SurfaceArea"
            << "Sphericity";
    }
    else
    {
        file<< "Volume";
    }

    file<< endl;
}


// * * * * * * * * * * * * * * * * Constructors  * * * * * * * * * * * * * * //

Foam::functionObjects::trackPhaseStructures::trackPhaseStructures
(
    const word& name,
    const Time& runTime,
    const dictionary& dict
)
:
    fvMeshFunctionObject(name, runTime, dict),
    logFiles(obr_, name),
    file_(obr_, name),
    alphaName_("alpha"),
    UName_("U"),
    calcSphericity_(true),
    patchNames_(0),
    threshold_(0.5),
    tolerance_(great),
    maxVol_(great),
    minVol_(0),
    thickness_(1),
    writeIndexField_(false),
    cutAtCyclicPatch_(true),
    allRegionIndex_(0),
    allRegionCentreOfGravity_(0),
    allRegionVelocity_(0),
    allRegionVolume_(0),
    allRegionSurfaceArea_(0),
    allRegionSphericity_(0),
    index_(1),
    regions_(0)
{
    read(dict);
    resetName(name);

    if (mesh_.nGeometricD() == 2)
    {
        twoDimensional_ = true;

        vector plane(0,0,0);
        if (mesh_.geometricD().x() == -1)
        {
            plane = vector(1,0,0);
        }
        else if (mesh_.geometricD().y() == -1)
        {
            plane = vector(0,1,0);
        }
        else if (mesh_.geometricD().z() == -1)
        {
            plane = vector(0,0,1);
        }

        const cell& faces = mesh_.cells()[0];
        const labelList points = faces.labels(mesh_.faces());
        pointField pLocal(points.size(), vector::zero);
        forAll(points, i)
        {
            const label& pointI = points[i];
            pLocal[i] = mesh_.points()[pointI];
        }

        thickness_ = Foam::max(pLocal & plane) - Foam::min(pLocal & plane);

        Info<< type() << ": "
            << "Calculating area (volume) and circularity (sphericity) "
            << "in 2D space" << nl
            << "plane " << plane << ", thickness " << thickness_ << nl << endl;
    }
    else if (mesh_.nGeometricD() == 3)
    {
        twoDimensional_ = false;

        Info<< type() << ": "
            << "Calculating volume and sphericity in 3D space." << nl << endl;
    }
    else
    {
        FatalIOErrorInFunction(dict)
            << type() << ": Only works for 2D and 3D cases."
            << exit(FatalIOError);
    }

    execute();
}


// * * * * * * * * * * * * * * * * Destructor  * * * * * * * * * * * * * * * //

Foam::functionObjects::trackPhaseStructures::~trackPhaseStructures()
{}


// * * * * * * * * * * * * * * * Member Functions  * * * * * * * * * * * * * //

bool Foam::functionObjects::trackPhaseStructures::read(const dictionary& dict)
{
    if (fvMeshFunctionObject::read(dict))
    {
        dict.readIfPresent("alpha", alphaName_);
        dict.readIfPresent("U", UName_);
        dict.readIfPresent("calcSphericity", calcSphericity_);
        dict.readIfPresent("excludePatches", patchNames_);
        dict.readIfPresent("threshold", threshold_);
        dict.readIfPresent("tolerance", tolerance_);
        dict.readIfPresent("maxVolume", maxVol_);
        dict.readIfPresent("minVolume", minVol_);
        dict.readIfPresent("writeIndexField", writeIndexField_);
        dict.readIfPresent("cutAtCyclicPatch", cutAtCyclicPatch_);

        if (dict.found("coordinateSystem"))
        {
            coordSysPtr_ =
                coordinateSystem::New(obr_, dict.subDict("coordinateSystem"));

            Info<< "Transforming all vectorFields with coordinate system "
                << coordSysPtr_().name() << endl;
        }

        return true;
    }
    else
    {
        return false;
    }
}


bool Foam::functionObjects::trackPhaseStructures::execute()
{
    Info<< type() << " " << name() << " execute:" << nl;

    autoPtr<volScalarField> alphaPtr;
    const volScalarField& alpha
    (
        lookupOrRead<volScalarField>(alphaPtr, alphaName_)
    );

    // Split into regions
    regionSplit regions(mesh_, getBlockedFaces(alpha));
    Info<< "    Determined " << regions.nRegions() << " regions" << endl;

    if (writeIndexField_)
    {
        regions_ = regions;
    }

    // Save centre of gravity
    Map<vector> allRegionCentreOfGravity0(0);
    if (allRegionCentreOfGravity_.size())
    {
        allRegionCentreOfGravity0 = allRegionCentreOfGravity_;
    }

    updateRegionProperties(regions);

    updateTrackedIndices(regions, allRegionCentreOfGravity0);

    // Write data to file
    logFiles::write();

    unsigned int w = IOstream::defaultPrecision() + 7;

    if (Pstream::master())
    {
        forAllIter(Map<label>, allRegionIndex_, iIter)
        {
            const label regionI((allRegionIndex_.find(iIter.key())).key());

            file()  << setw(w) << allRegionIndex_[iIter.key()]
                << ' ' << setw(w) << time_.value()
                << ' ' << setw(w) << allRegionCentreOfGravity_[regionI].x()
                << ' ' << setw(w) << allRegionCentreOfGravity_[regionI].y()
                << ' ' << setw(w) << allRegionCentreOfGravity_[regionI].z()
                << ' ' << setw(w) << allRegionVelocity_[regionI].x()
                << ' ' << setw(w) << allRegionVelocity_[regionI].y()
                << ' ' << setw(w) << allRegionVelocity_[regionI].z();

            if (calcSphericity_)
            {
                file()  << ' ' << setw(w) << allRegionVolume_[regionI]
                        << ' ' << setw(w) << allRegionSurfaceArea_[regionI]
                        << ' ' << allRegionSphericity_[regionI];
            }
            else
            {
                file()  << ' ' << allRegionVolume_[regionI];
            }

            file()  << endl;
        }
    }

    return true;
}


bool Foam::functionObjects::trackPhaseStructures::write()
{
    Info<< type() << " " << name() << " write:" << nl;

    // Write out global index field
    if (writeIndexField_)
    {
        volScalarField globalIndex
        (
            IOobject
            (
                alphaName_ + "_globalIndex",
                time_.name(),
                obr_,
                IOobject::NO_READ
            ),
            mesh_,
            dimensionedScalar(dimless, Zero)
        );

        forAll(globalIndex, celli)
        {
            const label regionI = regions_[celli];

            if (allRegionIndex_.found(regionI))
            {
                globalIndex[celli] = allRegionIndex_[regionI];
            }
        }
        globalIndex.correctBoundaryConditions();

        Info<< "    Writing global index field to " << globalIndex.name()
            << endl;
        globalIndex.write();
    }

    return true;
}


// ************************************************************************* //
