/*----------------------------------------------------------------------------*/
/*!
Copyright (c) 2018, 2019 by Christian Nowak a.k.a. Creestee a.k.a. chn
Contact: chnowak@web.de or creestee@creestee.com
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. This application may be used and redistributed in source code and binary
form free of charge for personal and for educational purposes.
4. Redistribution and usage of this application in source code or binary form
for commercial purposes requires explicit written permission from the
author.


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 THE COPYRIGHT OWNER 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.

The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the RadarVolumeExplorer project.
*/
/*----------------------------------------------------------------------------*/

#define _USE_MATH_DEFINES
#include <math.h>

#include <QFileInfo>
#include <QRegularExpression>
#include <QSet>

#include "RveRawdata.h"

#include "RveHDF5/RveHDF5Object.h"
#include "RveHDF5/RveHDF5Group.h"

#include <gl/GLU.h>

#ifndef GL_MULTISAMPLE
#define GL_MULTISAMPLE  0x809D
#endif

/*---------------------------------------------------------------------------*/
/*!*/
/*---------------------------------------------------------------------------*/
RveRawdata::RveRawdata( const QString &fname, QObject *parent )
 : QObject( parent ),
   m_Loaded( false ),
   m_Valid( false ),
   m_pHdf5( 0 )
{
   m_Valid = loadHdf5( fname );
}


/*---------------------------------------------------------------------------*/
/*!*/
/*---------------------------------------------------------------------------*/
RveRawdata::~RveRawdata()
{
   if( m_pHdf5 )
   {
      delete m_pHdf5;
      m_pHdf5 = 0;
   }
}


bool RveRawdata::isValid() const
{
   return( m_Valid );
}


QStringList RveRawdata::availableDataMoments() const
{
   return( m_AvailableDataMoments );
}


bool RveRawdata::loadHdf5( const QString &fname )
{
   if( m_pHdf5 )
      delete m_pHdf5;

   m_Valid = false;
   m_FileName = fname;
   m_pHdf5 = new RveHDF5Group();

   if( !RveHDF5Object::load( fname, (RveHDF5Object **)&m_pHdf5 ) )
   {
      delete m_pHdf5;
      m_pHdf5 = 0;
      return( false );
   }

   bool ok = true;

   if( isKnmi36( m_pHdf5 ) )
   {
      ok &= loadMetadataKnmi36( m_pHdf5 );
   } else
   if( isOdim22( m_pHdf5 ) )
   {
      ok &= loadMetadataOdim22( m_pHdf5 );
   } else
   {
      delete m_pHdf5;
      m_pHdf5 = 0;
      ok = false;
   }

   m_Valid = ok;

   return( ok );
}


