RecalEnergy.cpp 56.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
//
// cpp version of recal_cob
// improved search of the peaks
// using user-defined sources
//
// Dino Bazzacco, August 2014
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////

#include <ctime>
#include <csignal>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <stdlib.h>
#include <cmath>
#include <memory.h>

#include <vector>
#include <algorithm>
#include <functional> 

#include "ReadSpek.h"
#include "FitSpek.h"

using namespace std;

const double  m_pi    = 4.*atan(1.);
const double  s2fwhm  = sqrt(8.*log(2.));

string  specName;
string  specFormat;
int     specLength;
float  *specData   = NULL;
int     specOffset = 0;           // subtracted immediately after peak fit

ReadSpek Spek;    // reading managed by this

int     specNN =  1;     // number of
int     specN0 =  0;     // from
int     specNs =  1;     // step  (todo)

int     specFrom, specTo;

float   specFWHMdef = 10;
float   specAMPLdef =  5;
float  *specFWHM;
float  *specAMPL;

FILE   *testFP = NULL;
float  *testData;
float  testGain = 1;
string testFileName;
string testSuff;     // suffix for the output spectra
bool   testResults = false;

vector<double> specPeaks;
vector<double> Energies;
vector<double> Delendae;

double eBhead;      // band head
double eBstep;      // delta
int    eBnumb = 0;  // numbero of peaks

double refEner;
bool  useTL = true;
bool  useTR = true;

struct Fitted
{
  Fitted() : area(0), posi(0), fwhm(0), fw05(0), fw01(0), tailL(0), tailR(0), eref(-1), good(false) {;}
  double area;
  double ampli;
  double posi;
  double fw05;
  double fw01;
  double fwhm;
  double tailL;
  double tailR;
  int    eref; // the corresponding calibration line, if good==true
  bool   good;
};
vector<Fitted> Peaks;

struct NWA_t
{
  NWA_t() : index(-1), width(0), ampli(0) {;}
  int   index;
  float width;
  float ampli;
};

vector<NWA_t> nwa;

bool   bTwoLines = false;
bool   bOneLine  = false;
bool   doSlope   = true;
bool   doPoly1   = false;   // linear
bool   doPoly2   = false;   // cubic
int    numZero   = 0;       // number of fake peaks at (0,0)
int    modXtalk  = 0;
104
bool   MaxMode  = false;    // Dont fit peaks, only use max position
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344

bool   useErrors = false;   // fit using position and energy errors
double errE      = 0.01;

int    Dmode = 1;   // peak search using first derivative
int    xP_0, xP_1, xP_2, xP_3, xP_4, xP_5, xP_6;
float  xP_minAmpl;
float  xP_fThreshCFA;
int    xP_nMinWidthP;
int    xP_nMinWidthN;
int    xP_nMinWidthP1;
int    xP_nMinWidthP2;

CFitSpek   *m_pCFit;

double slope=0, tshift = 0;
double offset1=0, slope1=0;               // should be generalized to polynomials
double offset2=0, slope2=0, curv2=0;

float hGain = 1;

int  Verbosity = 0;  // &1 PeakFit  &2 CalibPeaks   &4 CalibSort

int  gterminate = 0;

#if 0
//// Sort predicates implemented as a functions
//// sort( Peaks.begin( ), Peaks.end( ), smallerPosi);
bool smallerPosi ( Fitted elem1, Fitted elem2 )
{
  return elem1.posi < elem2.posi;
}
bool largerArea ( Fitted elem1, Fitted elem2 )
{
  return elem1.area > elem2.area;
}
#else
//// Sort predicates implemented as a functors so they can be inlined
//// sort( Peaks.begin( ), Peaks.end( ), smallerPosi() );
struct smallerPosi
{
  bool operator()( Fitted elem1, Fitted elem2 ) {
    return elem1.posi < elem2.posi;
  }
};
struct largerArea
{
  bool operator()( Fitted elem1, Fitted elem2 ) {
    return elem1.area > elem2.area;
  }
};
struct largerAmplitude
{
  bool operator()( Fitted elem1, Fitted elem2 ) {
    return elem1.ampli > elem2.ampli;
  }
};
#endif

// callback for SIGINT
void terminate(int sig) {
  gterminate++;
  if(gterminate > 3)
    exit(EXIT_FAILURE);
}

// functions of ReadATCA
void    getparams (int, char **);
void    numparams (char *, int);
void    initialize();
bool    TestResults(int nspec);
int     PeakSearch1(float * data, int chA, int chB, float fwhm, float minAmpl, std::vector<double>&vPeaks);
int     PeakSearch2(float * data, int chA, int chB, float fwhm, float minAmpl, std::vector<double>&vPeaks);
int     LargePeaks1(float * data, int chA, int chB, float fwhm, float minAmpl, std::vector<double>&vPeaks, int maxNum);
void    SmoothSpek(float *spek, int nchan, double sigma, int ndiff, float *& tSpek, int &start); 
int     xP_Next1(float *yVal, int yLen);
int     xP_Next2(float *yVal, int yLen);
int     FitPeaks(int verbose);
double  ECalibration(int nspe, double& offset1, double& slope1, double& offset2, double& slope2, double& curv2, int verbose);   // energy calibration from position-energy pair(s)
double  TCalibration(int verbose);   // shift of the largest peak from its reference position (to be done)
bool    InvertMatrix3(const double m[9], double invOut[9]);
//double  Calibrated(double x) {
//  if(doSlope) {
//    if(doPoly2) {
//      return offset2 + (slope2 + curv2*x)*x;
//    }
//    else if(doPoly1) {
//      return offset1 + slope1*x;
//    }
//    else {
//      return x*slope;
//    }
//  }
//  return x + tshift;
//}
double  (*Calibrated) (double x) = NULL;
double  Calibrated0(double x) {return slope*x;}
double  Calibrated1(double x) {return offset1 + slope1*x;}
double  Calibrated2(double x) {return offset2 + (slope2 + curv2*x)*x;}
double  CalibratedT(double x) {return tshift  + x;}

clock_t startTime, stopTime;

