#include <RAT/BinLog.hh>
#include <RAT/Processor.hh>
#include <TMath.h>

namespace RAT {

  void BinLog(TAxis *axis, const Double_t non0start)
  {
    const Int_t bins = axis->GetNbins();
    const Double_t xmin = axis->GetXmin();
    const Double_t xmax = axis->GetXmax();

    const Double_t EPSILON = 1e-12; // smallest possible value
    Bool_t k0start = kFALSE;
    if (xmin<EPSILON) {
      k0start = kTRUE;
      if(non0start<EPSILON) {
        std::string param = Form("%f",non0start);
        throw Processor::ParamInvalid(param, "BinLog bad non0start value");
      }
    }

    Double_t *new_bins = new Double_t[bins + 1];

    const Double_t factor = k0start ? (TMath::Power(xmax/non0start, 1./(bins-1)))
                                    : (TMath::Power(xmax/xmin,      1./bins));

    new_bins[0] = xmin;
    new_bins[1] = k0start ? non0start : (new_bins[0]*factor);

    for (int i = 2; i <= bins; i++) {
      new_bins[i] = factor * new_bins[i-1];
    }
    axis->Set(bins, new_bins);
    delete [] new_bins;
  }

} // namespace RAT