bool RveRawdata::loadMetadataKnmi36( const RveHDF5Group *pHdf )
{
   RveHDF5Object *pRadarLocation = pHdf->getByPath( "/radar1/radar_location" );
   if( !pRadarLocation )
      return( false );
   if( pRadarLocation->type() != RveHDF5Object::TYPE_ATTRIBUTE )
      return( false );
   RveHDF5Attribute *pRadarLocationAttribute = (RveHDF5Attribute *)pRadarLocation;
   if( pRadarLocationAttribute->attrType() != RveHDF5Attribute::ATTR_FLOAT )
      return( false );
   if( pRadarLocationAttribute->numElements() != 2 )
      return( false );
   if( !pRadarLocationAttribute->getFloat( m_Longitude, 0 ) )
      return( false );
   if( !pRadarLocationAttribute->getFloat( m_Latitude, 1 ) )
      return( false );

   if( !pHdf->getAttrString( "/radar1/radar_name", m_SensorName ) &&
       !pHdf->getAttrString( "/radar1/radar_id", m_SensorName ) )
      return( false );

   if( !pHdf->getAttrFloat( "/radar1/radar_height", m_SensorHeight ) )
      m_SensorHeight = 0.0;

   QString sDateTime;
   if( !pHdf->getAttrString( "/overview/product_datetime_start", sDateTime ) )
      return( false );
   QStringList dt = sDateTime.toLower().trimmed().split( ";" );
   if( dt.size() != 2 )
      return( false );
   QString sDate = dt[0].trimmed();
   QString sTime = dt[1].trimmed();
   QStringList slDate = sDate.split( "-" );
   QStringList slTime = sTime.split( ":" );
   if( slDate.size() != 3 || slTime.size() != 3 )
      return( false );
   bool ok = true;
   int day = slDate[0].trimmed().toInt( &ok );
   if( !ok )
      return( false );
   QMap<QString, int> months;
   months.insert( "jan", 1 );
   months.insert( "feb", 2 );
   months.insert( "mar", 3 );
   months.insert( "apr", 4 );
   months.insert( "may", 5 );
   months.insert( "jun", 6 );
   months.insert( "jul", 7 );
   months.insert( "aug", 8 );
   months.insert( "sep", 9 );
   months.insert( "oct", 10 );
   months.insert( "nov", 11 );
   months.insert( "dec", 12 );
   if( !months.contains( slDate[1].trimmed() ) )
      return( false );
   int month = months.value( slDate[1].trimmed() );
   int year = slDate[2].trimmed().toInt( &ok );
   if( !ok )
      return( false );
   int hour = slTime[0].trimmed().toInt( &ok );
   if( !ok )
      return( false );
   int minute = slTime[1].trimmed().toInt( &ok );
   if( !ok )
      return( false );
   double second = slTime[2].trimmed().toDouble( &ok );
   if( !ok )
      return( false );
   int iSecs = floor( second );
   int iMSecs = (int)( ( ( second - floor( second ) ) * 1000.0 ) + 0.5 );
   m_DateTime = QDateTime( QDate( year, month, day ), QTime( hour, minute, iSecs, iMSecs ), Qt::UTC );

   QSet<QString> dataMoments;
   m_Range = 0.0;
   for( int i = 1; true; i++ )
   {
      RveHDF5Object *pObj = pHdf->getByPath( QString( "/scan%1" ).arg( i ) );
      if( !pObj )
         break;
      if( pObj->type() != RveHDF5Object::TYPE_GROUP )
         break;
      RveHDF5Group *pScan = (RveHDF5Group *)pObj;
      double binSize;
      if( !pScan->getAttrFloat( "scan_range_bin", binSize ) )
         break;
      int numBins;
      if( !pScan->getAttrInteger( "scan_number_range", numBins ) )
         break;
      binSize *= 1000.0;
      double startRange = 0.0;
      double stopRange = binSize * (double)numBins;
      if( m_Range < stopRange )
         m_Range = stopRange;

      QStringList names = pScan->names();
      foreach( QString name, names )
      {
         if( name.startsWith( "scan_" ) && name.endsWith( "_data" ) &&
             pScan->get( name )->type() == RveHDF5Object::TYPE_DATASET )
         {
            QString dataMoment = name.mid( 5, name.size() - ( 5 + 5 ) );
            if( !dataMoments.contains( dataMoment ) )
            {
               dataMoments.insert( dataMoment );
            }
         }
      }
   }

   m_AvailableDataMoments = dataMoments.toList();

   return( true );
}


bool RveRawdata::isOdim22( const RveHDF5Group *pHdf )
{
   if( !pHdf )
      return( false );

   QString sObject;
   if( !pHdf->getAttrString( "/what/object", sObject ) )
   {
      return( false );
   }

   if( sObject.trimmed().toUpper() != "PVOL" )
   {
      return( false );
   }

   QString sVersion;
   if( !pHdf->getAttrString( "/what/version", sVersion ) )
   {
      return( false );
   }

   if( sVersion.trimmed().toLower() != "h5rad 2.2" )
   {
      return( false );
   }

   return( true );
}


bool RveRawdata::isKnmi36( const RveHDF5Group *pHdf )
{
   if( !pHdf )
      return( false );

   QString sHdfVersion;
   if( !pHdf->getAttrString( "/overview/hdftag_version_number", sHdfVersion ) )
      return( false );

   if( sHdfVersion != "3.6" )
      return( false );

   int numRadarGroups = 0;
   pHdf->getAttrInteger( "/overview/number_radar_groups", numRadarGroups );
   if( numRadarGroups != 1 )
      return( false );

   int numScanGroups = 0;
   pHdf->getAttrInteger( "/overview/number_scan_groups", numScanGroups );
   if( numScanGroups < 1 )
      return( false );

   return( true );
}


QString RveRawdata::sensorName() const
{
   return( m_SensorName );
}