int main(int argc, char *argv[])
{
  getparams(argc, argv);        // parameters from the command line
  initialize();                 // initialize parameters related to digitisers and detectors

  //gterminate = 0;
  //signal(SIGINT, terminate);
  //cout << "\nAnalysis can be stopped by typing CTRL_C\n" << endl << flush;

  int  evnum = 0;
  bool evok  = true; 
  startTime  = clock();

  for(int nspe = 0; nspe < specNN; nspe++) {

    int ispec = specN0 + nspe*specNs;
    if( !Spek.Read(specLength, ispec) )
      break;
    specData = Spek.Data();

    specFWHMdef = specFWHM[nspe]; 
    specAMPLdef = specAMPL[nspe];
    int np    = 0; 
    int ngood = 0;

    if(bOneLine) 
      np = LargePeaks1(specData, specFrom, specTo, specFWHMdef, specAMPLdef, specPeaks, 1);
    else if(bTwoLines) 
      np = LargePeaks1(specData, specFrom, specTo, specFWHMdef, specAMPLdef, specPeaks, 6);
    else if(Dmode == 1)
      np = PeakSearch1(specData, specFrom, specTo, specFWHMdef, specAMPLdef, specPeaks);
    else
      np = PeakSearch2(specData, specFrom, specTo, specFWHMdef, specAMPLdef, specPeaks);

    //cout << specName << " # " << setw(2) /*<< setfill('0')*/ << nspe /*<< setfill(' ')*/ << setw(5) <<  np << "   ";
    //if(Verbosity) cout << endl;
    //printf("%5d  %s # %5d  ( %3d", nspe, specName.c_str(), ispec, np);
    //printf("%5d # %5d  %3d", nspe, ispec, np);

    if(Verbosity & 1) {
      printf("#1 %5d %6d %4d", nspe, ispec, np);
    }

    slope=0, tshift = 0;
    offset1=0, slope1=0;               // should be generalized to polynomials
    offset2=0, slope2=0, curv2=0;

    if(np) {
      int fp = FitPeaks( Verbosity );
      if(fp) {
        if(specOffset) {               // correct peak positions for specOffs
          for(size_t np = 0; np < Peaks.size(); np++) {
            Peaks[np].posi -= specOffset;
          }
        }
        if(doSlope){
          slope = ECalibration(nspe, offset1, slope1, offset2, slope2, curv2, Verbosity );
          if(slope) {
            for(size_t np = 0; np < Peaks.size(); np++) {
              if( Peaks[np].good ) 
                ngood++;
            }
          }
        }
        else {
          tshift = refEner - Peaks[0].posi;
          ngood  = 1;
        }
      }
    }
    else {
      Peaks.clear();
      if(Verbosity & 1)
        printf("\n");
    }

    if(doSlope) {
      double refPeakPosi=0, refPeakEner=0;
      int iref = -1;;
      if(refEner > 0 && slope) {
        refPeakPosi = refEner/slope;                            // position of the reference peak derived from calibration
        for(size_t irp = 0; irp < Peaks.size(); irp++) {
          if( (abs(Peaks[irp].posi-refPeakPosi) < specFWHMdef)/* && Peaks[irp].good*/ ) { // not restricted to the good peaks
            iref = irp;
            refPeakPosi = Peaks[irp].posi;                      // actual peak position
            refPeakEner = slope*refPeakPosi;
          }
        }
      }
      if(modXtalk==0)
        printf("%6d %6d %4d %3d", nspe, ispec, np, ngood);
      else
        printf("%6d %6d %4d %3d", nspe%modXtalk, ispec/modXtalk, np, ngood);
      double chi2 = 0;
      int nused = 0;
      for(size_t np = 0; np < Peaks.size(); np++) {
        if(Peaks[np].good) {
          nused++;
          double ee = slope*(Peaks[np].posi);
          chi2 += pow(Energies[Peaks[np].eref]-ee, 2);
        }
      }
      chi2 = (nused-1) ? chi2/(nused-1) : 0;
      if(iref>=0) {
        if(modXtalk==0) {
          printf(" %9.2f %8.3f %8.3f %9.0f %9.2f %6.1f %7.0f %7.3f %7.3f",
            refPeakEner, Peaks[iref].fw05*slope, Peaks[iref].fw01*slope,
            Peaks[iref].area, Peaks[iref].posi, Peaks[iref].fwhm, Peaks[iref].ampli, Peaks[iref].tailL, Peaks[iref].tailR);
        }
        else {
          printf(" %9.2f %8.3f %8.3f %9.0f %9.2f %6.1f %7.0f %7.3f %7.3f",
            refPeakEner, Peaks[iref].fw05, Peaks[iref].fw01,
            Peaks[iref].area, Peaks[iref].posi, Peaks[iref].fwhm, Peaks[iref].ampli, Peaks[iref].tailL, Peaks[iref].tailR);
        }
      }
      else {
        printf(" %9.2f %8.3f %8.3f %9.0f %9.2f %6.1f %7.0f %7.3f %7.3f", 0., 0., 0., 0., 0., 0., 0., 0., 0.);
      }
      if(modXtalk==0)
        printf("  %10.6f %6.2f", slope*hGain, min(999.99, chi2*100));
      else {
        if(slope)
          printf("  %12.7f", 1./(slope*hGain));
        else
          printf("  %12.7f", 0.);
      }
      if(doPoly1) {
        double chi2 = 0;
        int nused = 0;
        for(size_t np = 0; np < Peaks.size(); np++) {
          if(Peaks[np].good) {
            nused++;
            double ee = offset1 + slope1*(Peaks[np].posi);
            chi2 += pow(Energies[Peaks[np].eref]-ee, 2);
          }
        }
        chi2 = (nused-2)>0 ? chi2/(nused-2) : 0;
345
        printf(" %9.3f %10.6f %6.2f", offset1, slope1*hGain, min(999.99, chi2*100));
346 347 348 349 350 351 352 353 354 355 356 357
      }
      if(doPoly1 && doPoly2) {
        double chi2 = 0;
        int nused = 0;
        for(size_t np = 0; np < Peaks.size(); np++) {
          if(Peaks[np].good) {
            nused++;
            double ee = offset2 + slope2*Peaks[np].posi + curv2*Peaks[np].posi*Peaks[np].posi;
            chi2 += pow(Energies[Peaks[np].eref]-ee, 2);
          }
        }
        chi2 = (nused-3)>0 ? chi2/(nused-3) : 0;
358
        printf(" %9.3f %10.6f % 10.4e %6.2f", offset2, slope2*hGain, curv2*hGain*hGain, min(999.99, chi2*100));
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
      }
    }
    else {
      printf("%6d %6d %4d %3d", nspe, ispec, np, ngood);
      if(Peaks.size())
        printf(" %9.2f %8.3f %8.3f %9.0f %9.2f %6.1f %7.0f %7.3f %7.3f %11.3f",
          Peaks[0].posi, Peaks[0].fw05, Peaks[0].fw01, 
          Peaks[0].area, Peaks[0].posi, Peaks[0].fwhm, Peaks[0].ampli, Peaks[0].tailL, Peaks[0].tailR, tshift*hGain);
      else
        printf(" %9.2f %8.3f %8.3f %9.0f %9.2f %6.1f %7.0f %7.3f %7.3f %11.3f", 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.);
    }
    printf("\n");

    if(testResults) {
      if(!TestResults(nspe)) {
        cout << "Error writing " << testFileName << endl;
        break;
      }
    }
  }

  // TODO : write the calibration files in the needed formats

  stopTime = clock();
  double realTime = (double)(stopTime - startTime) / CLOCKS_PER_SEC;

  Spek.Close();

  exit(EXIT_SUCCESS);
}

void initialize()
{
  if(specFormat.empty()) {
    int spSize = 0;
    if( !SpecNameDecode(specName, specFormat, specLength) ) {
      specFormat = "UI";    // hopefully
      specLength = 16384;
    }
  }

  if( !Spek.Open(specName, specFormat) ) {
    cerr << "Error opening " << specName << endl; 
    exit(EXIT_FAILURE);
  }

  // exclude the very first and last part of the spectrum
  if(specFrom == specTo) {
    specFrom = int(5*specFWHMdef);
    specTo   = specLength-1 - specFrom;
  }

  cout << "#  Data format " << specFormat << " " << specLength
       << "      Search region " << specFrom << " " << specTo << endl
       << "#" << endl; 

  m_pCFit   = (CFitSpek *) new CFitSpek;

  // enabling the tails should be decided from the command line
  int  npars = m_pCFit->GFitParNumber();
  int* vpars = (int *) new int [npars];
  m_pCFit->GFitParGet(vpars);
  useTL ? vpars[6] |= 1 : vpars[6] &= ~1;   // control of the Tail to the Left
  useTR ? vpars[7] |= 1 : vpars[7] &= ~1;   // control of the Tail to the Right
  if(!doSlope)
    vpars[5] = 0;  // no step for time shifts
  m_pCFit->GFitParSet(vpars);

  specFWHM = new float[specNN];
  specAMPL = new float[specNN];
  for(int nn = 0; nn < specNN; nn++) {
    specFWHM[nn] = specFWHMdef;
    specAMPL[nn] = specAMPLdef;
  }
  for(size_t nn = 0; nn < nwa.size(); nn++) {
    int ii = nwa[nn].index;
    if(ii >= 0 && ii < specNN) {
      specFWHM[ii] = nwa[nn].width;
      specAMPL[ii] = nwa[nn].ampli;
    }
  }

  for(int nn = 0; nn < eBnumb; nn++)
    Energies.push_back(eBhead + eBstep*nn);

  if(Energies.size() < 1) {
    Energies.push_back(1173.238);
    Energies.push_back(1332.513);
  }
  if(Delendae.size()) {
    for(size_t dd = 0; dd < Delendae.size(); dd++) {
      size_t closest = 1;
      double delta   = fabs(Delendae[dd]-Energies[0]);
      for (size_t nn = 1; nn < Energies.size(); nn++) {
        if(fabs(Delendae[dd]-Energies[nn]) < delta) {
          closest = nn;
          delta   = fabs(Delendae[dd]-Energies[nn]);
        }
      }
      Energies.erase(Energies.begin()+closest);
    }
  }
  sort( Energies.begin( ), Energies.end( ) );
  if(doSlope)
    cout << "#  " << "Energies used for the calibration " << endl;
  else
    cout << "#  " << "Position used for the calibration " << endl;
  for (size_t nn = 0; nn < Energies.size(); nn++) {
    cout << "#  " << setw(3) << nn << fixed << setprecision(3) << setw(10) << Energies[nn] << endl;
  }
  if(Energies.size()==1) {
    bOneLine  = true;
    bTwoLines = false;
    refEner = Energies[0];
  }
  else if(Energies.size()==2) {
    bOneLine  = false;
    bTwoLines = true;
    if(!refEner) {
      refEner = Energies[1];
    }
    else {
      if(abs(refEner-Energies[0])>1. && abs(refEner-Energies[1])>1.)
        refEner = Energies[1];
    }
  }
  else {
    bOneLine  = false;
    bTwoLines = false;
    if(!refEner)
      refEner = Energies[Energies.size()-1];
  }

  if(testResults) {
    ostringstream name;
    name << "Recal__" << specNN << "-" << specLength << "-F__" << testSuff << ".dat" ;
    testFileName = name.str();
    testFP = fopen(testFileName.c_str(), "wb");
    if(!testFP) {
      cerr << "Error opening " << testFileName << endl; 
      exit(EXIT_FAILURE);
    }
    testData = new float[specLength];
    memset(testData, 0, sizeof(float)*specLength);
  }

  if(!doSlope)     Calibrated = CalibratedT;
  else if(doPoly2) Calibrated = Calibrated2;
  else if(doPoly1) Calibrated = Calibrated1;
  else             Calibrated = Calibrated0;

  cout << "#  " << endl;
  cout << "#  " << "Spectra taken from file : " << specName << endl;
  if(testResults)
    cout << "#  Calibrated spectra written to : " << testFileName << endl;


  cout << "#  " << endl;
  if(doSlope) {
    if(modXtalk==0) {
      cout << "# indx  #spec #pks #ok   rEnergy     FW05     FW01      Area  Position  Width   Ampli    WTML    WTMR  slope*gain rChi2%";
      if(doPoly1)
        cout << "   offs1*g   slope1*g rChi2%";
      if(doPoly2)
        cout << "   offs2*g   slope2*g    coeff2*g  rChi2%";
    }
    else {
      cout << "# indx  #spec #pks #ok   rEnergy     FW05     FW01      Area  Position  Width   Ampli    WTML    WTMR    cross-talk";
    }
      
  }
  else {
      cout << "# indx  #spec #pks #ok   rEnergy     FW05     FW01      Area  Position  Width   Ampli    WTML    WTMR  shift*gain";
  }
  cout << "\n# " << endl; 

}

