
// SPDX-License-Identifier: CC-BY-NC-SA-4.0
//
// Copyright (C) 2026 Bit by Bit Signal Processing LLC (https://bxbsp.com)
//
// This work is placed under the "Creative Commons Attribution
// NonCommercial ShareAlike 4.0 International" license, known
// by the shortened acronym "CC-BY-NC-SA-4.0".
//
// This work 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.
//
// A CC-BY-NC-SA-4.0 license allows you to use this work for
// noncommercial purposes so long as attribution is made to the
// original author.  Modified versions of this work may be distributed,
// but only under the same license.  For further details, see the
// Creative Commons License "CC-BY-NC-SA-4.0".
//
// You should have received a copy of the CC-BY-NC-SA-4.0 license
// along with this work. If not, see
// <https://creativecommons.org/licenses/by-nc-sa/4.0/>.
//

#include "graph_data.hh"
#include <stdlib.h>

graph_data::graph_data(int num_datasets, int num_points, double x_data_start, double x_data_step)
{
  this->num_datasets  = num_datasets;
  this->max_datasets  = num_datasets;
  this->num_points    = num_points;
  this->x_data_start  = x_data_start;
  this->x_data_step   = x_data_step;

  if(max_datasets>MAX_DATASETS)
    {
      printf("The number of curves on a graph exceeds the max.\n");
      abort();
    }
  
  this->y_data = new dataset*[num_datasets];

  for(int g=0; g<max_datasets; g++)
    {
      //printf("in graph_data_static, creating dataset %d with num_points %d\n", g, num_points);
      this->y_data[g] = new dataset(num_points);

      for(int i=0; i<num_points; i++)
	this->y_data[g]->data[i] = 0;
    }

}

graph_data::~graph_data()
{
  for(int g=0; g<max_datasets; g++)
    delete y_data[g];
  delete [] y_data;
}


void graph_data::find_ymin_ymax(double& ymin, double& ymax)
{
  double ymin_in_this_dataset = -1;  // Overridden below if there's any data
  double ymax_in_this_dataset =  1;
  bool first = true;
  
  if(num_datasets && num_points)
    {
      for(int graphitem=0; graphitem<num_datasets; graphitem++)
	{
	  double this_ymin = NAN;
	  double this_ymax = NAN;
	  y_data[graphitem]->find_ymin_ymax(this_ymin, this_ymax);

	  if(isfinite(this_ymin) && isfinite(this_ymax))
	    {
	      if(first)
		{
		  first = false;
		  ymin_in_this_dataset = this_ymin;
		  ymax_in_this_dataset = this_ymax;
		}
	      else
		{
		  ymin_in_this_dataset = (this_ymin<ymin_in_this_dataset) ? this_ymin : ymin_in_this_dataset;
		  ymax_in_this_dataset = (this_ymax>ymax_in_this_dataset) ? this_ymax : ymax_in_this_dataset;
		}
	    }
	}
    }

  ymin = ymin_in_this_dataset;
  ymax = ymax_in_this_dataset;
}