QString RveRawdata::text() const
{
   QStringList sl;
   sl.append( QString( "File Name: %1" ).arg( QFileInfo( m_FileName ).fileName() ) );
   sl.append( QString( "Sensor Name: %1" ).arg( m_SensorName ) );
   sl.append( QString( "Timestamp: %1" ).arg( m_DateTime.toString( Qt::ISODate ) ) );
   sl.append( QString( "Longitude: %1" ).arg( m_Longitude ) );
   sl.append( QString( "Latitude: %1" ).arg( m_Latitude ) );
   sl.append( QString( "Data Moment: %1" ).arg( m_DataMoment ) );
   sl.append( QString( "Range: %1km" ).arg( m_Range / 1000.0, 0, 'f', 1, QChar( '0' ) ) );
   
   return( sl.join( "\n" ) );
}


double RveRawdata::minValue() const
{
   return( m_MinValue );
}


double RveRawdata::maxValue() const
{
   return( m_MaxValue );
}


double RveRawdata::beamHeight( double distance, double elevation )
{
   double r = distance;
   double ke = 4.0 / 3.0;
   double ae = 6371.0 * 1000.0;
   double ha = m_SensorHeight;
   double ke_times_ae = ke * ae;
   double phi = elevation * 2.0 * M_PI / 360.0;
   return(
      sqrt( ( r * r ) +
            ( ke_times_ae * ke_times_ae ) +
            ( 2.0 * r * ke_times_ae * sin( phi ) ) )
         - ke_times_ae + ha );
}


QList<double> RveRawdata::elevations() const
{
   return( m_VolumeData.keys() );
}


double RveRawdata::rangeStep( double elevation ) const
{
   return( m_RangeSteps.value( elevation, -DBL_MAX ) );
}


double RveRawdata::numBins( double elevation ) const
{
   return( m_NumBins.value( elevation, -DBL_MAX ) );
}


double RveRawdata::startRange( double elevation ) const
{
   return( m_StartRanges.value( elevation, -DBL_MAX ) );
}


double RveRawdata::stopRange( double elevation ) const
{
   return( m_StopRanges.value( elevation, -DBL_MAX ) );
}


QMap<double, QVector<double> > *RveRawdata::slice( double elevation )
{
   if( !m_VolumeData.contains( elevation ) )
   {
      return( 0 );
   } else
   {
      return( &m_VolumeData[elevation] );
   }
}


bool RveRawdata::isLoaded() const
{
   return( m_Loaded );
}


double RveRawdata::range() const
{
   return( m_Range );
}


double RveRawdata::lon() const
{
   return( m_Longitude );
}


double RveRawdata::lat() const
{
   return( m_Latitude );
}



void RveRawdata::nearestElevation( double elevation, double height, double &elLower, double &elUpper, double &scale ) const
{
   const QVector<double> &elevations = m_Elevations;

   if( elevation <= elevations[0] )
   {
      scale = 1.0;
      elLower = elUpper = elevations[0];
      return;
   } else
   if( elevation >= elevations[elevations.size() - 1] )
   {
      scale = 1.0;
      elLower = elUpper = elevations[elevations.size() - 1];
      return;
   }

   for( int i = 0; i < elevations.size(); i++ )
   {
      if( elevations[i] > elevation )
      {
         elUpper = elevations[i];
         elLower = elevations[i - 1];
         break;
      }
   }

   scale = (elevation - elLower) / (elUpper - elLower);
}


double RveRawdata::nearestAzimuth( double elevation, double azimuth ) const
{
   int n = -1;
   double diff = 0.0;
   const QVector<double> &azimuths = m_Azimuths[elevation];

   for( int i = 0; i < azimuths.size(); i++ )
   {
      double curDiff = fabs( azimuths[i] - azimuth );
      if( curDiff < diff || n < 0 )
      {
         diff = curDiff;
         n = i;
      }
   }

   return( azimuths[n] );
}