void
getparams(int argc, char *argv[])
{
  int   argn;
  char *cmd;
  int   ok;

  ok = (argc > 1) ? 1 : 0;
  argn = 1;

  while(ok == 1 && argn < argc) {
    cmd = argv[argn++];
    ok  = 1;
    if(!strcmp(cmd, "-h")) {
      ok = -1;
    }
    else if(!strcmp(cmd, "-spe")) {
      numparams(cmd, argc-argn-1);
      specName = argv[argn++];
    }
    else if(!strcmp(cmd, "-num")) {
      numparams(cmd, argc-argn-1);
      specNN = atoi(argv[argn++]);
    }
    else if(!strcmp(cmd, "-sub")) {
      numparams(cmd, argc-argn-1);
      specN0 = atoi(argv[argn++]);
    }
    else if(!strcmp(cmd, "-step")) {
      numparams(cmd, argc-argn-1);
      specNs = atoi(argv[argn++]);
    }
    else if(!strcmp(cmd, "-fmt")) {
      numparams(cmd, argc-argn-2);
      specFormat = argv[argn++];
      specLength = atoi(argv[argn++]);
    }
    else if(!strcmp(cmd, "-offs")) {
      numparams(cmd, argc-argn-1);
      specOffset = atoi(argv[argn++]);
    }
    else if(!strcmp(cmd, "-lim")) {
      numparams(cmd, argc-argn-2);
      specFrom = atoi(argv[argn++]);
      specTo   = atoi(argv[argn++]);
    }
    else if(!strcmp(cmd, "-dwa")) {
      numparams(cmd, argc-argn-2);
      specFWHMdef = (float)atof(argv[argn++]);
      specAMPLdef = (float)atof(argv[argn++]);
    }
    else if(!strcmp(cmd, "-nwa")) {
      numparams(cmd, argc-argn-3);
      NWA_t tnwa;
      tnwa.index = atoi(argv[argn++]);
      tnwa.width = (float)atof(argv[argn++]);
      tnwa.ampli = (float)atof(argv[argn++]);
      nwa.push_back(tnwa);
    }
    else if(!strcmp(cmd, "-gain")) {
      numparams(cmd, argc-argn-1);
      hGain = float(atof(argv[argn++]));
    }
    else if(!strcmp(cmd, "-verbose")) {
      Verbosity = 0xFFFF;
    }
    else if(!strcmp(cmd, "-poly1")) {
      doPoly1 = true;
    }
    else if(!strcmp(cmd, "-poly2")) {
      doPoly1 = true;
      doPoly2 = true;
    }
    else if(!strcmp(cmd, "-zero")) {
      numZero++;
    }
613 614 615
    else if(!strcmp(cmd, "-max")) {
      MaxMode = true;
    }
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
    else if(!strcmp(cmd, "-errors")) {
      numparams(cmd, argc-argn-1);
      errE = float(atof(argv[argn++]));
      useErrors = true;;
    }
    else if(!strcmp(cmd, "-D1")) {
      Dmode = 1;
    }
    else if(!strcmp(cmd, "-D2")) {
      Dmode = 2;
    }
    else if(!strcmp(cmd, "-noTL")) {
      useTL = false;
    }
    else if(!strcmp(cmd, "-noTR")) {
      useTR = false;
    }
    else if(!strcmp(cmd, "-Xtalk")) {
      numparams(cmd, argc-argn-1);
      modXtalk = atoi(argv[argn++]);
    }
    else if(!strcmp(cmd, "-T")) {
      numparams(cmd, argc-argn-1);
      Energies.clear();
      Energies.push_back(atof(argv[argn++]));
      doSlope = false;
    }
    else if(!strcmp(cmd, "-v")) {
      numparams(cmd, argc-argn-1);
      Verbosity = atoi(argv[argn++]);
    }
    // Energies are taken from TkT, excluding some weak peaks
    else if(!strcmp(cmd, "-22Na")) {
      Energies.push_back( 511.006);
      Energies.push_back(1274.545);
    }
    else if(!strcmp(cmd, "-56Co")) {
      Energies.push_back( 846.772);
      Energies.push_back(1037.840);
      Energies.push_back(1175.102);
      Energies.push_back(1238.282);
      Energies.push_back(1360.250);
      Energies.push_back(1771.351);
      Energies.push_back(2015.181);
      Energies.push_back(2034.755);
      Energies.push_back(2598.458);
      Energies.push_back(3201.962);
      Energies.push_back(3253.416);
      Energies.push_back(3272.990);
      Energies.push_back(3451.152);
      Energies.push_back(3547.925);
    }
    else if(!strcmp(cmd, "-40K")) {
      Energies.push_back(1460.81);       // increase precision
    }
    else if(!strcmp(cmd, "-57Co")) {
      //Energies.push_back(  14.4130);
      Energies.push_back( 122.0614);
      Energies.push_back( 136.4743);
    }
    else if(!strcmp(cmd, "-60Co")) {
      Energies.push_back(1173.238);
      Energies.push_back(1332.513);
    }
    else if(!strcmp(cmd, "-88Y")) {
      Energies.push_back( 898.045);
      Energies.push_back(1836.062);
      //Energies.push_back(2734.087);
    }
    else if(!strcmp(cmd, "-133Ba")) {
      Energies.push_back(  53.156);
      Energies.push_back(  79.623);
      Energies.push_back(  80.999);
      Energies.push_back( 160.609);
      Energies.push_back( 223.116);
      Energies.push_back( 276.404);
      Energies.push_back( 302.858);
      Energies.push_back( 356.014);
      Energies.push_back( 383.859);
    }
    else if(!strcmp(cmd, "-134Cs")) {
      Energies.push_back( 475.36);
      Energies.push_back( 563.27);
      Energies.push_back( 569.30);
      Energies.push_back( 604.68);
      Energies.push_back( 795.78);
      Energies.push_back( 801.86);
      Energies.push_back(1038.53);
      Energies.push_back(1167.89);
      Energies.push_back(1365.17);
    }
    else if(!strcmp(cmd, "-137Cs")) {
      Energies.push_back( 661.661);
    }
    else if(!strcmp(cmd, "-152Eu")) {
      Energies.push_back( 121.7793);
      Energies.push_back( 244.6927);
      Energies.push_back( 344.2724);
      Energies.push_back( 411.111);
      Energies.push_back( 443.979);
      Energies.push_back( 778.890);
      Energies.push_back( 964.014);
      Energies.push_back(1085.793);
      //Energies.push_back(1089.700);
      Energies.push_back(1112.070);
      Energies.push_back(1407.993);
    }
    else if(!strcmp(cmd, "-208Pb")) {
      Energies.push_back(2614.5);   // increase precision
    }
    else if(!strcmp(cmd, "-226Ra")) {
      Energies.push_back( 186.211);
      Energies.push_back( 241.981);
      Energies.push_back( 295.213);
      Energies.push_back( 351.921);
      Energies.push_back( 609.312);
      Energies.push_back( 768.356);
      Energies.push_back( 934.061);
      Energies.push_back(1120.287);
      Energies.push_back(1238.110);
      Energies.push_back(1377.669);
      Energies.push_back(1509.228);
      Energies.push_back(1729.595);
      Energies.push_back(1764.494);
      Energies.push_back(1847.420);
      Energies.push_back(2118.551);
      Energies.push_back(2204.215);
      Energies.push_back(2447.810);
    }
    else if(!strcmp(cmd, "-241Am")) {
      Energies.push_back(  26.345);
      Energies.push_back(  59.537);
    }
    else if(!strcmp(cmd, "-ener")) {
      numparams(cmd, argc-argn-1);
      Energies.push_back(atof(argv[argn++]));
    }
    else if(!strcmp(cmd, "-band")) {
      numparams(cmd, argc-argn-3);
      eBhead = atof(argv[argn++]);
      eBstep = atof(argv[argn++]);
      eBnumb = atoi(argv[argn++]);
    }
    else if(!strcmp(cmd, "-kill")) {
      numparams(cmd, argc-argn-1);
      Delendae.push_back(atof(argv[argn++]));
    }
    else if(!strcmp(cmd, "-ref")) {
      numparams(cmd, argc-argn-1);
      refEner = atof(argv[argn++]);
    }
    else if(!strcmp(cmd, "-out")) {
      numparams(cmd, argc-argn-2);
      testGain = float(atof(argv[argn++]));
      testSuff = argv[argn++];
      testResults = true;
    }
    else {
      ok = 0;
    }
  }

  if(ok && specName.empty()) {
    cout << endl << "Name of spectrum to analyze must be given !" << endl;
    ok = -1;
  }

  if(ok < 1) {
    if(ok == 0 && argc > 1) cout << "\nInvalid switch " << argv[argn-1] << endl;
    cout << "\nUsage: " << argv[0] << " -spe file [...]" << endl << endl;
    cout << "  -h                    print this list and exit" << endl;
    cout << "  -spe   filename       name of spectrum to analyze (mandatory)" << endl;
    cout << "  -fmt   type nchan     format of the data and number of channels (if not encoded in filename)" << endl;
    cout << "                        valid formats: A C UC S US I UI L UL F D" << endl;
    cout << "  -num   nn             number of subspectra to analyze [" << specNN << "]" << endl;
    cout << "  -sub   first          analysis starts from subspectrum [" << specN0 << "]" << endl;
    cout << "  -step  step           analysis proceeds incrementing subspectrum by [" << specNs << "]" << endl;
    cout << "  -offs  nchan          channel offset to subtract to the position of the peaks [" << specOffset <<"]" << endl;
    cout << "  -lim   from to        limit the search to this range in channels" << endl;
    cout << "  -dwa   fwhm ampl      default fwhm and minmum amplitude for the peaksearch [" << specFWHMdef << " " << specAMPLdef << "]" << endl;
    cout << "  -nwa   nn fwhm ampl   fwhm and minmum amplitude for spectrum nn (can be given more than once)" << endl;
    cout << "  -ref   energy         energy (keV) of the reference peak for extended printouts" << endl;
    cout << "  -poly1                linear    calibration y = offset + slope*x" << endl;
    cout << "  -poly2                parabolic calibration y = offset + slope*x + curv*x*x" << endl;
    cout << "  -zero                 add a fake peak at (0,0) to push calibration through origin" << endl;
    cout << "  -gain  val            scaling factor for the slope [" << hGain << "]" << endl;
    cout << "  -out   gain tag       produce calibrated spectra (Recal__num-nchan-F__tag.dat) with the given dispersion and tag [" << testGain << "]" << endl;
    cout << "  -D1                   use the 1st-derivative search (default, always for 2-line sources)" << endl;
    cout << "  -D2                   use the 2nd-derivative search" << endl;
    cout << "  -noTL                 disable using the Left  Tail in peak fit" << endl;
    cout << "  -noTR                 disable using the Right Tail in peak fit" << endl;
    cout << "  -Xtalk mod            print results as when calculating xTalk coefficients mod==36/37/38" << endl;
    cout << "  -T     position       calculate shift of the largest peak with respect to the given position" << endl;
    cout << "  -v     level          verbosity bit0=fit_details, bit1=calib_details, bit2=more_calib_details [" << Verbosity << "]" << endl;
    cout << "  -ener  energy         add this energy to the list of lines (can be given more than once)" << endl;
    cout << "  -band  e0 step num    generate a band startin at e0 with num peaks spaced by step keV" << endl;
    cout << "  -kill  energy         remove the line closest to this energy from the list of lines" << endl;
    cout << "      List of available sources (more than one allowed; 60Co if nothing given)"  << endl;
    cout << "  -22Na -40K -56Co -57Co -60Co -88Y -133Ba -134Cs -137Cs -152Eu -208Pb -226Ra -241Am"  << endl;
    cout << " " << endl;
    exit(EXIT_FAILURE);
  }

  // echo the command line
  time_t ltime;
  time(&ltime);

  cout << "#  " << ctime(&ltime);
  cout << "#  " << endl;
  cout << "#  " << argv[0] << endl;
  cout << "#  ";
  for(int nn = 1; nn < argc; nn++)
    cout << argv[nn] << " ";
  cout << endl;
  cout << "#  " << endl;
}

