/****************************************************************************/
/* Copyright (c) 2020 MBARI                                                 */
/* MBARI Proprietary Information. All rights reserved.                      */
/****************************************************************************/
/* Summary  : Average and output the DVL speed wrt water between two times  */
/* Filename : dvl_avg.cpp                                                   */
/* Author   : Henthorn                                                      */
/* Project  : i2MAP                                                         */
/* Version  : 1.0                                                           */
/* Created  : 10/09/2020                                                    */
/* Archived :                                                               */
/****************************************************************************/
/* Modification History:                                                    */
/****************************************************************************/

#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/time.h>

#include "DataLogReader.h"
#include "MathP.h"
#include "TimeTag.h"
#include "FloatData.h"
#include "IntegerData.h"
#include "DataField.h"

void print_avg(double avg)
{
   printf("%.2f\n", avg);
}

int main(int argc, char* argv[])
{
   double avg = -10.;

   if (argc == 3)
   {
      double begin = atof(argv[1]);
      double end   = atof(argv[2]);
      try
      {
         DataLogReader *dvl_log = new DataLogReader("dvl.log");
         dvl_log->read();
         if (begin < dvl_log->timeTag()->value())
            throw Exception("Start time is out of bounds");

         do
         {
            dvl_log->read();
         } while (begin >= dvl_log->timeTag()->value());

         int n = 0;
         double total = 0.;
         do
         {
            DataField *f = NULL;
            double x = 0., y = 0., z = 0.;
            dvl_log->read();
            dvl_log->fields.get(7,&f); x = atof(f->ascii());
            dvl_log->fields.get(8,&f); y = atof(f->ascii());
            dvl_log->fields.get(9,&f); z = atof(f->ascii());

            total += sqrt(pow(x,2) + pow(y,2) + pow(z,2));
            avg = total/++n;

         } while (end >= dvl_log->timeTag()->value());
         //printf("Total = %.2f, n = %d\n", total, n);
      }
      catch (...)
      {
         print_avg(avg);
         return 0;
      }
   }

   print_avg(avg);
   return 0;
}
