/*
** (c) 1996-2000 The Regents of the University of California (through
** E.O. Lawrence Berkeley National Laboratory), subject to approval by
** the U.S. Department of Energy.  Your use of this software is under
** license -- the license agreement is attached and included in the
** directory as license.txt or you may contact Berkeley Lab's Technology
** Transfer Department at TTD@lbl.gov.  NOTICE OF U.S. GOVERNMENT RIGHTS.
** The Software was developed under funding from the U.S. Government
** which consequently retains certain rights as follows: the
** U.S. Government has been granted for itself and others acting on its
** behalf a paid-up, nonexclusive, irrevocable, worldwide license in the
** Software to reproduce, prepare derivative works, and perform publicly
** and display publicly.  Beginning five (5) years after the date
** permission to assert copyright is obtained from the U.S. Department of
** Energy, and subject to any subsequent five (5) year renewals, the
** U.S. Government is granted for itself and others acting on its behalf
** a paid-up, nonexclusive, irrevocable, worldwide license in the
** Software to reproduce, prepare derivative works, distribute copies to
** the public, perform publicly and display publicly, and to permit
** others to do so.
*/


//
// $Id: AmrDerive_IntScale.cpp,v 1.1 2003/01/22 22:16:53 jbb Exp $
//

#include <winstd.H>
#include <new>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>

#include <unistd.h>

#include "REAL.H"
#include "Box.H"
#include "FArrayBox.H"
#include "ParmParse.H"
#include "ParallelDescriptor.H"
#include "DataServices.H"
#include "Utility.H"
#include "VisMF.H"
#include "Derived.H"

#include "ArrayLim.H"

//
// This MUST be defined if don't have pubsetbuf() in I/O Streams Library.
//
#ifdef BL_USE_SETBUF
#define pubsetbuf setbuf
#endif

#if defined(BL_FORT_USE_UPPERCASE)
#  define TRANSV  TRANSV
#elif defined(BL_FORT_USE_LOWERCASE)
#  define TRANSV  transv
#elif defined(BL_FORT_USE_UNDERSCORE)
#  define TRANSV  transv_
#endif

extern "C" {
    void TRANSV(Real* v, ARLIM_P(vlo), ARLIM_P(vhi),
                const Real* dx, const Real* domnlo,
                Real* r,  Real* t, Real* z, int* n, ARLIM_P(alo), ARLIM_P(ahi),
                const int* maxbins);
        };


static
void
PrintUsage (const char* progName)
{
    std::cout << '\n';
    std::cout << "Usage:" << '\n';
    std::cout << progName << '\n';
    std::cout << "    infile  = inputFileName" << '\n';
    std::cout << "    outfile = outputFileName" << '\n';
    std::cout << "    type    = derivedTypeName" << '\n';
    std::cout << "   [-help]" << '\n';
    std::cout << "   [-verbose]" << '\n';
    std::cout << "   [fab.format = FormatType]" << '\n';
    std::cout << "      where FormatType=IEEE32(default), ASCII, 8BIT, or NATIVE" << '\n';
    std::cout << '\n';

    std::cout << "Available types:" << '\n';
    for (int nder = 0; nder < NumDeriveFunc; ++nder)
    {
        std::cout << "  " << DerivedQuants[nder].name << '\n';
    }
    std::cout << '\n';
    exit(1);
}

int
main (int   argc,
      char* argv[])
{
    BoxLib::Initialize(argc,argv);

    if (argc == 1)
        PrintUsage(argv[0]);
    ParmParse pp;

    if (pp.contains("help"))
        PrintUsage(argv[0]);

    FArrayBox::setFormat(FABio::FAB_IEEE_32);
    //
    // Scan the arguments.
    //
    bool verbose = false;
    if (pp.contains("verbose"))
    {
        verbose = true;
        AmrData::SetVerbose(true);
    }
    const int nfile = pp.countval("infiles");
    if (nfile<=0) 
        BoxLib::Abort("You must specify `infiles'");

    std::vector<std::string> iFile(nfile);
    pp.queryarr("infiles",iFile);

    DataServices::SetBatchMode();
    FileType fileType(NEWPLT);    

    const int nComp = BL_SPACEDIM;
    Array<string> names(nComp);
    names[0] = "xvel";
    names[1] = "yvel";
    names[2] = "zvel";

    DataServices* dataServices0 = new DataServices(iFile[0], fileType);
    AmrData& amrData0 = dataServices0->AmrDataRef();
    const Box box = amrData0.ProbDomain()[0];

    // Get a shifted domnlo vector to center domain
    Array<Real> domnlo(BL_SPACEDIM);
    for (int i=0; i<domnlo.size(); i++)
        domnlo[i] = -0.5*(amrData0.ProbLo()[i] + amrData0.ProbHi()[i]);

    delete dataServices0;

    // Build 3D arrays to hold bin data (j,bin,0)
    const int maxbin = 100;
    const IntVect vhi(box.length(1)-1,maxbin,0);
    const Box vbox(IntVect::TheZeroVector(),vhi);

    FArrayBox avVR(vbox,1), avVRi(vbox,1);
    FArrayBox avVT(vbox,1), avVTi(vbox,1);
    FArrayBox avVZ(vbox,1), avVZi(vbox,1);
    BaseFab<int> Nbin(vbox,1);

    FArrayBox vData(box,BL_SPACEDIM);
    FArrayBox tmp(box,1);

    avVR.setVal(0);
    avVT.setVal(0);
    avVZ.setVal(0);
    for (int ifile=0; ifile<iFile.size(); ++ifile)
    {
        DataServices dataServices(iFile[ifile], fileType);

        if (!dataServices.AmrDataOk())
            ParallelDescriptor::EndParallel();
        
        AmrData& amrData = dataServices.AmrDataRef();
        
        for (int i=0; i<BL_SPACEDIM; ++i)
        {
            amrData.FillVar(&tmp,box,0,names[i],0);
            vData.copy(tmp,box,0,box,i,1);
        }
        
        TRANSV(vData.dataPtr(), ARLIM(vData.loVect()), ARLIM(vData.hiVect()),
               amrData.DxLevel()[0].dataPtr(), domnlo.dataPtr(),
               avVRi.dataPtr(),  avVTi.dataPtr(),  avVZi.dataPtr(),  Nbin.dataPtr(),
               ARLIM(Nbin.loVect()), ARLIM(Nbin.hiVect()), &maxbin);
        
        // Add bins to sums
        avVR.plus(avVRi);
        avVT.plus(avVTi);
        avVZ.plus(avVZi);
    }

    // Divide by the number of files
    const Real factor = 1./float(nfile);
    avVR.mult(factor);
    avVT.mult(factor);
    avVZ.mult(factor);

    {
        std::string oFile("avVR.fab");
        std::cout << "Writing " << oFile << std::endl;
        std::ofstream osf(oFile.c_str(),std::ios::out|std::ios::binary);
        avVR.writeOn(osf);
        osf.close();
    }

    {
        std::string oFile("avVT.fab");
        std::cout << "Writing " << oFile << std::endl;
        std::ofstream osf(oFile.c_str(),std::ios::out|std::ios::binary);
        avVT.writeOn(osf);
        osf.close();
    }

    {
        std::string oFile("avVZ.fab");
        std::cout << "Writing " << oFile << std::endl;
        std::ofstream osf(oFile.c_str(),std::ios::out|std::ios::binary);
        avVZ.writeOn(osf);
        osf.close();
    }

    BoxLib::Finalize();
    return 0;
}