void
numparams(char * cmd, int nn)
{
  if(nn >= 0) return;
  nn = -nn;
  printf("error decoding command %s ==> %d parameter(s) missing \n", cmd, nn);
  exit(EXIT_FAILURE);
}

bool TestResults(int nspec)
{
  // delete previous
  memset(testData, 0, sizeof(float)*specLength);

  // fill with calibrated spectrum
  double e0(0), e1(0);  // calibrated beginning and end of channel
  e1 = Calibrated(0)*testGain;
  for(int nn = 0; nn < specLength; nn++) {
    e0 = e1;
    e1 = Calibrated(nn)*testGain;
    double val = specData[nn];
    int n0 = int(e0);
    int n1 = int(e1);
    if(n0 == n1) {        // all in one channel
      if(n0 >=0 && n0 < specLength)
        testData[n0] += float(val);
    }
    else if (n0 < n1) {   // spread linearly in the target range
      val /= (e1-e0);
      if(n0 >=0 && n0 < specLength)
        testData[n0] += float(val*(n0+1-e0));
      for(int ii = n0+1 ; ii < n1; ii++) {
        if(ii >=0 && ii < specLength)
          testData[ii] += float(val);
      }
      if(n1 >=0 && n1 < specLength)
        testData[n1] += float(val*(e1-n1));
    }
    else {                //  spread linearly in the target range, in reverse order
      val /= (e0-e1);
      {int nt = n0; n0 = n1; n1 = nt;}
      if(n0 >=0 && n0 < specLength)
        testData[n0] += float(val*(n0+1-e1));
      for(int ii = n0+1; ii < n1; ii++) {
        if(ii >=0 && ii < specLength)
          testData[ii] += float(val);
      }
      if(n1 >=0 && n1 < specLength)
        testData[n1] += float(val*(e0-n1));
    }
  }

  // write result
  int nn = fwrite(testData, sizeof(float), specLength, testFP);

  return (nn == specLength);
}