bool RveRawdata::loadVolumeKnmi36( const RveHDF5Group *pHdf, const QString &dataMoment )
{
   if( !isKnmi36( pHdf ) )
      return( false );
   if( !m_AvailableDataMoments.contains( dataMoment ) )
      return( false );
   clearVolume();

   m_MinValue = 999999;
   m_MaxValue = -999999;

   for( int i = 1; true; i++ )
   {
      RveHDF5Object *pObj = pHdf->getByPath( QString( "/scan%1" ).arg( i ) );
      if( !pObj )
         break;
      if( pObj->type() != RveHDF5Object::TYPE_GROUP )
         break;
      RveHDF5Group *pScan = (RveHDF5Group *)pObj;

      double elevation;
      if( !pScan->getAttrFloat( "scan_elevation", elevation ) )
         break;

      if( m_Elevations.contains( elevation ) )
         continue;

      int numRays;
      if( !pScan->getAttrInteger( "scan_number_azim", numRays ) )
         break;
      double aziStep;
      if( !pScan->getAttrFloat( "scan_azim_bin", aziStep ) )
         break;
      double binSize;
      if( !pScan->getAttrFloat( "scan_range_bin", binSize ) )
         break;
      int numBins;
      if( !pScan->getAttrInteger( "scan_number_range", numBins ) )
         break;
      binSize *= 1000.0;
      double startRange = 0.0;
      double stopRange = binSize * (double)numBins;

      pObj = pScan->getByPath( QString( "scan_%1_data" ).arg( dataMoment ) );
      if( pObj->type() != RveHDF5Object::TYPE_DATASET )
         break;

      RveHDF5Dataset *pData = (RveHDF5Dataset *)pObj;
      if( pData->numDimensions() != 2 )
         break;
      if( pData->dim( 0 ) != numRays ||
          pData->dim( 1 ) != numBins )
         break;

      int missingDataValue = 0;
      if( !pScan->getAttrInteger( "calibration/calibration_missing_data", missingDataValue ) )
         break;

      QString calibString;
      if( !pScan->getAttrString( QString( "calibration/calibration_%1_formulas" ).arg( dataMoment ), calibString ) )
         break;
      double offset;
      double gain;
      if( !getGainOffset( calibString, gain, offset ) )
         break;

      m_Elevations.append( elevation );
      QVector<double> azimuths;
      for( int i = 0; i < numRays; i++ )
      {
         azimuths.append( (double)i * aziStep );
      }
      m_Azimuths.insert( elevation, azimuths );
      m_NumBins.insert( elevation, numBins );
      m_RangeSteps.insert( elevation, binSize );
      m_StartRanges.insert( elevation, startRange );
      m_StopRanges.insert( elevation, stopRange );

      if( pData->dataType() == RveHDF5Attribute::ATTR_INTEGER )
      {
         if( pData->dataTypeSize() == 2 )
         {
            for( int ray = 0; ray < numRays; ray++ )
            {
               for( int bin = 0; bin < numBins; bin++ )
               {
                  quint16 d = ( (quint16*)pData->data() )[numBins * ray + bin];
                  double value = -DBL_MAX;
                  if( d != missingDataValue )
                  {
                     value = ( (double)d * gain ) + offset;
                     if( value < m_MinValue )
                        m_MinValue = value;
                     else
                     if( value > m_MaxValue )
                        m_MaxValue = value;
                  }
                  m_VolumeData[elevation][azimuths[ray]].push_back( value );
               }
            }
         }
      }
   }

   qSort( m_Elevations );

   m_Loaded = true;
   m_DataMoment = dataMoment;

   return( true );
}


bool RveRawdata::getGainOffset( const QString &calibString, double &gain, double &offset )
{
   QString doubleRegExp = "((\\+|\\-)?\\d+(\\.\\d*)?(E(\\+|\\-)\\d+)?)";
   QRegularExpression regExp( "^GEO=" + doubleRegExp + "\\s*\\*\\s*PV\\s*\\+\\s*" + doubleRegExp + "$" );
   QRegularExpressionMatch match = regExp.match( calibString.toUpper() );

   if( !match.isValid() )
      return( false );

   QString sGain = match.captured( 1 );
   QString sOffset = match.captured( 6 );

   if( sGain.isNull() || sOffset.isNull() )
      return( false );

   bool ok = true;
   gain = sGain.toDouble( &ok );
   if( !ok )
      return( false );
   offset = sOffset.toDouble( &ok );
   if( !ok )
      return( false );

   return( true );
}


