/*
** (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: AmrDeriveYAvg.cpp,v 1.3 2003/02/04 18:07:18 marc Exp $
//

#include <winstd.H>
#include <new>
#include <iostream>
using std::cout;
using std::endl;
#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 AVGPLANE  AVGPLANE
#elif defined(BL_FORT_USE_LOWERCASE)
#  define AVGPLANE avgplane
#elif defined(BL_FORT_USE_UNDERSCORE)
#  define AVGPLANE  avgplane_
#endif

extern "C" {

    void AVGPLANE(Real* v, ARLIM_P(vlo), ARLIM_P(vhi),
                  Real* a, ARLIM_P(alo), ARLIM_P(ahi),
                  const int* jlo, const int* jhi);
        };


static
void
PrintUsage (const char* progName)
{
    cout << '\n';
    cout << "Usage:" << '\n';
    cout << progName << '\n';
    cout << "    infiles  = inputFileList" << '\n';
    cout << "   [help=<0,1>]" << '\n';
    cout << "   [bsize=<n>]" << '\n';
    cout << "   [-verbose]" << '\n';
    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> infiles(nfile);
    pp.queryarr("infiles",infiles);

    int bsize=5; pp.query("bsize",bsize);

    Real yrange=.015; pp.query("yrange",yrange);

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

    const int nComp = 1;
    Array<string> names(nComp);
    names[0] = "temp";

    DataServices* dataServices0 = new DataServices(infiles[0], fileType);
    AmrData& amrData0 = dataServices0->AmrDataRef();

    const int finestLevel = amrData0.FinestLevel();
    const Array<Real>& dx = amrData0.DxLevel()[finestLevel];
    const Box box = amrData0.ProbDomain()[finestLevel];

    const int jmid = int(0.5*(box.hiVect()[1]-box.loVect()[1]+1) - 1);

    cout << "jmid:" << jmid << endl;
    const int jhi = jmid + int(yrange/dx[1]);
    const int jlo = jmid - int(yrange/dx[1]);
    IntVect ivlo = box.smallEnd(); ivlo[1] = jmid;
    IntVect ivhi = box.bigEnd(); ivhi[1] = jmid;
    Box avgBox(ivlo,ivhi);

    FArrayBox pData(box,nComp);
    FArrayBox avgData(avgBox,1);
    FArrayBox tmp(box,1);    
    FArrayBox tmpAvg(avgBox,1);    

    delete dataServices0;

    cout << "Averaging data over j indices: " << jlo << ", " << jhi << endl;

    avgData.setVal(0.0);
    for (int ifile=0; ifile<infiles.size(); ++ifile)
    {
        cout << "Processing infile= " << infiles[ifile] << endl;

        DataServices dataServices(infiles[ifile], fileType);

        if (!dataServices.AmrDataOk())
            ParallelDescriptor::EndParallel();
        
        AmrData& amrData = dataServices.AmrDataRef();

        cout << "    Reading data" << endl;

        for (int i=0; i<nComp; ++i)
        {
            amrData.FillVar(&tmp,box,finestLevel,names[i],0);
            pData.copy(tmp,box,0,box,i,1);
        }
        
        cout << "    Averaging data" << endl;

        // Compute sum of squares of fluctuating vels for each bin/plane
        AVGPLANE(pData.dataPtr(), ARLIM(pData.loVect()), ARLIM(pData.hiVect()),
                 tmpAvg.dataPtr(), ARLIM(tmpAvg.loVect()), ARLIM(tmpAvg.hiVect()),
                 &jlo, &jhi);

        avgData.plus(tmpAvg);
    }

    const Real factor = 1./float(infiles.size());
    avgData.mult(factor);

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

    BoxLib::Finalize();
    return 0;
}