// - smooth the spectrum with a gaussian kernel
// - differentiate ONCE
// Loop (maxNum times)
//   find the minimum of the derivative and the associated +++--- pattern
//   accept it with conditions with the cross-over as peak position
//   erase the region
// 
int  LargePeaks1(float *m_pSpek, int chA, int chB, float fwhm, float minAmpl, std::vector<double>&vPeaks, int maxNum)
{
  //CheckLimits(chA, chB);
  int nChan = chB-chA+1;

  double  sigma = fwhm/s2fwhm;
  float  *tSpek = NULL;     // the smoothed and differentiated spectrum
  int     xMin  = 0;        // position of chA in tSpek
  SmoothSpek(m_pSpek+chA, nChan, sigma, 1, tSpek, xMin);
  int xMax = xMin + nChan;  // position of chB+1 in tSpek

  // ready to search peaks from xMin to xMax
  vPeaks.clear();

  // put here sensible values
  xP_minAmpl     = float(0.5*abs(minAmpl*exp(-.5)/sigma)); // max(g') = |g'(sigma)| = g(0)*exp(-0.5)/sigma
  xP_fThreshCFA  = 0;
  xP_nMinWidthP  = max(2, int(fwhm)-2);
  xP_nMinWidthN  = max(2, int(fwhm)-2);

  while(vPeaks.size() < size_t(maxNum)) {
    // variables named as in xP_Next1
    xP_0 = xP_1 = xP_2 = -1; // positive lobe
    xP_3 = xP_4 = xP_5 = -1; // negative lobe
    // find the largest negative peak
    float yMin = 0;
    for(int nn = xMin+1; nn < xMax; nn++) {
      if(tSpek[nn] < yMin) {
        yMin = tSpek[nn];
        xP_4 = nn;
      }
    }
    if(xP_4 < 0)
      break;      // empty?
    // find the zero crossing at the left of the minimum
    for(int nn = xP_4; nn > xMin; nn--) {
      if(tSpek[nn] > 0) {
        xP_2 = nn;
        break;
      }
    }
    if(xP_2 < 0)
      break;
    xP_3 = xP_2 + 1;
    // find the end of the negative lobe
    for(int nn = xP_3; nn < xMax; nn++) {
      if(tSpek[nn] >= 0) {
        xP_5 = nn;
        break;
      }
    }
    if(xP_5 < 0)
      break;
    // find the beginning of the positive lobe, and the maximum
    float yMax = 0;
    for(int nn = xP_2; nn > xMin; nn--) {
      if(tSpek[nn] <= 0) {
        xP_0 = nn;
        break;
      }
      if(tSpek[nn] > yMax) {
        yMax = tSpek[nn];
        xP_1 = nn;
      }
    }
    if(xP_0 < 0)
      break;
    int widthP = xP_2-xP_0;
    int widthN = xP_5-xP_3;
    bool good = true;
    if(widthP < xP_nMinWidthP || widthN < xP_nMinWidthN)
      good = false;
    if(yMax < xP_minAmpl || yMin > -xP_minAmpl)
      good = false;
    float cmp = abs(yMax/yMin);
    if(cmp < 0.2f || cmp > 2.f)
      good = false;
    if(good) {
      // peak position is transition from positive to negative
      double xPos = 0.5f*(xP_2+xP_3);     // position of peak in tSpek coordinates
      vPeaks.push_back(xPos-xMin+chA+1);  //     ""            m_pSpek   ""
    }
    // zero the region
    for(int nn = xP_0; nn <xP_5; nn++)
      tSpek[nn] = 0;
  }

#if 0
  // Copy back (the remaining part of) the working spectrum
  memcpy(m_pSpek+chA, tSpek+xMin, sizeof(float)*nChan);
  float scale = float(sigma/exp(-.5));
  for(int nn = chA; nn < chA+nChan; nn++)
    m_pSpek[nn] *= scale;
#endif

  delete [] tSpek;

  return vPeaks.size();
}

// imported from TkT
// - smooth the spectrum with a gaussian kernel
// - differentiate ONCE
// Loop
//   look for the +++--- pattern with conditions on its shape and amplitude
//   test significance of peak before accepting it (nothing yet)
// 
int  PeakSearch1(float *m_pSpek, int chA, int chB, float fwhm, float minAmpl, std::vector<double>&vPeaks)
{
  //CheckLimits(chA, chB);
  int nChan = chB-chA+1;

  double  sigma = fwhm/s2fwhm;
  float  *tSpek = NULL;     // the smoothed and differentiated spectrum
  int     xMin  = 0;        // position of chA in tSpek
  SmoothSpek(m_pSpek+chA, nChan, sigma, 1, tSpek, xMin);
  int xMax = xMin + nChan;  // position of chB+1 in tSpek

  // ready to search peaks from xMin to xMax
  vPeaks.clear();

  // put here sensible values
  xP_minAmpl     = float(0.5*abs(minAmpl*exp(-.5)/sigma)); // max(g') = |g'(sigma)| = g(0)*exp(-0.5)/sigma
  xP_fThreshCFA  = 0;
  xP_nMinWidthP  = max(2, int(fwhm)-2);
  xP_nMinWidthN  = max(2, int(fwhm)-2);

  int xx = xMin;
  while(xx < xMax) {
    if( xP_Next1(tSpek+xx, nChan-xx) <= 0 )
      break;
    // peak position is transition from positive to negative
    double xPos = xx + 0.5f*(xP_2+xP_3);      // position of peak in tSpek coordinates
    vPeaks.push_back(xPos + chA + 1 - xMin);  //     ""            m_pSpek   ""
    xx += xP_5;
  }

#if 0
  //// Copy back the differentiated spectrum so that the caller can reconstruct
  //// the smoothed spectrum by one running integrations (SI). 
  //// The reconstruction is exact only if the initial part of the original spectrum
  //// is zero for more than nKern channels, otherwise the passed-back part does
  //// not contain the whole information and this can cause offset-like effects.
  memcpy(m_pSpek+chA, tSpek+xMin, sizeof(float)*nChan);
  float scale = float(sigma/exp(-.5));
  for(int nn = chA; nn < chA+nChan; nn++)
    m_pSpek[nn] *= scale;
#endif

  delete [] tSpek;

  return vPeaks.size();
}

// imported from TkT
// - smooth the spectrum with a gaussian kernel
// - differentiate TWICE
// Loop
//   look for the next mexican-hat pattern with conditions on its shape and amplitude
//   test significance of peak before accepting it (nothing yet)
// 
int PeakSearch2(float *m_pSpek, int chA, int chB, float fwhm, float minAmpl, std::vector<double>&vPeaks)
{
  //CheckLimits(chA, chB);
  int nChan = chB-chA+1;

  double  sigma = fwhm/s2fwhm;
  float  *tSpek = NULL;     // the smoothed and differentiated spectrum
  int     xMin  = 0;        // position of chA in tSpek
  SmoothSpek(m_pSpek+chA, nChan, sigma, 2, tSpek, xMin);
  int xMax = xMin + nChan;  // position of chB+1 in tSpek

  // ready to search peaks from xMin to xMax
  vPeaks.clear();

  // put here sensible values
  xP_minAmpl     = float(abs(minAmpl/(sigma*sigma))); // max(g'') =  |g''(0)| = |g(0)|/sigma**2
  xP_fThreshCFA  = 0;
  xP_nMinWidthN  = max(2, int(fwhm)-2);
  xP_nMinWidthP1 = max(2, xP_nMinWidthN-1);
  xP_nMinWidthP2 = max(2, (xP_nMinWidthN+1)/2);

  int xx = xMin;
  while(xx < xMax) {
    if( xP_Next2(tSpek+xx, xMax-xx) <= 0 )
      break;
    // first moments of the negative lobe to get the peak position
    float xP0 = 0, xP1 = 0;
    int nn0 = xx + xP_2 + 1;
    int nn1 = xx + xP_4 + 1;
    for(int nn = nn0; nn < nn1; nn++) {
      float x = float(nn-nn0)+0.5f;
      float y = tSpek[nn];
      xP0 += y;
      xP1 += y*x;
    }
    float xPos = nn0 + xP1/xP0;           // position of peak in tSpek coordinates
    vPeaks.push_back(xPos + chA - xMin);  //     ""            m_pSpek   ""
    xx += xP_4;
  }

#if 0
  //// Copy back the double-diff spectrum so that the caller can reconstruct
  //// the smoothed spectrum by two successive running integrations (SI). 
  //// The reconstruction is exact only if the initial part of the original spectrum
  //// is zero for more than nKern channels, otherwise the passed-back part does
  //// not contain the whole information and this can cause offset-like effects.
  memcpy(m_pSpek+chA, tSpek+xMin, sizeof(float)*nChan);
  float scale = float(sigma*sigma);
  for(int nn = chA; nn < chA+nChan; nn++)
    m_pSpek[nn] *= scale;
#endif

  delete [] tSpek;

  return vPeaks.size();
}

