/*  axsscalg.C   */
/*  Copyright 1990 Mountain Math Software  */
/*  All Rights Reserved                    */
#include "cgidbg.h"
#include "coord.h"
#include "usercom.h"
#include "plotdat.h"
#include "dsp_app.h"


const MinSamplesPerPlot = 3 ;
static const Big = 0x3fffffff ;
const MaxVal = 100000 ;

int AxisScalingX::Rescale(double min, double vir_wid, int Expand,
	int PixelWidth, double Rate)
{
	double VirtualWidth = vir_wid ;
/*
 *	LogOut << "AxisScalingX(" << min << "," << VirtualWidth << ", " <<
 *		Expand << ", PixelWidth = " << PixelWidth << Rate << ")\n" ;
 */
	double OrigNumber = GetSamplesPerPlot();
	if (!OrigNumber) OrigNumber = PixelWidth ;
	double NewNumber ;
	if (!VirtualWidth) VirtualWidth = 1 ;
	if (Expand) NewNumber = 1 + ((OrigNumber-1) *  VirtualWidth)  ;
	else NewNumber = 1 + (OrigNumber-1)  / VirtualWidth ;
	if (NewNumber == OrigNumber) return 0;
	int Changed = 0 ;
	double SaveNumber = NewNumber ;
	if (NewNumber > MaxVal) {
		Changed = 1 ;
		NewNumber = MaxVal ;
		DspApplication::flush_help_info();
		*Output + OutputInfo <<
			"Rescaling limited to no more than " << MaxVal <<
			" samples per plot.\n" <<
			"Plot may be badly scaled.\n" ;
		DspApplication::write_help_info();
	}
	if (NewNumber < MinSamplesPerPlot) {
		Changed = 1 ;
		NewNumber = MinSamplesPerPlot ;
		DspApplication::flush_help_info();
		*Output + OutputInfo << "Rescaling limited to no less than "
			<< MinSamplesPerPlot << " samples per plot.\n" <<
			"Plot may be badly scaled.\n" ;
		DspApplication::write_help_info();
	}
	if (Changed) VirtualWidth *= NewNumber / SaveNumber ;
	double OrigWidth ;
	double SaveMin ;
	double Factor ;
	switch (Scale) {
case PlotScaleFixed:
		OrigWidth = Max - Min ;
		break ;
case PlotScaleRangeAuto:
case PlotScaleAuto:
		OrigWidth = SamplesPerPlot * Rate ;
		break ;
	}
	SaveMin = Min ;
	if (Expand) {
		Min = SaveMin + OrigWidth * min  ;
		Max = SaveMin + OrigWidth * (min + VirtualWidth) ;
	} else {
		double NewWidth = OrigWidth * (NewNumber-1) / (OrigNumber-1) ;
		Min = SaveMin - min * OrigWidth ;
		Max = Min + NewWidth ;
	}
	SetSamplesPerPlot(NewNumber);
/*
 *	LogOut << "Min = " << Min << ", Max = " << Max << ", Samples = "
 *		<< NewNumber << "\n" ;
 */
	return 1;
}

