/*****************************************************************************
*
* Copyright (c) 2000 - 2013, Lawrence Livermore National Security, LLC
* Produced at the Lawrence Livermore National Laboratory
* LLNL-CODE-442911
* All rights reserved.
*
* This file is  part of VisIt. For  details, see https://visit.llnl.gov/.  The
* full copyright notice is contained in the file COPYRIGHT located at the root
* of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html.
*
* Redistribution  and  use  in  source  and  binary  forms,  with  or  without
* modification, are permitted provided that the following conditions are met:
*
*  - Redistributions of  source code must  retain the above  copyright notice,
*    this list of conditions and the disclaimer below.
*  - Redistributions in binary form must reproduce the above copyright notice,
*    this  list of  conditions  and  the  disclaimer (as noted below)  in  the
*    documentation and/or other materials provided with the distribution.
*  - Neither the name of  the LLNS/LLNL nor the names of  its contributors may
*    be used to endorse or promote products derived from this software without
*    specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT  HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR  IMPLIED WARRANTIES, INCLUDING,  BUT NOT  LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND  FITNESS FOR A PARTICULAR  PURPOSE
* ARE  DISCLAIMED. IN  NO EVENT  SHALL LAWRENCE  LIVERMORE NATIONAL  SECURITY,
* LLC, THE  U.S.  DEPARTMENT OF  ENERGY  OR  CONTRIBUTORS BE  LIABLE  FOR  ANY
* DIRECT,  INDIRECT,   INCIDENTAL,   SPECIAL,   EXEMPLARY,  OR   CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT  LIMITED TO, PROCUREMENT OF  SUBSTITUTE GOODS OR
* SERVICES; LOSS OF  USE, DATA, OR PROFITS; OR  BUSINESS INTERRUPTION) HOWEVER
* CAUSED  AND  ON  ANY  THEORY  OF  LIABILITY,  WHETHER  IN  CONTRACT,  STRICT
* LIABILITY, OR TORT  (INCLUDING NEGLIGENCE OR OTHERWISE)  ARISING IN ANY  WAY
* OUT OF THE  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
*****************************************************************************/

// ************************************************************************* //
//                            avtSARFileFormat.C                           //
// ************************************************************************* //

#include <avtSARFileFormat.h>

#include <string>

#include <vtkFloatArray.h>
#include <vtkRectilinearGrid.h>
#include <vtkUnstructuredGrid.h>

#include <avtDatabaseMetaData.h>

#include <InvalidFilesException.h>
#include <InvalidVariableException.h>


using     std::string;


// ****************************************************************************
//  Method: avtSAR constructor
//
//  Programmer: childs -- generated by xml2avt
//  Creation:   Mon Jan 24 14:44:37 PST 2005
//
// ****************************************************************************

avtSARFileFormat::avtSARFileFormat(const char *filename)
    : avtSTSDFileFormat(filename)
{
    // Try to parse out nX, nY, nZ.
    int len = strlen(filename);
    if (len < 18)
    {
        cerr << "Not long enough" << endl;
        EXCEPTION1(InvalidFilesException,
                          "Name must be of the form <text>####x####x####.sar");
    }

    int xStart = len-18;
    int yStart = len-13;
    int zStart = len-8;

    bool nondigit = false;
    for (int i = 0 ; i < 4 ; i++)
    {
        if (! isdigit(filename[xStart+i]))
            nondigit = true;
        if (! isdigit(filename[yStart+i]))
            nondigit = true;
        if (! isdigit(filename[zStart+i]))
            nondigit = true;
    }

    if (nondigit)
    {
        //cerr << "HAS NON DIGIT" << endl;
        //cerr << "X = " << filename + xStart << endl;
        //cerr << "Y = " << filename + yStart << endl;
        //cerr << "Z = " << filename + zStart << endl;
        EXCEPTION1(InvalidFilesException,
                          "Name must be of the form <text>####x####x####.sar");
    }

    nX = atoi(filename + xStart);
    nY = atoi(filename + yStart);
    nZ = atoi(filename + zStart);

    if (nX <= 0 || nY <= 0 || nZ <= 0)
    {
        EXCEPTION1(InvalidFilesException,
                          "Believe dimension of one axis is 0.  "
                          "Name must be of the form <text>####x####x####.sar");
    }
}


// ****************************************************************************
//  Method: avtSARFileFormat::FreeUpResources
//
//  Purpose:
//      When VisIt is done focusing on a particular timestep, it asks that
//      timestep to free up any resources (memory, file descriptors) that
//      it has associated with it.  This method is the mechanism for doing
//      that.
//
//  Programmer: childs -- generated by xml2avt
//  Creation:   Mon Jan 24 14:44:37 PST 2005
//
// ****************************************************************************

void
avtSARFileFormat::FreeUpResources(void)
{
}