// generates a smoothed and differentiated version of the input data
// returns the  pointer and the position of the first valid channel
// the caller has to free tSpek
void SmoothSpek(float *spek, int nchan, double sigma, int ndiff, float *&tSpek, int &start)
{
  // generate the gaussian kernel for the smoothing operation
  int     nKern  = 2*int(5.5*sigma)+1;    // < 1ppm
  int     zKern  =  nKern/2;
  double  gfact1 = -1./(2.*sigma*sigma);
  double  gfact2 = 1./(sigma*sqrt(2.*m_pi));

  float  *gKern  = new float [nKern];
  for(int nn = 0; nn <= zKern; nn++) {
    double gvalue = gfact2*exp( ((nn-zKern)*(nn-zKern))*gfact1 );
    gKern[nn] = gKern[nKern-1-nn] = float(gvalue);
  }

  // the temporary space for the data
  int tLen = nKern + nchan + nKern;

  start = nKern;
  tSpek = new float [tLen];

  // copy the original spectrum to the temporary storage,
  // leaving nKern empty channels on both sides
  memset(tSpek, 0, sizeof(float)*nKern);
  memcpy(tSpek+nKern, spek, nchan*sizeof(float));
  memset(tSpek+nKern+nchan, 0, sizeof(float)*nKern);

  // convolution --> the resulting spectrum is right shifted by zKern channels
  for(int ii = tLen-1; ii >= nKern; ii--) {
    float csum = 0;
    for(int jj = 0; jj < nKern; jj++)
      csum += gKern[jj]*tSpek[ii-jj];
    tSpek[ii] = csum;
  }
  start += zKern;

  // differentiate as requested
  for(int nd = 0; nd < ndiff; nd++) {
    for(int ii = tLen-1; ii >0; ii--)
      tSpek[ii] -= tSpek[ii-1];
  }
  //start += ndiff/2;

  delete [] gKern;
}

// trigger on a +++--- sequence, first derivative of a gaussian
// with conditions on the width and amplitude of the lobes
int xP_Next1(float *yDat, int yLen)
{
  enum {
    stateUnknown,   // initial or negative before starting a new sequence
    stateP,         // positive: xP_0(first positive chan),xP_1(max), xP_2(last positive)
    stateN,         // negative: xP_3(first negative), xP_4(min), xP_5(last negative)
  };

  int    state = stateUnknown;            // start in an indefinite state
  int    widthP = 0, widthN = 0;
  float  yMax, yMin;

  for(int nn = 0; nn < yLen; nn++) {
    float yInp = yDat[nn];
    switch (state) {
      case stateUnknown:                  // was below CF threshold in an indefinite state
        if(yInp > xP_fThreshCFA) {        // and goes above
          state = stateP;                 // initiate a possible trigger sequence
          xP_0  = xP_1 = xP_2 = nn;
          yMax = yInp;
          widthP = 1;                     // start checking width
        }                                 // if it stays below there is nothing to do
        break;
      case stateP:                        // was above threshold
        if(yInp >= xP_fThreshCFA) {       // and stays above
          if(yInp > yMax) {
            xP_1 = nn;                    // record maximum of first positive lobe
            yMax = yInp;
          }
          xP_2 = nn;
          widthP++;                       // incr positive width and stay in this state
        }
        else {                            // transition to negative
          if(widthP >=  xP_nMinWidthP &&  // positive lobe wide enough
             //widthP < 4*xP_nMinWidthP &&  // but not too wide
             xP_1 > xP_0 &&               // and has a maximum
             yMax > xP_minAmpl) {         // which is large enough
              state = stateN;             // initiate a negative lobe sequence
              xP_3  = xP_4 = xP_5 = nn;
              yMin  = yInp;
              widthN = 1;                // start counting width of negative lobe
          }
          else
            state = stateUnknown;         // go back to indefinite below threshold
        }
        break;
      case stateN:                        // below threshold in a valid-sequence state
        if(yInp < xP_fThreshCFA) {        // and stays below
          if(yInp < yMin) {
            xP_4 = nn;                    // record minimum
            yMin = yInp;
          }
          xP_5 = nn;
          widthN++;                       // incr negative width and stay in this state
          if(widthN > xP_nMinWidthN &&    // second positive lobe wide enough for a valid sequence
            yInp > yMin &&                // and signal is beyond minimum
            yMin < -xP_minAmpl) {         // and minimum large enough
              float cmp = abs(yMax/yMin);
              if(cmp < 0.2f || cmp > 2.f)
                state = stateUnknown;
              else
               return nn;                  // this is a good trigger
          }
          break;
        }
        else {                            // goes positive without having triggered
          state = stateP;                 // initiate a new possible trigger sequence
          xP_0 = xP_1 = xP_2 = nn;
          yMax = yInp;
          widthP = 1;                     // start checking width
          break;
        }
    }
  }
  return -1;
}

// trigger on a +++---++++ sequence
// with conditions on the width and amplitude of the lobes
int xP_Next2(float *yDat, int yLen)
{
  enum {
    stateUnknown,   // initial or negative before starting a new sequence
    stateP1,        // positive: xP_0(first positive chan),xP_1(max), xP_2(last positive)
    stateN,         // negative: xP_3(min), xP_4(last negative)
    stateP2         // positive: xP_5(max), xP_6(last)
  };

  int    state = stateUnknown;            // start in an indefinite state
  int    widthP1 = 0, widthN = 0, widthP2 = 0;
  float  yMax1, yMin, yMax2;

  for(int nn = 0; nn < yLen; nn++) {
    float yInp = yDat[nn];
    switch (state) {
case stateUnknown:                  // was below CF threshold in an indefinite state
  if(yInp > xP_fThreshCFA) {        // and goes above
    state = stateP1;                // initiate a possible trigger sequence
    xP_0  = xP_1 = xP_2 = nn;
    yMax1 = yMin = yInp;
    widthP1 = 1;                    // start checking width
  }                                 // if it stays below there is nothing to do
  break;
case stateP1:                       // was above threshold
  if(yInp >= xP_fThreshCFA) {       // and stays above
    if(yInp > yMax1) {
      xP_1 = nn;                    // record maximum of first positive lobe
      yMax1 = yInp;
    }
    xP_2 = nn;
    widthP1++;                      // incr positive width and stay in this state
  }
  else {                            // transition to negative
    if(widthP1 >= xP_nMinWidthP1 && // positive lobe wide enough
      xP_1 > xP_0) {              // and has a maximum
        state = stateN;             // initiate a negative lobe sequence
        xP_3  = xP_4 = nn;
        yMin    = yInp;
        widthN  = 1;                // start counting width of negative lobe
    }
    else
      state = stateUnknown;         // go back to indefinite below threshold
  }
  break;
case stateN:                        // below threshold in a valid-sequence state
  if(yInp < xP_fThreshCFA) {        // and stays below
    if(yInp < yMin) {
      xP_3 = nn;                    // record minimum
      yMin = yInp;
    }
    xP_4 = nn;
    widthN++;                       // incr positive width and stay in this state
  }
  else {                            // transition to positive
    if(widthN >= xP_nMinWidthN &&   // negative lobe wide enough
      yMin < -xP_minAmpl &&         // its amplitude large enough
      yMin < -1.1*yMax1 &&          // and minimum-to-maximum is acceptable
      yMin > -4.5*yMax1) {          // (exact value is -0.5*exp(1.5)) = -2.2408)
        state = stateP2;            // initiate the second positive lobe sequence
        xP_5  = xP_6 = nn;
        yMax2 = yInp;
        widthP2 = 1;                // start counting width of second positive lobe
    }
    else {
      state = stateP1;              // restart a new sequence
      xP_0  = xP_1 = xP_2 = nn;
      yMax1 = yMin =  yInp;
      widthP1 = 1;                  // start checking width
    }
  }
  break;
case stateP2:                       // above threshold in a valid-sequence state
  if(yInp > xP_fThreshCFA) {        // and is still above
    if(yInp > yMax2) { 
      xP_5  = nn;                   // record max of second positive lobe
      yMax2 = yInp;
    }
    xP_6 = nn;
    widthP2++;                      // incr positive width and stay in this state
    if(widthP2 > xP_nMinWidthP2 &&  // second positive lobe wide enough for a valid sequence
      yInp < yMax2) {              // and signal is beyond maximum
        return nn;                 // this is a good trigger
    }
  }
  else {                            // goes positive (with or without trigger)
    state = stateUnknown;           // ready  to start a possible new trigger sequence
  }
  break;
    }
  }
  return -1;
}