bool RveRawdata::loadMetadataOdim22( const RveHDF5Group *pHdf )
{
   if( !isOdim22( pHdf ) )
      return( false );

   QString sDate;
   if( !pHdf->getAttrString( "/what/date", sDate ) )
   {
      return( false );
   }

   QString sTime;
   if( !pHdf->getAttrString( "/what/time", sTime ) )
   {
      return( false );
   }

   m_DateTime = QDateTime( QDate::fromString( sDate.trimmed(), "yyyyMMdd" ), QTime::fromString( sTime.trimmed(), "hhmmss" ), Qt::UTC );

   if( !pHdf->getAttrFloat( "/where/height", m_SensorHeight ) )
   {
      return( false );
   }

   if( !pHdf->getAttrString( "/how/system", m_SensorName ) )
   {
      return( false );
   }

   if( !pHdf->getAttrFloat( "/where/lon", m_Longitude ) )
   {
      return( false );
   }

   if( !pHdf->getAttrFloat( "/where/lat", m_Latitude ) )
   {
      return( false );
   }

   m_Range = 0.0;
   QSet<QString> dataMoments;
   for( int i = 1; true; i++ )
   {
      RveHDF5Object *pObj = pHdf->getByPath( QString( "/dataset%1" ).arg( i ) );
      if( !pObj )
         break;
      if( pObj->type() != RveHDF5Object::TYPE_GROUP )
         continue;

      RveHDF5Group *pDataset = (RveHDF5Group *)pObj;

      double rStep;
      if( !pDataset->getAttrFloat( "/where/rscale", rStep ) )
         continue;
      double startRange;
      if( !pDataset->getAttrFloat( "/where/rstart", startRange ) )
         continue;
      int nbins = -1;
      if( !pDataset->getAttrInteger( "/where/nbins", nbins ) )
         continue;
      double stopRange = startRange + ( (double)nbins * rStep );

      if( m_Range < stopRange )
         m_Range = stopRange;

      for( int j = 1; true; j++ )
      {
         pObj = pDataset->getByPath( QString( "data%1/what" ).arg( j ) );
         if( !pObj )
            break;
         QString dataMoment;
         if( pObj->getAttrString( "quantity", dataMoment ) )
         {
            if( !dataMoments.contains( dataMoment ) )
            {
               dataMoments.insert( dataMoment );
            }
         }
      }
   }

   m_AvailableDataMoments = dataMoments.toList();

   return( true );
}


