/***************************************************************************
**
**  This file is part of ArrayCore.
**
**  ArrayCore is free software: you can redistribute it and/or modify
**  it under the terms of the GNU General Public License as published by
**  the Free Software Foundation, either version 3 of the License, or
**  (at your option) any later version.
**
**  ArrayCore is distributed in the hope that it will be useful,
**  but WITHOUT ANY WARRANTY; without even the implied warranty of
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
**  GNU General Public License for more details.
**
**  You should have received a copy of the GNU General Public License
**  along with Foobar.  If not, see <http://www.gnu.org/licenses/>
**
**  See http://www.geopsy.org for more information.
**
**  Created: 2018-04-12
**  Copyright: 2018-2019
**    Marc Wathelet (ISTerre, Grenoble, France)
**
***************************************************************************/

#include "AsyncStationPair.h"
#include "ArrayStationSignals.h"

namespace ArrayCore {

  /*!
    \class AsyncStationPair AsyncStationPair.h
    \brief Brief description of class still missing

    Full description of class still missing
  */

  /*!
    Description of constructor still missing
  */
  AsyncStationPair::AsyncStationPair()
  {
    TRACE;
    _index1=0;
    _index2=0;
    _station1=0;
    _station2=0;
    _sum=new Complex[6];
    _sum2=new double[6];
    _count=0;
  }

  AsyncStationPair::~AsyncStationPair()
  {
    TRACE;
    delete [] _sum;
    delete [] _sum2;
  }

  void AsyncStationPair::addCrossSpectrum(const GaussianFrequencyBand& f, QString prefix)
  {
    int nFreq=f.maximumIndex();
    Complex z1[3], z2[3], c[6];
    for(int iFreq=f.minimumIndex(); iFreq<=nFreq; iFreq++) {
      double w=f.taperValue(iFreq);
      w*=w;
      z1[0]=_station1->spectrumValue(0, iFreq);
      z1[1]=_station1->spectrumValue(1, iFreq);
      z1[2]=_station1->spectrumValue(2, iFreq);
      z2[0]=_station2->spectrumValue(0, iFreq);
      z2[1]=_station2->spectrumValue(1, iFreq);
      z2[2]=_station2->spectrumValue(2, iFreq);
      int k=0;
      for(int i=0; i<3; i++) {
        for(int j=i; j<3; j++) {
          c[k++]+=z1[i]*conjugate(z2[j])*w;
        }
      }
    }
    for(int i=0; i<6; i++) {
      App::log(prefix+QString(" %1 %2 %3 ").arg(_index1).arg(_index2).arg(i)
                     +c[i].toString('g', 6)+QString(" %1 %2").arg(c[i].abs()).arg(c[i].phase())+"\n");
      _sum[i]+=c[i];
      _sum2[i]+=c[i].abs2();
    }
    _count++;
  }

  Complex AsyncStationPair::mean(int component)
  {
    return _sum[component]/_count;
  }

  double AsyncStationPair::stddev(int component)
  {
    return (_sum2[component]-_count*_sum[component].abs2())/(_count-1.0);
  }

} // namespace ArrayCore