int FitPeaks(int verbose)
{
  if(specPeaks.size() < 1)
    return 0;

  // order peaks (needed to merge correctly close neighbours)
  sort( specPeaks.begin( ), specPeaks.end( ) );

  const float nwLe = 4.f; //  define left border
  const float nwOv = 2.f; //  check region overlap
  const float nwRi = 3.f; //  define right border

  Peaks.clear();

  // instead of specFWHMdef, we should use realistic width to define regions and overlaps

  int nmult = 0;
  int numpk = int(specPeaks.size());
  for(int nn = 0; nn < numpk; nn += 1 + nmult) {
    int chanA = int(specPeaks[nn]-nwLe*specFWHMdef);
    int chanB = int(specPeaks[nn]+nwRi*specFWHMdef);
    chanA = max(1,chanA);
    chanB = min(chanB, specLength-2);
    nmult = 0;
1366
    
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
    if(nn < numpk-2) {
      // check if the next peaks are in the same region
      for(size_t jj = nn+1; jj < specPeaks.size(); jj++) {
        if(specPeaks[jj]-nwOv*specFWHMdef >= chanB)
          break;
        nmult++;
        chanB = int(specPeaks[jj]+nwRi*specFWHMdef);
        chanB = min(chanB, specLength-2);
      }
    }

    int np = m_pCFit->CalcGaussianFit(specData, chanA, chanB, specPeaks);

    for(int jj = 0; jj < np; jj++) {
      Fitted res;
      res.area  = m_pCFit->Area(jj);
      res.ampli = m_pCFit->Amplitude(jj);
      res.posi  = m_pCFit->Position(jj);
1385
      if(MaxMode) res.posi = specPeaks[nn+jj];
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
      res.fw05  = m_pCFit->Fw05(jj);
      res.fw01  = m_pCFit->Fw01(jj);
      res.fwhm  = m_pCFit->Fwhm(jj);
      res.tailL = m_pCFit->W01L(jj);
      res.tailR = m_pCFit->W01R(jj);
      bool bad = (res.area < 10) || (res.fwhm >= 5*specFWHMdef) || (res.tailR > 5.f*res.tailL);
      if(verbose&1) {
        if(nn || jj) printf("#1                  ");
        if(jj == 0) printf(" %3d ", nn+jj);
        else        printf("  %3d", nn+jj);
        printf(" %10.1f %10.2f  %10.2f %8.3f %8.3f %8.3f %8.3f %8.3f", res.area, res.ampli, res.posi, res.fw05, res.fw01, res.fwhm, res.tailL, res.tailR);
        if(bad)
          printf("  ***");
        printf("\n");
      }
      if(!bad) {
        Peaks.push_back(res);
      }
    }
  }
  return Peaks.size();
}

