//   Match 2.0.1 -- aligns data series using dynamic programming
//   Copyright (C) 2001-2003  Lorraine E. Lisiecki and Philip A. Lisiecki 
//
//This program 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; version 2
//of the License.
//
//This program 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 this program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
//02111-1307, USA.
//
//The original authors reserve the right to license this program or
//modified versions of this program under other licenses at our
//discretion.
//
//If you publish results generated by this software please cite
//Lisiecki, L. E. and P. A. Lisiecki, The application of dynamic
//  programming to the correlation of paleoclimate records,
//  Paleoceanography, 17(D4), 1049, doi:10.1029/2001PA000733, 
//  2002. 
//
//Any questions regarding this license or the operation of this
//software may be directed to Lorraine Lisiecki
//<zogalum@alum.mit.edu>.


#include <math.h>
#include "series.hh"
#include "normalize.hh"

namespace std {}
using namespace std;

// Normalize entire series to have requested mean and standard deviation 
// within the interval between start and end.
// Returns false iff too few data points or std dev is zero. 
bool normalize(series &s, int signalnum, 
	       float start, float end, floatnan mean, floatnan sd) {

  int count=0;
  float sum=0.0;
  float sumsq=0.0;

  for(unsigned i=0; i<s.cores.size(); i++) {
    core &c=*(s.cores[i][signalnum]);
    for(int j=0; j<c.size; j++) {
      if(c[j].x >= start && c[j].x <= end) {
	count++;
	sum += c[j].y;
	sumsq += c[j].y*c[j].y;
      }
    }
  }

  if(count<2) return false;

  float obs_mean=sum/count;
  float obs_sd=sqrt((sumsq*count-sum*sum)/count/(count-1));
  if(obs_sd==0) return false;

  if(mean.my_isnan())
    mean=obs_mean;
  if(sd.my_isnan())
    sd=obs_sd;

  for(unsigned i=0; i<s.cores.size(); i++) {
    core &c=*(s.cores[i][signalnum]);
    for(int j=0; j<c.size; j++) {
      c[j].y=sd*((c[j].y-obs_mean)/obs_sd)+mean;
    }
  }
  
  return true;
}

  