// ****************************************************************************
//  Method: avtSARFileFormat::PopulateDatabaseMetaData
//
//  Purpose:
//      This database meta-data object is like a table of contents for the
//      file.  By populating it, you are telling the rest of VisIt what
//      information it can request from you.
//
//  Programmer: childs -- generated by xml2avt
//  Creation:   Mon Jan 24 14:44:37 PST 2005
//
// ****************************************************************************

void
avtSARFileFormat::PopulateDatabaseMetaData(avtDatabaseMetaData *md)
{
    avtMeshType mt = AVT_RECTILINEAR_MESH;
    int nblocks = 1;
    int block_origin = 0;
    int spatial_dimension = 3;
    int topological_dimension = 3;
    double *extents = NULL;
    AddMeshToMetaData(md, "mesh", mt, extents, nblocks, block_origin,
                      spatial_dimension, topological_dimension);


    string mesh_for_this_var = "mesh";
    string varname = "SAR";

    avtCentering cent = AVT_NODECENT;
    AddScalarVarToMetaData(md, varname, mesh_for_this_var, cent);
}


// ****************************************************************************
//  Method: avtSARFileFormat::GetMesh
//
//  Purpose:
//      Gets the mesh associated with this file.  The mesh is returned as a
//      derived type of vtkDataSet (ie vtkRectilinearGrid, vtkStructuredGrid,
//      vtkUnstructuredGrid, etc).
//
//  Arguments:
//      meshname    The name of the mesh of interest.  This can be ignored if
//                  there is only one mesh.
//
//  Programmer: childs -- generated by xml2avt
//  Creation:   Mon Jan 24 14:44:37 PST 2005
//
// ****************************************************************************

vtkDataSet *
avtSARFileFormat::GetMesh(const char *meshname)
{
    int  i;

    if (strcmp(meshname, "mesh") != 0)
        EXCEPTION1(InvalidVariableException, meshname);

    vtkRectilinearGrid *grid = vtkRectilinearGrid::New();
    grid->SetDimensions(nX, nY, nZ);

    vtkFloatArray *x = vtkFloatArray::New();
    x->SetNumberOfTuples(nX);
    for (i = 0 ; i < nX ; i++)
        x->SetTuple1(i, (float) i);
    grid->SetXCoordinates(x);
    x->Delete();

    vtkFloatArray *y = vtkFloatArray::New();
    y->SetNumberOfTuples(nY);
    for (i = 0 ; i < nY ; i++)
        y->SetTuple1(i, (float) i);
    grid->SetYCoordinates(y);
    y->Delete();

    vtkFloatArray *z = vtkFloatArray::New();
    z->SetNumberOfTuples(nZ);
    for (i = 0 ; i < nZ ; i++)
        z->SetTuple1(i, (float) i);
    grid->SetZCoordinates(z);
    z->Delete();

    return grid;
}


// ****************************************************************************
//  Method: avtSARFileFormat::GetVar
//
//  Purpose:
//      Gets a scalar variable associated with this file.  Although VTK has
//      support for many different types, the best bet is vtkFloatArray, since
//      that is supported everywhere through VisIt.
//
//  Arguments:
//      varname    The name of the variable requested.
//
//  Programmer: childs -- generated by xml2avt
//  Creation:   Mon Jan 24 14:44:37 PST 2005
//
// ****************************************************************************

vtkDataArray *
avtSARFileFormat::GetVar(const char *varname)
{
    if (strcmp(varname, "SAR") != 0)
        EXCEPTION1(InvalidVariableException, varname);

    ifstream ifile(filename);
    if (ifile.fail())
    {
        EXCEPTION1(InvalidFilesException, filename);
    }

    int ntuples = nX*nY*nZ;
    vtkFloatArray *rv = vtkFloatArray::New();
    rv->SetNumberOfTuples(ntuples);
    float *ptr = (float *) rv->GetVoidPointer(0);
    float *buff = new float[ntuples];
    ifile.read((char *) buff, ntuples*sizeof(float));
    for (int i = 0 ; i < nX ; i++)
        for (int j = 0 ; j < nY ; j++)
            for (int k = 0 ; k < nZ ; k++)
                 ptr[k*nY*nX + j*nX + i] = buff[i*nY*nZ + j*nZ + k];
    delete [] buff;

    return rv;
}


// ****************************************************************************
//  Method: avtSARFileFormat::GetVectorVar
//
//  Purpose:
//      Gets a vector variable associated with this file.  Although VTK has
//      support for many different types, the best bet is vtkFloatArray, since
//      that is supported everywhere through VisIt.
//
//  Arguments:
//      varname    The name of the variable requested.
//
//  Programmer: childs -- generated by xml2avt
//  Creation:   Mon Jan 24 14:44:37 PST 2005
//
// ****************************************************************************

vtkDataArray *
avtSARFileFormat::GetVectorVar(const char *varname)
{
    EXCEPTION1(InvalidVariableException, varname);
}