// the energies should be already sorted in ascending order
// the peaks will be sorted in largest area order and the 
// first Energies.size() of them will be connected to all energies, checking
// how many other peaks match the specific gain
double ECalibration(int nspe, double& offset1, double& slope1, double& offset2, double& slope2, double& curv2, int verbose)
{
  vector <Fitted>::iterator Iter;

  if(Energies.size() == 1) {
    // select the peak with the largest area
    int pn_max = 0;
    for(size_t nn = 1; nn < Peaks.size(); nn++) {
      if(Peaks[nn].area > Peaks[pn_max].area) {
        pn_max = nn;
      }
    }
    offset1 = slope1 = 0;
    double slope  = Energies[0] / Peaks[pn_max].posi;
    Peaks[pn_max].good = true;
    Peaks[pn_max].eref = 0;
    if(verbose&2)
      printf("#2 %5d  Slope = %10.6f\n", nspe, slope);
    return slope;
  }

  if( Peaks.size() < 2 || Energies.size() < 2) {
    if(verbose&2)
      cout << "#   Number of peaks (" << Peaks.size() << ") or number of energies (" << Energies.size() << ")  too small" << endl;
    return 0;
  }

#if 0
  // all peaks used as pivot
  int npmax = Peaks.size();
  for(int np = 0; np < npmax; np++)
    Peaks[np].good = true;
#else
  // only the peak with largest area used as pivot
  sort( Peaks.begin( ), Peaks.end( ), largerAmplitude() );
  int npmax = min( min(Peaks.size(), size_t(4)), Energies.size() );  // limit the number of peaks to min(np,ne,4)
  for(int np = 0; np < npmax; np++)
    Peaks[np].good = true;
  for(size_t np = npmax; np < Peaks.size(); np++)
    Peaks[np].good = false;
#endif

  // (re)order the peaks 
  sort( Peaks.begin( ), Peaks.end( ), smallerPosi() );
  if(verbose&4) {
    printf("#  Sorted Peak Positions = (");
    for ( Iter = Peaks.begin( ) ; Iter != Peaks.end( ) ; Iter++ ) printf( " %d", int((*Iter).posi) );
    printf(" )\n");
  }

  // Connect every (large) peak with every energy and check how many other (peak,energy) pairs agree with this slope
  // The combination with the largest number of agreeing pairs provides the reference gain for the final average
  // Equal number of matches are ordered by chi2
  int    np_max = 0;      // number of matches
  int    np_ind = 0;      // reference peak
  int    np_ref = 0;      // reference energy
  double np_chi = 1.e40;  // to distinguish among equal matchers
  double dpos2max = specFWHMdef*specFWHMdef;
  for(size_t np = 0; np < Peaks.size(); np++) {
    if(!Peaks[np].good)
      continue;
    int    ec_max = 0;      // number of matches for peak np
    int    ec_ref = 0;      // reference energy
    double ec_chi = 1.e30;  // its chi2 
    for(size_t ne = 0; ne < Energies.size(); ne++) {            // connecting peak np with energy ne
      double lgain = (Peaks[np].posi)/Energies[ne];             // gives this gain
      int match = 0;
      double chi2 = 0;
      for(size_t nee = 0; nee < Energies.size(); nee++) {       // count the number of matches for this combination
        double epos = Energies[nee]*lgain;                      // expected position
        for(size_t ip = 0; ip < Peaks.size(); ip++) {
          double dpos  = Peaks[ip].posi-epos;
          double dpos2 = dpos*dpos;
          if(dpos2 < dpos2max) {
            match++;
            chi2 += dpos2;
            break;
          }
        }
      }
      if( (match > ec_max)  ||                        // more matches
          ((match == ec_max) && (chi2 < ec_chi)) ) {  // or better chi2
        ec_max = match;       // record the best combination so far
        ec_ref = ne;
        ec_chi = chi2;
      }
    }
    if( (ec_max > np_max) ||                           // more matches
        ((ec_max == np_max) && (ec_chi < np_chi)) ) {  // or better chi2
      np_max = ec_max;       // record the best combination so far
      np_ind = np;
      np_ref = ec_ref;
      np_chi = ec_chi;
    }
    //if(np_max == Energies.size())
    //  break;    // cannot do better than this ?
  }

  double bestSlope = Energies[np_ref]/(Peaks[np_ind].posi);
  if(verbose&4) {
    printf("#  Best-match slope %g [p=%d e=%d] with %d values\n", bestSlope, np_ind, np_ref, np_max);
  }

  // find the good peaks
  for(size_t np = 0; np < Peaks.size(); np++) {
    Peaks[np].eref = -1;
    Peaks[np].good = false;
  }
  int match = 0;
  for(size_t ne = 0; ne < Energies.size(); ne++) {
    double epos = Energies[ne]/bestSlope;
    for(size_t np = 0; np < Peaks.size(); np++) {
      if(abs(Peaks[np].posi-epos) < specFWHMdef && !Peaks[np].good) {
        match++;
        Peaks[np].eref = ne;
        Peaks[np].good = true;
        break;
      }
    }
  }

  // fit slope using the good peaks, starting without errors
  double val_xx = 0;
  double val_xy = 0;
  int used = 0;
  for(size_t np = 0; np < Peaks.size(); np++) {
    if(Peaks[np].good) {
      ++used;
      double x  = Peaks[np].posi;
      double y  = Energies[Peaks[np].eref];
      val_xx += x*x;
      val_xy += x*y; 
    }
  }
  double slope0 = val_xy / val_xx;
  double slope  = slope0;

  // if enabled, error**2 for chi1 is: errPos**2 + errEner**2
  // errP = slope * sigma/sqrt(Area)  Approx for a gaussian peak. Scaled to keV
  // errE taken from command line -errors errE (should be specific of each calibration line)

  // Not really worthwhile in actual practice.

  if(useErrors) {
    // repete, using errors
    double val_xx = 0;
    double val_xy = 0;
    int used = 0;
    for(size_t np = 0; np < Peaks.size(); np++) {
      if(Peaks[np].good) {
        ++used;
        double x  = Peaks[np].posi;
        double y  = Energies[Peaks[np].eref];
        double errP = slope0* pow(Peaks[np].fwhm/s2fwhm, 2.)/Peaks[np].area;
        double w2 = 1. / (errP*errP+errE*errE);
        val_xx += w2*x*x;
        val_xy += w2*x*y; 
      }
    }
    slope = val_xy / val_xx;
  }

  bool fit1Done = false;
  offset1 = slope1 = 0;
  if(match>=2 && doPoly1) {
    // fit a stright line through the good peaks
    double sx0 = 0., sx1 = 0., sx2 = 0., syx0 = 0., syx1 = 0.;
    double w2s = 0; // to record the average weight
    used = 0;
    double w2 = 1.;
    for(size_t np = 0; np < Peaks.size(); np++) {
      if(Peaks[np].good) {
        ++used;
        double x  = Peaks[np].posi;
        double y  = Energies[Peaks[np].eref];
        if(useErrors) {
          double errP = slope* pow(Peaks[np].fwhm/s2fwhm, 2.)/Peaks[np].area;
          w2 = 1. / (errP*errP+errE*errE);
        }
        sx0  += w2;
        sx1  += w2*x;
        sx2  += w2*x*x;
        syx0 += w2*y;
        syx1 += w2*y*x;
        w2s  += w2;
      }
    }
    if(numZero > 0 ) {
      // multiple artificial peaks at (0,0) to help system pass through origin
        //double x=0, y=0;      // --> only sx0 affected 
        double w2 = w2s/used;   // ??
        sx0  += w2*numZero;     // with multiplicity
    }
    double deter = sx0*sx2-sx1*sx1;
    if(deter > 0.) {
      offset1 = ( sx2*syx0 - sx1*syx1)/deter;
      slope1  = (-sx1*syx0 + sx0*syx1)/deter;
      double err_offset1 = sqrt(sx2/deter);
      double err_slope1  = sqrt(sx0/deter);
      fit1Done = true;
    }
  }

  bool fit2Done = false;
  offset2 = slope2 = curv2 = 0;
  if(match>=3 && doPoly2) {
    // fit a parabola line through the good peaks
    double sx0 = 0., sx1 = 0., sx2 = 0., sx3 = 0., sx4 = 0., syx0 = 0., syx1 = 0., syx2 = 0.;
    double w2s = 0; // to record the average weight
    used = 0;
    double w2 = 1.;
    for(size_t np = 0; np < Peaks.size(); np++) {
      if(Peaks[np].good) {
        ++used;
        double x  = Peaks[np].posi;
        double y  = Energies[Peaks[np].eref];
        if(useErrors) {
          double errP = slope* pow(Peaks[np].fwhm/s2fwhm, 2.)/Peaks[np].area;
          w2 = 1. / (errP*errP+errE*errE);
        }
        sx0  += w2;
        sx1  += w2*x;
        sx2  += w2*x*x;
        sx3  += w2*x*x*x;
        sx4  += w2*x*x*x*x;
        syx0 += w2*y;
        syx1 += w2*y*x;
        syx2 += w2*y*x*x;
        w2s  += w2;
      }
    }
    if(numZero > 0 ) {
      // multiple artificial peaks at (0,0) to help system pass through origin
        //double x=0, y=0;      // --> only sx0 affected 
        double w2 = w2s/used;   // ??
        sx0  += w2*numZero;     // with multiplicity
    }
    double dd[9]; memset(dd, 0, sizeof(dd));    // row-wise
    double xd[3]; memset(xd, 0, sizeof(xd));
    // [sx0]  [sx1]  [sx2]   [b0]    [ex0]
    // [sx1]  [sx2]  [sx3] * [b1] =  [ex1]
    // [sx2]  [sx3]  [sx4]   [b2]    [ex3]

    dd[0] = sx0; dd[1] = sx1; dd[2] = sx2; xd[0] = syx0;
    dd[3] = sx1; dd[4] = sx2; dd[5] = sx3; xd[1] = syx1;
    dd[6] = sx2; dd[7] = sx3; dd[8] = sx4; xd[2] = syx2;

    double DD[9];
    if(InvertMatrix3(dd, DD)) {
      offset2 = DD[0]*xd[0] + DD[1]*xd[1] + DD[2]*xd[2];
      slope2  = DD[3]*xd[0] + DD[4]*xd[1] + DD[5]*xd[2];
      curv2   = DD[6]*xd[0] + DD[7]*xd[1] + DD[8]*xd[2];
      fit2Done = true;
    }
  }

  if(verbose&2) {
    printf("#2 %5d  Slope = %1.6f", nspe, slope);
    if(fit1Done)
      printf("    Cal1=[ %7.4f  %1.6f ]", offset1, slope1);
    if(fit1Done && fit2Done)
      printf("    Cal2=[ %7.4f  %1.6f % .5e ]", offset2, slope2, curv2);
    printf("\n");
    size_t nn = 0;
    double chi2[5] = {0};
    int nused = 0;
    for(size_t np = 0; np < Peaks.size(); np++) {
      if(Peaks[np].good) {
        nused++;
        double lineEner = Energies[Peaks[np].eref];
        double seenPosi = Peaks[np].posi;
        double seenEner = seenPosi*slope;
        double diffEner = seenEner-lineEner;
        chi2[0] += diffEner*diffEner;
        printf("#2 %5d  %4d %4d %15.1f %10.2f %9.3f %9.3f   %11.3f %7.3f",
          nspe, int(nn++), int(np), Peaks[np].area, Peaks[np].posi, Peaks[np].fwhm, Peaks[np].fwhm*slope, lineEner, diffEner);
        if(fit1Done) {
          seenEner = offset1 + slope1*seenPosi;
          diffEner = seenEner-lineEner;
          printf(" %7.3f", diffEner);
          chi2[1] += diffEner*diffEner;
        }
        if(fit1Done && fit2Done) {
          seenEner = offset2 + slope2*seenPosi + curv2*seenPosi*seenPosi;
          diffEner = seenEner-lineEner;
          printf(" %7.3f", diffEner);
          chi2[2] += diffEner*diffEner;
        }
        printf("\n");
      }
    }
    chi2[0] = (nused-1) ? chi2[0]/(nused-1) : 0;
    printf("#2 %5d  Chi2 %73.3f", nspe, chi2[0]);
    if(fit1Done) {
      chi2[1] = (nused-2) ? chi2[1]/(nused-2) : 0;
      printf(" %7.3f", chi2[1]);
    }
    if(fit1Done && fit2Done) {
      chi2[2] = (nused-3) ? chi2[2]/(nused-3) : 0;
      printf(" %7.3f", chi2[2]);
    }
    printf("\n");
  }

  return slope;
}

double TCalibration(int verbose)
{
  return 0;
}

bool InvertMatrix3(const double m[9], double invOut[9])
{
  double d00 = m[0];
  double d01 = m[1];
  double d02 = m[2];
  double d10 = m[3];
  double d11 = m[4];
  double d12 = m[5];
  double d20 = m[6];
  double d21 = m[7];
  double d22 = m[8];

  double Det =  d00*(d11*d22 - d12*d21) + d01*(d12*d20 - d10*d22) + d02*(d10*d21 - d11*d20);
  if (Det == 0)
    return false;

  double D00 =  d11*d22 - d12*d21; double D01 =  d12*d20 - d10*d22; double D02 =  d10*d21 - d11*d20;
  double D10 =  d21*d02 - d22*d01; double D11 =  d22*d00 - d20*d02; double D12 =  d20*d01 - d21*d00;
  double D20 =  d01*d12 - d02*d11; double D21 =  d02*d10 - d00*d12; double D22 =  d00*d11 - d01*d10;

  Det = 1/Det;

  invOut[0] = D00 * Det;
  invOut[1] = D01 * Det;
  invOut[2] = D02 * Det;
  invOut[3] = D10 * Det;
  invOut[4] = D11 * Det;
  invOut[5] = D12 * Det;
  invOut[6] = D20 * Det;
  invOut[7] = D21 * Det;
  invOut[8] = D22 * Det;

#if 0
#define indx(n1, n2) (n1*3+n2)
  double unit[9]; memset(unit, 0, sizeof(unit));
  for(int i1 = 0; i1 < 3; i1++) {
    for(int i2 = 0; i2 < 3; i2++) {
      double accu = 0;
      for(int ii = 0; ii < 3; ii++) {
        accu += m[indx(i1,ii)]*invOut[indx(ii,i2)];
      } 
      unit[indx(i1,i2)] = accu;
    }
  } 
#undef indx
#endif

  return true;
}