/*
** (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.
*/

//BL_COPYRIGHT_NOTICE
#include <winstd.H>

#include <new>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <list>
#include <map>
#include <algorithm>
#include <fstream>

#ifndef WIN32
#include <unistd.h>
#endif

#include "ParmParse.H"
#include "ParallelDescriptor.H"
#include "DataServices.H"
#include "Utility.H"
#include "FArrayBox.H"
#include "Utility.H"

#include "AmrDeriveIntScalLen_F.H"

static
void 
print_usage (int,
             char* argv[])
{
	std::cerr << "usage:\n";
    std::cerr << argv[0] << " infile [options] \n\tOptions:\n";
    exit(1);
}

static
std::string fileID(const std::string& str)
{
	const int len = str.size();
	std::string result = str;
	int i = 1;
	while (isdigit(str[len-i]))
		result = str.substr(len-i++);
	return result;
}

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

    if (argc < 2)
        print_usage(argc,argv);

    ParmParse pp;

    if (pp.contains("help"))
        print_usage(argc,argv);

    if (pp.contains("verbose"))
        AmrData::SetVerbose(true);

    std::string infile;
    pp.get("file",infile);

    std::cout << "Reading " << infile << "...";

    DataServices::SetBatchMode();
    FileType fileType(NEWPLT);
    DataServices dataServices(infile, fileType);
    std::cout << "done" << std::endl;

    if (!dataServices.AmrDataOk())
        DataServices::Dispatch(DataServices::ExitRequest, NULL);
    AmrData& amrData = dataServices.AmrDataRef();

    int finestLevel = amrData.FinestLevel();
    Box box(amrData.ProbDomain()[finestLevel]);
    int dir = 2;
    //Box piece = box.chop(dir,box.length()[dir]*3/4);

    Array<std::string> plotnames = amrData.PlotVarNames();
	
    FArrayBox vFab(box,BL_SPACEDIM);
    BoxArray ba(1);
    ba.set(0,box);
    MultiFab TMP(ba,1,0);
    
    const Array<Real>& dx = amrData.DxLevel()[finestLevel];
    
    char tmpStr[10];
    sprintf(tmpStr,"%-4.4g",amrData.Time());
    std::string zoneID = fileID(infile) + " (t=" + tmpStr + ")";
    
#if 1
    std::cout << "Loading v into fab...";
    vFab.setVal(0.0);
    int idV = -1;
    for (int i=0; i<plotnames.size(); ++i)
        if (plotnames[i] == "x_velocity") idV = i;
    
    std::string dirName[3] = {"x", "y", "z"};
    for (int d=0; d<BL_SPACEDIM; ++d)
    {
        std::string name = dirName[d]+std::string("_velocity");
        amrData.FillVar(TMP, amrData.FinestLevel(), name);
        TMP.copy(vFab,0,d,1);
    }
    std::cout << "done" << std::endl;

    const int corrSize = (int) (0.5*box.length(0));
    Array<Real> corr(corrSize);
    Array<Real> TSL_z(box.length()[2]);
    FArrayBox ug(Box(box).growHi(0,box.length()[0]),1);
    cout << "gbox = " << ug.box() << endl;
    const int nComp = vFab.nComp();
    FORT_SCALLEN(vFab.dataPtr(),ARLIM(vFab.loVect()),ARLIM(vFab.hiVect()),
                 nComp, dx.dataPtr(),
                 box.loVect(), box.hiVect(), TSL_z.dataPtr(),
                 corr.dataPtr(), corr.size(),
                 ug.dataPtr(),ARLIM(ug.loVect()),ARLIM(ug.hiVect()));

    Array<Real> TKE_z(box.length()[2]);
    FORT_TKE(vFab.dataPtr(),ARLIM(vFab.loVect()),ARLIM(vFab.hiVect()),
             nComp, dx.dataPtr(),
             box.loVect(), box.hiVect(), TKE_z.dataPtr());

    Array<Real> TI_z(box.length()[2]);
    FORT_TI(vFab.dataPtr(),ARLIM(vFab.loVect()),ARLIM(vFab.hiVect()),
            nComp, dx.dataPtr(),
            box.loVect(), box.hiVect(), TI_z.dataPtr());

    Array<Real> GradUSqrd_z(box.length()[2]-2);
    FORT_GUS(vFab.dataPtr(),ARLIM(vFab.loVect()),ARLIM(vFab.hiVect()),
             nComp, dx.dataPtr(),
             box.loVect(), box.hiVect(), GradUSqrd_z.dataPtr());

    // Dump TSL data to Tecplot file
    std::ofstream tlsos(std::string(infile+std::string("_TSL.dat")).c_str());
    tlsos << "VARIABLES = \"Z\", \"TSL\"" << std::endl;
    tlsos << "ZONE T=\""<< zoneID << "\" I=" << box.length()[2] << " F=POINT" << std::endl;
    for (int k=box.smallEnd()[2]; k<=box.bigEnd()[2]; ++k)
        tlsos << (k+0.5)*dx[2] << "  " << TSL_z[k-box.smallEnd()[2]] << std::endl;
    tlsos.close();

    // Dump TKE data to Tecplot file
    std::ofstream tkeos(std::string(infile+std::string("_TKE.dat")).c_str());
    tkeos << "VARIABLES = \"Z\", \"TKE\"" << std::endl;
    tkeos << "ZONE T=\""<< zoneID << "\" I=" << box.length()[2] << " F=POINT" << std::endl;
    for (int k=box.smallEnd()[2]; k<=box.bigEnd()[2]; ++k)
        tkeos << (k+0.5)*dx[2] << "  " << TKE_z[k-box.smallEnd()[2]] << std::endl;
    tkeos.close();

    // Dump GUS data to Tecplot file
    std::ofstream gusos(std::string(infile+std::string("_GUS.dat")).c_str());
    gusos << "VARIABLES = \"Z\", \"GUS\"" << std::endl;
    gusos << "ZONE T=\""<< zoneID << "\" I=" << GradUSqrd_z.size() << " F=POINT" << std::endl;
    for (int k=0; k<=GradUSqrd_z.size(); ++k)
        gusos << (k+1.5)*dx[2] << "  " << GradUSqrd_z[k] << std::endl;
    gusos.close();
#else
    vFab.setVal(-1.0);
    int idT = -1;
    for (int i=0; i<plotnames.size(); ++i)
        if (plotnames[i] == "temp") idT = i;
	
    std::cout << "Loading T into fab...";
    amrData.FillVar(TMP, amrData.FinestLevel(), "temp");
    TMP.copy(vFab,0,0,1);
    std::cout << "done" << std::endl;

    const int nComp = vFab.nComp();
    Array<Real> Tavg_z(box.length()[2]);
    FORT_TAVG(vFab.dataPtr(),ARLIM(vFab.loVect()),ARLIM(vFab.hiVect()),
              nComp, dx.dataPtr(), box.loVect(), box.hiVect(), Tavg_z.dataPtr());

    // Dump TAVG data to Tecplot file
    std::ofstream tavgos(std::string(infile+std::string("_TAVG.dat")).c_str());
    tavgos << "VARIABLES = \"Z\", \"TAVG\"" << std::endl;
    tavgos << "ZONE T=\""<< zoneID << "\" I=" << box.length()[2] << " F=POINT" << std::endl;
    for (int k=box.smallEnd()[2]; k<=box.bigEnd()[2]; ++k)
        tavgos << (k+0.5)*dx[2] << "  " << Tavg_z[k-box.smallEnd()[2]] << std::endl;
    tavgos.close();

#endif

    BoxLib::Finalize();
}