bool RveRawdata::loadVolumeOdim22( const RveHDF5Group *pHdf, const QString &dataMoment )
{
   if( !isOdim22( pHdf ) )
      return( false );
   if( !m_AvailableDataMoments.contains( dataMoment ) )
      return( false );

   clearVolume();

   m_MinValue = 999999;
   m_MaxValue = -999999;

   double startRange = 0.0;
   double stopRange = 0.0;
   double startAngle = 0.0;
   double stopAngle = 0.0;

   for( int i = 1; true; i++ )
   {
      RveHDF5Object *obj = pHdf->getByPath( QString( "/dataset%1" ).arg( i ) );
      if( !obj )
         break;
      if( obj->type() != RveHDF5Object::TYPE_GROUP )
         continue;
      RveHDF5Group *dataset = (RveHDF5Group *)obj;
      double elevation;
      if( !dataset->getAttrFloat( "/where/elangle", elevation ) )
         continue;
      double rStep;
      if( !dataset->getAttrFloat( "/where/rscale", rStep ) )
         continue;
      if( !dataset->getAttrFloat( "/where/rstart", startRange ) )
         continue;
      int nbins = -1;
      if( !dataset->getAttrInteger( "/where/nbins", nbins ) )
         continue;
      int nrays = -1;
      if( !dataset->getAttrInteger( "/where/nrays", nrays ) )
         continue;
      stopRange = startRange + ( (double)nbins * rStep );

      RveHDF5Object *startazAObj = dataset->getByPath( "/how/startazA" );
      if( !startazAObj )
         continue;
      if( startazAObj->type() != RveHDF5Object::TYPE_ATTRIBUTE )
         continue;
      RveHDF5Attribute *startazA = (RveHDF5Attribute *)startazAObj;
      if( startazA->attrType() != RveHDF5Attribute::ATTR_FLOAT )
         continue;
      nrays = startazA->size() / startazA->elementSize();
      QVector<double> rayAngles;
      for( int ray = 0; ray < nrays; ray++ )
      {
         double angle;
         startazA->getFloat( angle, ray );
         rayAngles.append( angle );
      }

      int nData = -1;
      for( int j = 1; true; j++ )
      {
         QString quantity;
         if( dataset->getAttrString( QString( "/data%1/what/quantity" ).arg( j ), quantity ) )
         {
            if( quantity == dataMoment )
            {
               nData = j;
               break;
            }
         } else
         {
            break;
         }
      }

      if( nData < 0 )
         continue;

      RveHDF5Object *dataObject = dataset->getByPath( QString( "/data%1/data" ).arg( nData ) );
      if( !dataObject )
         continue;
      if( dataObject->type() != RveHDF5Object::TYPE_DATASET )
         continue;
      RveHDF5Dataset *data = (RveHDF5Dataset *)dataObject;
      if( data->numDimensions() != 2 )
         continue;
      if( data->dim( 0 ) != nrays || data->dim( 1 ) != nbins )
         continue;

      double nodata;
      if( !dataset->getAttrFloat( QString( "/data%1/what/nodata" ).arg( nData ), nodata ) )
         continue;

      double undetect;
      if( !dataset->getAttrFloat( QString( "/data%1/what/undetect" ).arg( nData ), undetect ) )
         continue;

      double offset;
      if( !dataset->getAttrFloat( QString( "/data%1/what/offset" ).arg( nData ), offset ) )
         continue;

      double gain;
      if( !dataset->getAttrFloat( QString( "/data%1/what/gain" ).arg( nData ), gain ) )
         continue;

      if( data->dataType() == RveHDF5Attribute::ATTR_FLOAT )
      {
      } else
      if( data->dataType() == RveHDF5Attribute::ATTR_INTEGER )
      {
         QMap<double, QVector<double> > mSlice;

         for( int ray = 0; ray < nrays; ray++ )
         {
            QVector<double> rayData;
            double rayAngle = rayAngles[ray];

            for( int bin = 0; bin < nbins; bin++ )
            {
               double v = -DBL_MAX;
               bool valid = false;
               if( data->dataTypeSize() == 1 )
               {
                  quint8 d = ( (quint8 *)data->data() )[bin + ( nbins * ray )];
                  v = (double)d;
               } else
                  if( data->dataTypeSize() == 2 )
                  {
                     quint16 d = ( (quint16 *)data->data() )[bin + ( nbins * ray )];
                     v = (double)d;
                  } else
                     if( data->dataTypeSize() == 4 )
                     {
                        quint32 d = ( (quint32 *)data->data() )[bin + ( nbins * ray )];
                        v = (double)d;
                     }

                  if( v != nodata && v != undetect )
                  {
                     valid = true;
                     v = offset + ( gain * v );

                     if( v > m_MaxValue )
                        m_MaxValue = v;
                     else
                     if( v < m_MinValue )
                        m_MinValue = v;
                  } else
                  {
                     valid = false;
                     v = -DBL_MAX;
                  }

                  rayData.append( v );
            }

            mSlice.insert( rayAngle, rayData );
         }

         m_VolumeData.insert( elevation, mSlice );
         m_RangeSteps.insert( elevation, rStep );
         m_NumBins.insert( elevation, nbins );
         m_StartRanges.insert( elevation, startRange );
         m_StopRanges.insert( elevation, stopRange );
      }
   }

   m_Elevations = m_VolumeData.keys().toVector();
   qSort( m_Elevations );
   foreach( double elevation, m_Elevations )
   {
      QVector<double> az = m_VolumeData[elevation].keys().toVector();
      qSort( az );
      m_Azimuths.insert( elevation, az );
   }

   m_DataMoment = dataMoment;
   m_Loaded = true;

   return( true );
}


bool RveRawdata::loadVolume( const QString &dataMoment )
{
   if( !m_pHdf5 )
      return( false );
   if( dataMoment.trimmed().isEmpty() )
      return( false );
   if( !m_AvailableDataMoments.contains( dataMoment ) )
      return( false );

   if( isOdim22( m_pHdf5 ) )
   {
      return( loadVolumeOdim22( m_pHdf5, dataMoment ) );
   } else
   if( isKnmi36( m_pHdf5 ) )
   {
      return( loadVolumeKnmi36( m_pHdf5, dataMoment ) );
   }

   return( false );
}


void RveRawdata::clearVolume()
{
   m_VolumeData.clear();
   m_RangeSteps.clear();
   m_StartRanges.clear();
   m_StopRanges.clear();
   m_Elevations.clear();
   m_Azimuths.clear();
}


QString RveRawdata::dataMoment() const
{
   return( m_DataMoment );
}
