Macros

Line Code
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 104 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 345 346 347 348 349 350 351 352 353 354 355 356 357 358 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 613 614 615 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 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 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 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129
#include <fstream>
#include <iostream>
#include <utility>

#include <TBranch.h>
#include <TCanvas.h>
#include <TF1.h>
#include <TProfile.h>
#include <TRandom.h>

#include <CLHEP/Vector/LorentzVector.h>

#include "CalibCalorimetry/CaloMiscalibTools/interface/CaloMiscalibMapEcal.h"
#include "CalibCalorimetry/CaloMiscalibTools/interface/MiscalibReaderFromXMLEcalBarrel.h"
#include "CalibCalorimetry/CaloMiscalibTools/interface/MiscalibReaderFromXMLEcalEndcap.h"
#include "Calibration/EcalCalibAlgos/interface/ZeeCalibration.h"
#include "Calibration/EcalCalibAlgos/interface/ZeeKinematicTools.h"
#include "Calibration/Tools/interface/CalibrationCluster.h"
#include "Calibration/Tools/interface/EcalIndexingTools.h"
#include "Calibration/Tools/interface/EcalRingCalibrationTools.h"
#include "Calibration/Tools/interface/HouseholderDecomposition.h"
#include "Calibration/Tools/interface/MinL3Algorithm.h"
#include "Calibration/Tools/interface/calibXMLwriter.h"
#include "CondFormats/DataRecord/interface/EcalIntercalibConstantsRcd.h"
#include "CondFormats/EcalObjects/interface/EcalIntercalibConstants.h"
#include "DataFormats/CaloRecHit/interface/CaloRecHit.h"
#include "DataFormats/Common/interface/Handle.h"
#include "DataFormats/EcalDetId/interface/EBDetId.h"
#include "DataFormats/EcalDetId/interface/EEDetId.h"
#include "DataFormats/EgammaReco/interface/BasicCluster.h"
#include "DataFormats/EgammaReco/interface/SuperCluster.h"
#include "FWCore/Framework/interface/TriggerNamesService.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "Geometry/CaloGeometry/interface/CaloSubdetectorGeometry.h"

#define MZ 91.1876

#define DEBUG 1

ZeeCalibration::ZeeCalibration(const edm::ParameterSet& iConfig)
    : hlTriggerResults_(iConfig.getParameter<edm::InputTag>("HLTriggerResults")),
      mcProducer_(iConfig.getUntrackedParameter<std::string>("mcProducer", "")),
      rechitProducer_(iConfig.getParameter<std::string>("rechitProducer")),
      rechitCollection_(iConfig.getParameter<std::string>("rechitCollection")),
      erechitProducer_(iConfig.getParameter<std::string>("erechitProducer")),
      erechitCollection_(iConfig.getParameter<std::string>("erechitCollection")),
      scProducer_(iConfig.getParameter<std::string>("scProducer")),
      scCollection_(iConfig.getParameter<std::string>("scCollection")),
      scIslandProducer_(iConfig.getParameter<std::string>("scIslandProducer")),
      scIslandCollection_(iConfig.getParameter<std::string>("scIslandCollection")),
      electronProducer_(iConfig.getParameter<std::string>("electronProducer")),
      electronCollection_(iConfig.getParameter<std::string>("electronCollection")),
      trigResultsToken_(consumes<edm::TriggerResults>(hlTriggerResults_)),
      hepMCToken_(consumes<edm::HepMCProduct>(edm::InputTag(mcProducer_))),
      ebRecHitToken_(consumes<EBRecHitCollection>(edm::InputTag(rechitProducer_, rechitCollection_))),
      eeRecHitToken_(consumes<EERecHitCollection>(edm::InputTag(erechitProducer_, erechitCollection_))),
      scToken_(consumes<reco::SuperClusterCollection>(edm::InputTag(scProducer_, scCollection_))),
      islandSCToken_(consumes<reco::SuperClusterCollection>(edm::InputTag(scIslandProducer_, scIslandCollection_))),
      gsfElectronToken_(consumes<reco::GsfElectronCollection>(edm::InputTag(electronProducer_, electronCollection_))),
      geometryToken_(esConsumes()) {
#ifdef DEBUG
  std::cout << "[ZeeCalibration] Starting the ctor" << std::endl;
#endif

  theMaxLoops = iConfig.getUntrackedParameter<unsigned int>("maxLoops", 0);

  wantEtaCorrection_ = iConfig.getUntrackedParameter<bool>("wantEtaCorrection", true);

  outputFileName_ = iConfig.getParameter<std::string>("outputFile");

  minInvMassCut_ = iConfig.getUntrackedParameter<double>("minInvMassCut", 70.);
  maxInvMassCut_ = iConfig.getUntrackedParameter<double>("maxInvMassCut", 110.);

  calibMode_ = iConfig.getUntrackedParameter<std::string>("ZCalib_CalibType");

  outputFile_ = TFile::Open(outputFileName_.c_str(), "RECREATE");  // open output file to store histograms

  myTree = new TTree("myTree", "myTree");
  //  myTree->Branch("zMass","zMass", &mass);
  myTree->Branch("zMass", &mass4tree, "mass/F");
  myTree->Branch("zMassDiff", &massDiff4tree, "massDiff/F");

  barrelfile_ = iConfig.getUntrackedParameter<std::string>("initialMiscalibrationBarrel", "");
  endcapfile_ = iConfig.getUntrackedParameter<std::string>("initialMiscalibrationEndcap", "");

  electronSelection_ =
      iConfig.getUntrackedParameter<unsigned int>("electronSelection", 0);  //option for electron selection

  etaBins_ = iConfig.getUntrackedParameter<unsigned int>("etaBins", 10);
  etBins_ = iConfig.getUntrackedParameter<unsigned int>("etBins", 10);

  etaMin_ = iConfig.getUntrackedParameter<double>("etaMin", 0.);
  etMin_ = iConfig.getUntrackedParameter<double>("etMin", 0.);
  etaMax_ = iConfig.getUntrackedParameter<double>("etaMax", 3.);
  etMax_ = iConfig.getUntrackedParameter<double>("etMax", 100.);

  //  new ZeePlots("zeePlots.root");
  //  ZeePlots->bookHistos();

  //ZeeCalibrationPLots("zeeCalibPlots");
  //ZeecaPlots->bookHistos(maxsIter);

  theParameterSet = iConfig;
  EcalIndexingTools* myIndexTool = nullptr;

  myIndexTool = EcalIndexingTools::getInstance();

  myIndexTool->setBinRange(etaBins_, etaMin_, etaMax_, etBins_, etMin_, etMax_);

  //creating the algorithm
  theAlgorithm_ = new ZIterativeAlgorithmWithFit(iConfig);

  // Tell the framework what data is being produced
  //setWhatProduced(this);
  setWhatProduced(this, &ZeeCalibration::produceEcalIntercalibConstants);
  findingRecord<EcalIntercalibConstantsRcd>();

  for (int i = 0; i < 50; i++) {
    coefficientDistanceAtIteration[i] = -1.;
    loopArray[i] = -1.;
    sigmaArray[i] = -1.;
    sigmaErrorArray[i] = -1.;
  }

#ifdef DEBUG
  std::cout << "[ZeeCalibration] Done with the ctor" << std::endl;
#endif
}

ZeeCalibration::~ZeeCalibration() {
  //   if (theAlgorithm_)
  //     delete theAlgorithm_;
}

//_____________________________________________________________________________
// Produce EcalIntercalibConstants
std::shared_ptr<EcalIntercalibConstants> ZeeCalibration::produceEcalIntercalibConstants(
    const EcalIntercalibConstantsRcd& iRecord) {
  std::cout << "@SUB=ZeeCalibration::produceEcalIntercalibConstants" << std::endl;
  return ical;
}

void ZeeCalibration::beginOfJob() { isfirstcall_ = true; }

//========================================================================
void ZeeCalibration::endOfJob() {
  printStatistics();

  if (calibMode_ != "ETA_ET_MODE") {
    ///if not ETA_ET MODE - begin

    //Writing out calibration coefficients
    calibXMLwriter* barrelWriter = new calibXMLwriter(EcalBarrel);
    for (int ieta = -EBDetId::MAX_IETA; ieta <= EBDetId::MAX_IETA; ++ieta) {
      if (ieta == 0)
        continue;
      for (int iphi = EBDetId::MIN_IPHI; iphi <= EBDetId::MAX_IPHI; ++iphi) {
        // make an EBDetId since we need EBDetId::rawId() to be used as the key for the pedestals
        if (EBDetId::validDetId(ieta, iphi)) {
          EBDetId ebid(ieta, iphi);
          barrelWriter->writeLine(ebid, *(ical->getMap().find(ebid.rawId())));
        }
      }
    }

    calibXMLwriter* endcapWriter = new calibXMLwriter(EcalEndcap);
    for (int iX = EEDetId::IX_MIN; iX <= EEDetId::IX_MAX; ++iX) {
      for (int iY = EEDetId::IY_MIN; iY <= EEDetId::IY_MAX; ++iY) {
        // make an EEDetId since we need EEDetId::rawId() to be used as the key for the pedestals
        if (EEDetId::validDetId(iX, iY, 1)) {
          EEDetId eeid(iX, iY, 1);
          endcapWriter->writeLine(eeid, *(ical->getMap().find(eeid.rawId())));
        }
        if (EEDetId::validDetId(iX, iY, -1)) {
          EEDetId eeid(iX, iY, -1);
          endcapWriter->writeLine(eeid, *(ical->getMap().find(eeid.rawId())));
        }
      }
    }

  }  ///if not ETA_ET MODE - end

  std::cout << "Writing  histos..." << std::endl;
  outputFile_->cd();

  //  zeeplts->Write();

  h1_eventsBeforeEWKSelection_->Write();
  h1_eventsAfterEWKSelection_->Write();

  h1_eventsBeforeBorderSelection_->Write();
  h1_eventsAfterBorderSelection_->Write();

  h1_borderElectronClassification_->Write();

  h2_xtalMiscalibCoeffBarrel_->Write();
  h2_xtalMiscalibCoeffEndcapMinus_->Write();
  h2_xtalMiscalibCoeffEndcapPlus_->Write();

  h1_electronCosTheta_SC_->Write();
  h1_electronCosTheta_TK_->Write();
  h1_electronCosTheta_SC_TK_->Write();

  h1_zMassResol_->Write();
  h1_zEtaResol_->Write();
  h1_zPhiResol_->Write();
  h1_eleEtaResol_->Write();
  h1_elePhiResol_->Write();
  h1_seedOverSC_->Write();
  h1_preshowerOverSC_->Write();

  for (unsigned int i = 0; i < 25; i++) {
    if (i < theMaxLoops) {
      h_ESCEtrueVsEta_[i]->Write();
      h_ESCEtrue_[i]->Write();

      h_ESCcorrEtrueVsEta_[i]->Write();
      h_ESCcorrEtrue_[i]->Write();

      h2_chi2_[i]->Write();
      h2_iterations_[i]->Write();

      //      h_DiffZMassDistr_[i]->Write();

      //h_ZMassDistr_[i]->Write();
    }
  }

  h2_fEtaBarrelGood_->Write();
  h2_fEtaBarrelBad_->Write();
  h2_fEtaEndcapGood_->Write();
  h2_fEtaEndcapBad_->Write();
  h1_eleClasses_->Write();

  h_eleEffEta_[0]->Write();
  h_eleEffPhi_[0]->Write();
  h_eleEffPt_[0]->Write();

  h_eleEffEta_[1]->Write();
  h_eleEffPhi_[1]->Write();
  h_eleEffPt_[1]->Write();

  int j = 0;

  int flag = 0;

  Double_t mean[25] = {0.};
  Double_t num[25] = {0.};
  Double_t meanErr[25] = {0.};
  Float_t rms[25] = {0.};
  Float_t tempRms[10][25];

  for (int ia = 0; ia < 10; ia++) {
    for (int ib = 0; ib < 25; ib++) {
      tempRms[ia][ib] = 0.;
    }
  }

  int aa = 0;

  for (int k = 0; k < theAlgorithm_->getNumberOfChannels(); k++) {
    //////grouped
    bool isNearCrack = false;

    if (calibMode_ == "RING") {
      isNearCrack = (abs(ringNumberCorrector(k)) == 1 || abs(ringNumberCorrector(k)) == 25 ||
                     abs(ringNumberCorrector(k)) == 26 || abs(ringNumberCorrector(k)) == 45 ||
                     abs(ringNumberCorrector(k)) == 46 || abs(ringNumberCorrector(k)) == 65 ||
                     abs(ringNumberCorrector(k)) == 66 || abs(ringNumberCorrector(k)) == 85 ||
                     abs(ringNumberCorrector(k)) == 86 || abs(ringNumberCorrector(k)) == 124);
    }

    if (k < 85) {
      if ((k + 1) % 5 != 0) {
        if (!isNearCrack) {
          mean[j] += calibCoeff[k];
          mean[j] += calibCoeff[169 - k];

          num[j] += 2.;

          //meanErr[j]+= calibCoeffError[k];
          //meanErr[j]+= calibCoeffError[169 - k];

          meanErr[j] += 1. / pow(calibCoeffError[k], 2);
          meanErr[j] += 1. / pow(calibCoeffError[169 - k], 2);

          tempRms[aa][j] += calibCoeff[k];
          aa++;
          tempRms[aa][j] += calibCoeff[169 - k];
          aa++;
        }
      }

      else {
        if (!isNearCrack) {
          mean[j] += calibCoeff[k];
          mean[j] += calibCoeff[169 - k];

          num[j] += 2.;

          //meanErr[j]+= calibCoeffError[k];
          //meanErr[j]+= calibCoeffError[169 - k];

          meanErr[j] += 1. / pow(calibCoeffError[k], 2);
          meanErr[j] += 1. / pow(calibCoeffError[169 - k], 2);

          tempRms[aa][j] += calibCoeff[k];
          aa++;
          tempRms[aa][j] += calibCoeff[169 - k];
          aa++;
        }
        j++;
        aa = 0;
      }
    }
    //EE begin

    if (k >= 170 && k <= 204) {
      if (flag < 4) {
        //make groups of 5 Xtals in #eta
        mean[j] += calibCoeff[k] / 10.;
        mean[j] += calibCoeff[k + 39] / 10.;

        meanErr[j] += calibCoeffError[k] / 30.;
        meanErr[j] += calibCoeffError[k + 39] / 30.;

        tempRms[aa][j] += calibCoeff[k];
        aa++;
        tempRms[aa][j] += calibCoeff[k + 39];
        aa++;

        flag++;
      }

      else if (flag == 4) {
        //make groups of 5 Xtals in #eta
        mean[j] += calibCoeff[k] / 10.;
        mean[j] += calibCoeff[k + 39] / 10.;

        meanErr[j] += calibCoeffError[k] / 30.;
        meanErr[j] += calibCoeffError[k + 39] / 30.;

        tempRms[aa][j] += calibCoeff[k];
        aa++;
        tempRms[aa][j] += calibCoeff[k + 39];
        aa++;

        flag = 0;
        //	  std::cout<<" index(>85) "<<k<<" j is "<<j<<" mean[j] is "<<mean[j]<<std::endl;
        j++;
        aa = 0;
      }
    }
    if (k >= 205 && k <= 208) {
      mean[j] += calibCoeff[k] / 8.;
      mean[j] += calibCoeff[k + 39] / 8.;

      meanErr[j] += calibCoeffError[k] / 30.;
      meanErr[j] += calibCoeffError[k + 39] / 30.;

      tempRms[aa][j] += calibCoeff[k];
      aa++;
      tempRms[aa][j] += calibCoeff[k + 39];
      aa++;
    }
    //EE end

    /*
      for(int jj =0; jj< 25; jj++){ 
      if(meanErr[jj] > 0.)
	std::cout<<" meanErr[jj] before sqrt: "<<meanErr[jj]<<std::endl;

	meanErr[jj] = 1./sqrt( meanErr[jj] );

	std::cout<<" meanErr[jj] after sqrt: "<<meanErr[jj]<<std::endl;
      }
      */

    if (!isNearCrack) {
      h2_coeffVsEta_->Fill(ringNumberCorrector(k), calibCoeff[k]);
      h2_miscalRecal_->Fill(initCalibCoeff[k], 1. / calibCoeff[k]);
      h1_mc_->Fill(initCalibCoeff[k] * calibCoeff[k] - 1.);

      if (k < 170) {
        h2_miscalRecalEB_->Fill(initCalibCoeff[k], 1. / calibCoeff[k]);
        h1_mcEB_->Fill(initCalibCoeff[k] * calibCoeff[k] - 1.);
      }

      if (k >= 170) {
        h2_miscalRecalEE_->Fill(initCalibCoeff[k], 1. / calibCoeff[k]);
        h1_mcEE_->Fill(initCalibCoeff[k] * calibCoeff[k] - 1.);
      }
    }
  }

  for (int ic = 0; ic < 17; ic++) {
    mean[ic] = mean[ic] / num[ic];  //find mean of recalib coeff on group of rings
    //meanErr[ic] = meanErr[ic] / ( sqrt( num[ic] ) * num[ic] ); //find mean of recalib coeff on group of rings
    meanErr[ic] = 1. / sqrt(meanErr[ic]);  //find mean of recalib coeff on group of rings
  }

  //build array of RMS
  for (int ic = 0; ic < 25; ic++) {
    for (int id = 0; id < 10; id++) {
      if (tempRms[id][ic] > 0.) {
        rms[ic] += (tempRms[id][ic] - mean[j]) * (tempRms[id][ic] - mean[j]);
      }
    }
    rms[ic] /= 10.;  //this is approximate
    rms[ic] = sqrt(rms[ic]);
  }

  //build array of RMS

  Double_t xtalEta[25] = {1.4425, 1.3567, 1.2711, 1.1855, 1.10,   1.01,   0.92,   0.83,   0.7468,
                          0.6612, 0.5756, 0.4897, 0.3985, 0.3117, 0.2250, 0.1384, 0.0487, 1.546,
                          1.651,  1.771,  1.908,  2.071,  2.267,  2.516,  2.8};

  Double_t zero[25] = {0.026};  //interval/sqrt(12)

  for (int j = 0; j < 25; j++)
    h2_coeffVsEtaGrouped_->Fill(xtalEta[j], mean[j]);

  //  for(int sho = 0; sho <25; sho++)
  //cout<<"xtalEta[j] "<< xtalEta[sho]<<" mean[j]  "<<mean[sho]<<"  err[j] "<<meanErr[sho]<<std::endl;

  TProfile* px = h2_coeffVsEta_->ProfileX("coeffVsEtaProfile");
  px->SetXTitle("Eta channel");
  px->SetYTitle("recalibCoeff");
  px->Write();

  h2_coeffVsEta_->Write();
  h2_coeffVsEtaGrouped_->Write();
  h2_zMassVsLoop_->Write();
  h2_zMassDiffVsLoop_->Write();
  h2_zWidthVsLoop_->Write();
  h2_coeffVsLoop_->Write();
  h2_miscalRecal_->Write();
  h1_mc_->Write();
  h2_miscalRecalEB_->Write();
  h1_mcEB_->Write();
  h2_miscalRecalEE_->Write();
  h1_mcEE_->Write();

  h2_residualSigma_->Write();

  const ZIterativeAlgorithmWithFit::ZIterativeAlgorithmWithFitPlots* algoHistos = theAlgorithm_->getHistos();

  double weightSumMeanBarrel = 0.;
  double weightSumMeanEndcap = 0.;

  for (int iIteration = 0; iIteration < theAlgorithm_->getNumberOfIterations(); iIteration++)
    for (int iChannel = 0; iChannel < theAlgorithm_->getNumberOfChannels(); iChannel++) {
      if (iIteration == (theAlgorithm_->getNumberOfIterations() - 1)) {
        if (iChannel < 170)
          weightSumMeanBarrel += algoHistos->weightedRescaleFactor[iIteration][iChannel]->Integral() / 170.;

        if (iChannel >= 170)
          weightSumMeanEndcap += algoHistos->weightedRescaleFactor[iIteration][iChannel]->Integral() / 78.;

        h1_occupancyVsEta_->Fill((Double_t)ringNumberCorrector(iChannel),
                                 algoHistos->weightedRescaleFactor[iIteration][iChannel]->Integral());

        h1_occupancy_->Fill(algoHistos->weightedRescaleFactor[iIteration][iChannel]->Integral());

        if (iChannel < 170)
          h1_occupancyBarrel_->Fill(algoHistos->weightedRescaleFactor[iIteration][iChannel]->Integral());

        if (iChannel >= 170)
          h1_occupancyEndcap_->Fill(algoHistos->weightedRescaleFactor[iIteration][iChannel]->Integral());

#ifdef DEBUG
        std::cout << "Writing weighted integral for channel " << ringNumberCorrector(iChannel) << " ,value "
                  << algoHistos->weightedRescaleFactor[iIteration][iChannel]->Integral() << std::endl;
#endif
      }
    }

  //  std::cout<<"Done! Closing output file... "<<std::endl;

  h1_weightSumMeanBarrel_->Fill(weightSumMeanBarrel);
  h1_weightSumMeanEndcap_->Fill(weightSumMeanEndcap);

  std::cout << "Weight sum mean on channels in Barrel is :" << weightSumMeanBarrel << std::endl;
  std::cout << "Weight sum mean on channels in Endcap is :" << weightSumMeanEndcap << std::endl;

  h1_weightSumMeanBarrel_->Write();
  h1_weightSumMeanEndcap_->Write();

  h1_occupancyVsEta_->Write();
  h1_occupancy_->Write();
  h1_occupancyBarrel_->Write();
  h1_occupancyEndcap_->Write();

  myTree->Write();

  TGraphErrors* graph = new TGraphErrors(25, xtalEta, mean, zero, meanErr);
  graph->Draw("APL");
  graph->Write();

  double zero50[50] = {0.};

  TGraphErrors* residualSigmaGraph = new TGraphErrors(50, loopArray, sigmaArray, zero50, sigmaErrorArray);
  residualSigmaGraph->SetName("residualSigmaGraph");
  residualSigmaGraph->Draw("APL");
  residualSigmaGraph->Write();

  TGraphErrors* coefficientDistanceAtIterationGraph =
      new TGraphErrors(50, loopArray, coefficientDistanceAtIteration, zero50, zero50);
  coefficientDistanceAtIterationGraph->SetName("coefficientDistanceAtIterationGraph");
  coefficientDistanceAtIterationGraph->Draw("APL");
  coefficientDistanceAtIterationGraph->Write();

  Float_t noError[250] = {0.};

  Float_t ringInd[250];
  for (int i = 0; i < 250; i++)
    ringInd[i] = ringNumberCorrector(i);

  TGraphErrors* graphCoeff =
      new TGraphErrors(theAlgorithm_->getNumberOfChannels(), ringInd, calibCoeff, noError, calibCoeffError);
  graphCoeff->SetName("graphCoeff");
  graphCoeff->Draw("APL");
  graphCoeff->Write();

  //   outputFile_->Write();//this automatically writes all histos on file

  h1_ZCandMult_->Write();
  h1_reco_ZMass_->Write();

  h1_reco_ZMassCorr_->Write();
  h1_reco_ZMassCorrBB_->Write();
  h1_reco_ZMassCorrEE_->Write();

  outputFile_->Close();

  myZeePlots_->writeEleHistograms();
  myZeePlots_->writeMCEleHistograms();
  myZeePlots_->writeZHistograms();
  myZeePlots_->writeMCZHistograms();

  // myZeeRescaleFactorPlots_ = new ZeeRescaleFactorPlots("zeeRescaleFactorPlots.root");
  //myZeeRescaleFactorPlots_->writeHistograms( theAlgorithm_ );

  //  delete myZeeRescaleFactorPlots_;
}

//_____________________________________________________________________________
// Called at each event
//________________________________________

edm::EDLooper::Status ZeeCalibration::duringLoop(const edm::Event& iEvent, const edm::EventSetup& iSetup) {
  using namespace edm;

#ifdef DEBUG
  std::cout << "[ZeeCalibration] Entering duringLoop" << std::endl;
#endif

  // code that used to be in beginJob
  if (isfirstcall_) {
    //inizializzare la geometria di ecal
    const auto& geometry = iSetup.getData(geometryToken_);
    EcalRingCalibrationTools::setCaloGeometry(&geometry);

    myZeePlots_ = new ZeePlots("zeePlots.root");
    //  myZeeRescaleFactorPlots_ = new ZeeRescaleFactorPlots("zeeRescaleFactorPlots.root");

    // go to *OUR* rootfile and book histograms
    outputFile_->cd();
    bookHistograms();

    std::cout << "[ZeeCalibration::beginOfJob] Histograms booked " << std::endl;

    loopFlag_ = 0;

    //Read miscalibration map if requested
    CaloMiscalibMapEcal* miscalibMap = nullptr;
    if (!barrelfile_.empty() || !barrelfile_.empty()) {
      miscalibMap = new CaloMiscalibMapEcal();
      miscalibMap->prefillMap();
    }

    if (!barrelfile_.empty()) {
      MiscalibReaderFromXMLEcalBarrel barrelreader_(*miscalibMap);
      barrelreader_.parseXMLMiscalibFile(barrelfile_);
#ifdef DEBUG
      std::cout << "[ZeeCalibration::beginOfJob] Parsed EB miscal file" << std::endl;
#endif
    }

    if (!endcapfile_.empty()) {
      MiscalibReaderFromXMLEcalEndcap endcapreader_(*miscalibMap);
      endcapreader_.parseXMLMiscalibFile(endcapfile_);
#ifdef DEBUG
      std::cout << "[ZeeCalibration::beginOfJob] Parsed EE miscal file" << std::endl;
#endif
    }

    std::cout << "  theAlgorithm_->getNumberOfChannels() " << theAlgorithm_->getNumberOfChannels() << std::endl;

    ////////////////////set miscalibration
    for (int k = 0; k < theAlgorithm_->getNumberOfChannels(); k++) {
      calibCoeff[k] = 1.;
      calibCoeffError[k] = 0.;

      std::vector<DetId> ringIds;

      if (calibMode_ == "RING")
        ringIds = EcalRingCalibrationTools::getDetIdsInRing(k);

      if (calibMode_ == "MODULE")
        ringIds = EcalRingCalibrationTools::getDetIdsInModule(k);

      if (calibMode_ == "ABS_SCALE" || calibMode_ == "ETA_ET_MODE")
        ringIds = EcalRingCalibrationTools::getDetIdsInECAL();

      if (miscalibMap) {
        initCalibCoeff[k] = 0.;
        for (unsigned int iid = 0; iid < ringIds.size(); ++iid) {
          float miscalib = *(miscalibMap->get().getMap().find(ringIds[iid]));
          //	      float miscalib=miscalibMap->get().getMap().find(ringIds[iid])->second; ////////AP
          initCalibCoeff[k] += miscalib;
        }
        initCalibCoeff[k] /= (float)ringIds.size();
        std::cout << k << " " << initCalibCoeff[k] << " " << ringIds.size() << std::endl;
      } else {
        initCalibCoeff[k] = 1.;
      }
    }

    ical = std::make_shared<EcalIntercalibConstants>();

    for (int k = 0; k < theAlgorithm_->getNumberOfChannels(); k++) {
      //      std::vector<DetId> ringIds = EcalRingCalibrationTools::getDetIdsInRing(k);

      std::vector<DetId> ringIds;

      if (calibMode_ == "RING")
        ringIds = EcalRingCalibrationTools::getDetIdsInRing(k);

      if (calibMode_ == "MODULE")
        ringIds = EcalRingCalibrationTools::getDetIdsInModule(k);

      if (calibMode_ == "ABS_SCALE" || calibMode_ == "ETA_ET_MODE")
        ringIds = EcalRingCalibrationTools::getDetIdsInECAL();

      for (unsigned int iid = 0; iid < ringIds.size(); ++iid) {
        //	ical->setValue( ringIds[iid], 1. * initCalibCoeff[k] );

        if (ringIds[iid].subdetId() == EcalBarrel) {
          EBDetId myEBDetId(ringIds[iid]);
          h2_xtalMiscalibCoeffBarrel_->SetBinContent(
              myEBDetId.ieta() + 86,
              myEBDetId.iphi(),
              *(miscalibMap->get().getMap().find(ringIds[iid])));  //fill TH2 with miscalibCoeff
        }

        if (ringIds[iid].subdetId() == EcalEndcap) {
          EEDetId myEEDetId(ringIds[iid]);
          if (myEEDetId.zside() < 0)
            h2_xtalMiscalibCoeffEndcapMinus_->SetBinContent(
                myEEDetId.ix(),
                myEEDetId.iy(),
                *(miscalibMap->get().getMap().find(ringIds[iid])));  //fill TH2 with miscalibCoeff

          if (myEEDetId.zside() > 0)
            h2_xtalMiscalibCoeffEndcapPlus_->SetBinContent(
                myEEDetId.ix(),
                myEEDetId.iy(),
                *(miscalibMap->get().getMap().find(ringIds[iid])));  //fill TH2 with miscalibCoeff
        }

        ical->setValue(ringIds[iid], *(miscalibMap->get().getMap().find(ringIds[iid])));
      }

      read_events = 0;
      init_ = false;
    }
    isfirstcall_ = false;
  }  // if isfirstcall

  ////////////////////////////////////////////////////////////////////////////HLT begin

  for (unsigned int iHLT = 0; iHLT < 200; ++iHLT) {
    aHLTResults[iHLT] = false;
  }

#ifdef DEBUG
  std::cout << "[ZeeCalibration::duringLoop] Done with initializing aHLTresults[] " << std::endl;
#endif

  edm::Handle<edm::TriggerResults> hltTriggerResultHandle;
  iEvent.getByToken(trigResultsToken_, hltTriggerResultHandle);

  if (!hltTriggerResultHandle.isValid()) {
    //std::cout << "invalid handle for HLT TriggerResults" << std::endl;
  } else {
    hltCount = hltTriggerResultHandle->size();

    if (loopFlag_ == 0)
      myZeePlots_->fillHLTInfo(hltTriggerResultHandle);

#ifdef DEBUG
    std::cout << "[ZeeCalibration::duringLoop] Done with myZeePlots_->fillHLTInfo(hltTriggerResultHandle); "
              << std::endl;
#endif

    for (int i = 0; i < hltCount; i++) {
      aHLTResults[i] = hltTriggerResultHandle->accept(i);

      //HLT bit 32 = HLT1Electron
      //HLT bit 34 = HLT2Electron
      //HLT bit 35 = HLT2ElectronRelaxed
    }

    if (!aHLTResults[32] && !aHLTResults[34] && !aHLTResults[35])
      return kContinue;
  }

#ifdef DEBUG
  std::cout << "[ZeeCalibration::duringLoop] End HLT section" << std::endl;
#endif

  //////////////////////////////////////////////////////////////////////HLT end

  std::vector<HepMC::GenParticle*> mcEle;

  float myGenZMass(-1);

  if (!mcProducer_.empty()) {
    //DUMP GENERATED Z MASS - BEGIN
    Handle<HepMCProduct> hepProd;
    iEvent.getByToken(hepMCToken_, hepProd);

    const HepMC::GenEvent* myGenEvent = hepProd->GetEvent();

    if (loopFlag_ == 0)
      myZeePlots_->fillZMCInfo(&(*myGenEvent));

#ifdef DEBUG
    std::cout << "[ZeeCalibration::duringLoop] Done with myZeePlots_->fillZMCInfo( & (*myGenEvent) ); " << std::endl;
#endif

    for (HepMC::GenEvent::particle_const_iterator p = myGenEvent->particles_begin(); p != myGenEvent->particles_end();
         ++p) {
      //return a pointer to MC Z in the event
      if ((*p)->pdg_id() == 23 && (*p)->status() == 2) {
        myGenZMass = (*p)->momentum().m();
      }
    }
    //DUMP GENERATED Z MASS - END

    if (loopFlag_ == 0)
      myZeePlots_->fillEleMCInfo(&(*myGenEvent));

    //loop over MC positrons and find the closest MC positron in (eta,phi) phace space - begin
    HepMC::GenParticle MCele;

    for (HepMC::GenEvent::particle_const_iterator p = myGenEvent->particles_begin(); p != myGenEvent->particles_end();
         ++p) {
      if (abs((*p)->pdg_id()) == 11) {
        mcEle.push_back((*p));
        MCele = *(*p);
      }
    }

    if (mcEle.size() == 2 && fabs(mcEle[0]->momentum().eta()) < 2.4 && fabs(mcEle[1]->momentum().eta()) < 2.4) {
      NEVT++;

      if (fabs(mcEle[0]->momentum().eta()) < 1.479 && fabs(mcEle[1]->momentum().eta()) < 1.479)
        MCZBB++;

      if ((fabs(mcEle[0]->momentum().eta()) > 1.479 && fabs(mcEle[1]->momentum().eta()) < 1.479) ||
          (fabs(mcEle[0]->momentum().eta()) < 1.479 && fabs(mcEle[1]->momentum().eta()) > 1.479))
        MCZEB++;

      if (fabs(mcEle[0]->momentum().eta()) > 1.479 && fabs(mcEle[1]->momentum().eta()) > 1.479)
        MCZEE++;
    }
  }

  // Get EBRecHits
  Handle<EBRecHitCollection> phits;
  iEvent.getByToken(ebRecHitToken_, phits);
  if (!phits.isValid()) {
    std::cerr << "Error! can't get the product EBRecHitCollection " << std::endl;
  }
  const EBRecHitCollection* hits = phits.product();  // get a ptr to the product

  // Get EERecHits
  Handle<EERecHitCollection> ephits;
  iEvent.getByToken(eeRecHitToken_, ephits);
  if (!ephits.isValid()) {
    std::cerr << "Error! can't get the product EERecHitCollection " << std::endl;
  }
  const EERecHitCollection* ehits = ephits.product();  // get a ptr to the product

  //Get Hybrid SuperClusters
  Handle<reco::SuperClusterCollection> pSuperClusters;
  iEvent.getByToken(scToken_, pSuperClusters);
  if (!pSuperClusters.isValid()) {
    std::cerr << "Error! can't get the product SuperClusterCollection " << std::endl;
  }
  const reco::SuperClusterCollection* scCollection = pSuperClusters.product();

#ifdef DEBUG
  std::cout << "scCollection->size()" << scCollection->size() << std::endl;
  for (reco::SuperClusterCollection::const_iterator scIt = scCollection->begin(); scIt != scCollection->end(); scIt++) {
    std::cout << scIt->energy() << std::endl;
  }
#endif

  //Get Island SuperClusters
  Handle<reco::SuperClusterCollection> pIslandSuperClusters;
  iEvent.getByToken(islandSCToken_, pIslandSuperClusters);
  if (!pIslandSuperClusters.isValid()) {
    std::cerr << "Error! can't get the product IslandSuperClusterCollection " << std::endl;
  }
  const reco::SuperClusterCollection* scIslandCollection = pIslandSuperClusters.product();

#ifdef DEBUG
  std::cout << "scCollection->size()" << scIslandCollection->size() << std::endl;
#endif

  if ((scCollection->size() + scIslandCollection->size()) < 2)
    return kContinue;

  // Get Electrons
  Handle<reco::GsfElectronCollection> pElectrons;
  iEvent.getByToken(gsfElectronToken_, pElectrons);
  if (!pElectrons.isValid()) {
    std::cerr << "Error! can't get the product ElectronCollection " << std::endl;
  }
  const reco::GsfElectronCollection* electronCollection = pElectrons.product();

  /*
  //reco-mc association map
  std::map<HepMC::GenParticle*,const reco::PixelMatchGsfElectron*> myMCmap;
  
    fillMCmap(&(*electronCollection),mcEle,myMCmap);
    
    fillEleInfo(mcEle,myMCmap);
  */

  if (electronCollection->size() < 2)
    return kContinue;

  if (!hits && !ehits) {
    std::cout << "!hits" << std::endl;
    return kContinue;
  }

  if (hits->empty() && ehits->empty()) {
    std::cout << "hits->size() == 0" << std::endl;
    return kContinue;
  }

  if (!electronCollection) {
    std::cout << "!electronCollection" << std::endl;
    return kContinue;
  }

  if (electronCollection->empty()) {
    std::cout << "electronCollection->size() == 0" << std::endl;
    return kContinue;
  }

  ///////////////////////////////////////////////////////////////////////////////////////
  ///                          START HERE....
  ///////////////////////////////////////////////////////////////////////////////////////

  read_events++;

  //  std::cout << "read_events = " << read_events << std::endl;

  ////////////////////////CHOOSE EVENTS WITH 2 OR MORE ELECTRONS ////////////////////

#ifdef DEBUG
  std::cout << " Starting with myZeePlots_->fillEleInfo(electronCollection); " << std::endl;
#endif

  if (loopFlag_ == 0)
    myZeePlots_->fillEleInfo(electronCollection);

#ifdef DEBUG
  std::cout << " Done with myZeePlots_->fillEleInfo(electronCollection); " << std::endl;
#endif

  //FILL an electron vector - end
  //###################################Electron-SC association: begin#####################################################
  //Filling new ElectronCollection with new SC ref and calibElectron container
  std::vector<calib::CalibElectron> calibElectrons;
  //std::map< const calib::CalibElectron* , const reco::SuperCluster* > eleScMap;

  //#####################################Electron-SC association map: end#####################################################
  for (unsigned int e_it = 0; e_it != electronCollection->size(); e_it++) {
    calibElectrons.push_back(calib::CalibElectron(&((*electronCollection)[e_it]), hits, ehits));
#ifdef DEBUG
    std::cout << calibElectrons.back().getRecoElectron()->superCluster()->energy() << " "
              << calibElectrons.back().getRecoElectron()->energy() << std::endl;
#endif
    //      h1_recoEleEnergy_->Fill(calibElectrons.back().getRecoElectron()->superCluster()->energy());
  }
  //  if (iLoop == 0)
  //fillCalibElectrons(calibElectrons);

#ifdef DEBUG
  std::cout << "Filled histos" << std::endl;
#endif

  //COMBINATORY FOR Z MASS - begin
  std::vector<std::pair<calib::CalibElectron*, calib::CalibElectron*> > zeeCandidates;
  int myBestZ = -1;

  mass = -1.;
  double DeltaMinvMin(5000.);

  if (calibElectrons.size() < 2)
    return kContinue;

  for (unsigned int e_it = 0; e_it != calibElectrons.size() - 1; e_it++) {
    for (unsigned int p_it = e_it + 1; p_it != calibElectrons.size(); p_it++) {
#ifdef DEBUG
      std::cout << e_it << " " << calibElectrons[e_it].getRecoElectron()->charge() << " " << p_it << " "
                << calibElectrons[p_it].getRecoElectron()->charge() << std::endl;
#endif
      if (calibElectrons[e_it].getRecoElectron()->charge() * calibElectrons[p_it].getRecoElectron()->charge() != -1)
        continue;

      mass = ZeeKinematicTools::calculateZMass_withTK(
          std::pair<calib::CalibElectron*, calib::CalibElectron*>(&(calibElectrons[e_it]), &(calibElectrons[p_it])));

      if (mass < 0)
        continue;

#ifdef DEBUG
      std::cout << "#######################mass " << mass << std::endl;
#endif

      zeeCandidates.push_back(
          std::pair<calib::CalibElectron*, calib::CalibElectron*>(&(calibElectrons[e_it]), &(calibElectrons[p_it])));
      double DeltaMinv = fabs(mass - MZ);

      if (DeltaMinv < DeltaMinvMin) {
        DeltaMinvMin = DeltaMinv;
        myBestZ = zeeCandidates.size() - 1;
      }
    }
  }

  //  h_DeltaZMassDistr_[loopFlag_]->Fill( (mass-MZ) / MZ );

  //  zeeCa->Fill(zeeCandidates);
  //
  h1_ZCandMult_->Fill(zeeCandidates.size());

  if (zeeCandidates.empty() || myBestZ == -1)
    return kContinue;

  if (loopFlag_ == 0)
    myZeePlots_->fillZInfo(zeeCandidates[myBestZ]);

#ifdef DEBUG
  std::cout << "Found ZCandidates " << myBestZ << std::endl;
#endif

  //  h1_zMassResol_ ->Fill(mass-myGenZMass);

  /////////////////////////////DUMP ELECTRON CLASS

  int class1 = zeeCandidates[myBestZ].first->getRecoElectron()->classification();
  int class2 = zeeCandidates[myBestZ].second->getRecoElectron()->classification();

  h1_eleClasses_->Fill(class1);
  h1_eleClasses_->Fill(class2);

  std::cout << "BEFORE " << std::endl;

  //  myZeePlots_->fillEleClassesPlots( zeeCandidates[myBestZ].first );
  //myZeePlots_->fillEleClassesPlots( zeeCandidates[myBestZ].second );

  std::cout << "AFTER " << std::endl;

  ///////////////////////ELECTRON CLASS STATISTICS

  if (class1 < 100)
    //    h1_Elec_->Fill(1);
    TOTAL_ELECTRONS_IN_BARREL++;
  if (class1 >= 100)
    TOTAL_ELECTRONS_IN_ENDCAP++;

  if (class2 < 100)
    TOTAL_ELECTRONS_IN_BARREL++;
  if (class2 >= 100)
    TOTAL_ELECTRONS_IN_ENDCAP++;

  if (class1 == 0)
    GOLDEN_ELECTRONS_IN_BARREL++;
  if (class1 == 100)
    GOLDEN_ELECTRONS_IN_ENDCAP++;
  if (class1 == 10 || class1 == 20)
    SILVER_ELECTRONS_IN_BARREL++;
  if (class1 == 110 || class1 == 120)
    SILVER_ELECTRONS_IN_ENDCAP++;
  if (class1 >= 30 && class1 <= 34)
    SHOWER_ELECTRONS_IN_BARREL++;
  if (class1 >= 130 && class1 <= 134)
    SHOWER_ELECTRONS_IN_ENDCAP++;
  if (class1 == 40)
    CRACK_ELECTRONS_IN_BARREL++;
  if (class1 == 140)
    CRACK_ELECTRONS_IN_ENDCAP++;

  if (class2 == 0)
    GOLDEN_ELECTRONS_IN_BARREL++;
  if (class2 == 100)
    GOLDEN_ELECTRONS_IN_ENDCAP++;
  if (class2 == 10 || class2 == 20)
    SILVER_ELECTRONS_IN_BARREL++;
  if (class2 == 110 || class2 == 120)
    SILVER_ELECTRONS_IN_ENDCAP++;
  if (class2 >= 30 && class2 <= 34)
    SHOWER_ELECTRONS_IN_BARREL++;
  if (class2 >= 130 && class2 <= 134)
    SHOWER_ELECTRONS_IN_ENDCAP++;
  if (class2 == 40)
    CRACK_ELECTRONS_IN_BARREL++;
  if (class2 == 140)
    CRACK_ELECTRONS_IN_ENDCAP++;

  /////////////////////////////////

  ///////////////////////////////////////EXCLUDE ELECTRONS HAVING HOTTEST XTAL WHICH IS A BORDER XTAL - begin

  DetId firstElehottestDetId =
      getHottestDetId(
          zeeCandidates[myBestZ].first->getRecoElectron()->superCluster()->seed()->hitsAndFractions(), hits, ehits)
          .first;
  DetId secondElehottestDetId =
      getHottestDetId(
          zeeCandidates[myBestZ].second->getRecoElectron()->superCluster()->seed()->hitsAndFractions(), hits, ehits)
          .first;

  bool firstElectronIsOnModuleBorder(false);
  bool secondElectronIsOnModuleBorder(false);

  h1_eventsBeforeBorderSelection_->Fill(1);

  if (class1 < 100) {
    if (firstElehottestDetId.subdetId() == EcalBarrel)
      firstElectronIsOnModuleBorder = xtalIsOnModuleBorder(firstElehottestDetId);

    BARREL_ELECTRONS_BEFORE_BORDER_CUT++;

    if (firstElehottestDetId.subdetId() == EcalBarrel && !firstElectronIsOnModuleBorder)
      BARREL_ELECTRONS_AFTER_BORDER_CUT++;
  }

  if (class2 < 100) {
    if (secondElehottestDetId.subdetId() == EcalBarrel)
      secondElectronIsOnModuleBorder = xtalIsOnModuleBorder(secondElehottestDetId);

    BARREL_ELECTRONS_BEFORE_BORDER_CUT++;

    if (secondElehottestDetId.subdetId() == EcalBarrel && !secondElectronIsOnModuleBorder)
      BARREL_ELECTRONS_AFTER_BORDER_CUT++;
  }

  if (class1 < 100) {
    if (firstElehottestDetId.subdetId() == EcalBarrel && firstElectronIsOnModuleBorder) {
      h1_borderElectronClassification_->Fill(class1);
      return kContinue;
    }
  }

  if (class2 < 100) {
    if (secondElehottestDetId.subdetId() == EcalBarrel && secondElectronIsOnModuleBorder) {
      h1_borderElectronClassification_->Fill(class2);
      return kContinue;
    }
  }

  h1_eventsAfterBorderSelection_->Fill(1);
  ///////////////////////////////////////EXCLUDE ELECTRONS HAVING HOTTEST XTAL WHICH IS A BORDER XTAL - end

  if (class1 < 100 && class2 < 100) {
    BBZN++;
    if (class1 == 0 && class2 == 0)
      BBZN_gg++;
    if (class1 < 21 && class2 < 21)
      BBZN_tt++;
    if (class1 < 21 || class2 < 21)
      BBZN_t0++;
  }

  if (class1 >= 100 && class2 >= 100) {
    EEZN++;
    if (class1 == 100 && class2 == 100)
      EEZN_gg++;
    if (class1 < 121 && class2 < 121)
      EEZN_tt++;
    if (class1 < 121 || class2 < 121)
      EEZN_t0++;
  }

  if ((class1 < 100 && class2 >= 100) || (class2 < 100 && class1 >= 100)) {
    EBZN++;
    if ((class1 == 0 && class2 == 100) || (class2 == 0 && class1 == 100))
      EBZN_gg++;
    if ((class1 < 21 && class2 < 121) || (class2 < 21 && class1 < 121))
      EBZN_tt++;
    if (class2 < 21 || class1 < 21 || class2 < 121 || class1 < 121)
      EBZN_t0++;
  }

  ///////////////////////////ELECTRON SELECTION///////////////////////////////

  if (myBestZ == -1)
    return kContinue;

  bool invMassBool = ((mass > minInvMassCut_) && (mass < maxInvMassCut_));

  bool selectionBool = false;
  //0 = all electrons (but no crack)

  ////////EWK selection - begin

  float theta1 = 2. * atan(exp(-zeeCandidates[myBestZ].first->getRecoElectron()->superCluster()->eta()));
  bool ET_1 = ((zeeCandidates[myBestZ].first->getRecoElectron()->superCluster()->energy() * sin(theta1)) > 20.);

  float theta2 = 2. * atan(exp(-zeeCandidates[myBestZ].second->getRecoElectron()->superCluster()->eta()));
  bool ET_2 = ((zeeCandidates[myBestZ].second->getRecoElectron()->superCluster()->energy() * sin(theta2)) > 20.);

  bool HoE_1 = (zeeCandidates[myBestZ].first->getRecoElectron()->hadronicOverEm() < 0.115);
  bool HoE_2 = (zeeCandidates[myBestZ].second->getRecoElectron()->hadronicOverEm() < 0.115);

  bool DeltaPhiIn_1 = (zeeCandidates[myBestZ].first->getRecoElectron()->deltaPhiSuperClusterTrackAtVtx() < 0.090);
  bool DeltaPhiIn_2 = (zeeCandidates[myBestZ].second->getRecoElectron()->deltaPhiSuperClusterTrackAtVtx() < 0.090);

  bool DeltaEtaIn_1 = (zeeCandidates[myBestZ].first->getRecoElectron()->deltaEtaSuperClusterTrackAtVtx() < 0.0090);
  bool DeltaEtaIn_2 = (zeeCandidates[myBestZ].second->getRecoElectron()->deltaEtaSuperClusterTrackAtVtx() < 0.0090);

  h1_eventsBeforeEWKSelection_->Fill(1);

  if (!(invMassBool && ET_1 && ET_2 && HoE_1 && HoE_2 && DeltaPhiIn_1 && DeltaPhiIn_2 && DeltaEtaIn_1 && DeltaEtaIn_2))
    return kContinue;
  ////////EWK selection - end

  h1_eventsAfterEWKSelection_->Fill(1);

  ///////////////////////////////////////EXCLUDE ELECTRONS HAVING HOTTEST XTAL WHICH IS A BORDER XTAL

  int c1st = zeeCandidates[myBestZ].first->getRecoElectron()->classification();
  int c2nd = zeeCandidates[myBestZ].second->getRecoElectron()->classification();
  if (electronSelection_ == 0)
    selectionBool = (myBestZ != -1 && c1st != 40 && c1st != 40 && c2nd != 40 && c2nd != 140);

  //1 = all electrons are Golden, BB or Narrow

  if (electronSelection_ == 1)
    selectionBool =
        (myBestZ != -1 && (c1st == 0 || c1st == 10 || c1st == 20 || c1st == 100 || c1st == 110 || c1st == 120) &&
         (c2nd == 0 || c2nd == 10 || c2nd == 20 || c2nd == 100 || c2nd == 110 || c2nd == 120));

  //2 = all electrons are Golden
  if (electronSelection_ == 2)
    selectionBool = (myBestZ != -1 && (c1st == 0 || c1st == 100) && (c2nd == 0 || c2nd == 100));
  //3 = all electrons are showering
  if (electronSelection_ == 3)
    selectionBool = (myBestZ != -1 && ((c1st >= 30 && c1st <= 34) || ((c1st >= 130 && c1st <= 134))) &&
                     ((c2nd >= 30 && c2nd <= 34) || ((c2nd >= 130 && c2nd <= 134)))

    );

  //4 = all Barrel electrons are Golden, BB or Narrow; take all Endcap electrons

  if (electronSelection_ == 4)
    selectionBool = (myBestZ != -1 && (

                                          ((c1st == 0 || c1st == 10 || c1st == 20) && c2nd >= 100 && c2nd != 140)

                                          ||

                                          ((c2nd == 0 || c2nd == 10 || c2nd == 20) && c1st >= 100 && c1st != 140)

                                              ));

  //5 = all Endcap electrons (but no crack)

  if (electronSelection_ == 5)
    selectionBool = (myBestZ != -1 && c1st >= 100 && c2nd >= 100 && c1st != 140 && c2nd != 140);

  //6 = all Barrel electrons (but no crack)

  if (electronSelection_ == 6)
    selectionBool = (myBestZ != -1 && c1st < 100 && c2nd < 100 && c1st != 40 && c2nd != 40);

  //7 = this eliminates the events which have 1 ele in the Barrel and 1 in the Endcap

  if (electronSelection_ == 7)
    selectionBool = (myBestZ != -1 && !(c1st < 100 && c2nd >= 100) && !(c1st >= 100 && c2nd < 100));

  float ele1EnergyCorrection(1.);
  float ele2EnergyCorrection(1.);

  if (invMassBool && selectionBool && wantEtaCorrection_) {
    ele1EnergyCorrection = getEtaCorrection(zeeCandidates[myBestZ].first->getRecoElectron());
    ele2EnergyCorrection = getEtaCorrection(zeeCandidates[myBestZ].second->getRecoElectron());
  }

  if (invMassBool && selectionBool) {
    h1_electronCosTheta_SC_->Fill(
        ZeeKinematicTools::cosThetaElectrons_SC(zeeCandidates[myBestZ], ele1EnergyCorrection, ele2EnergyCorrection));
    h1_electronCosTheta_TK_->Fill(
        ZeeKinematicTools::cosThetaElectrons_TK(zeeCandidates[myBestZ], ele1EnergyCorrection, ele2EnergyCorrection));
    h1_electronCosTheta_SC_TK_->Fill(
        ZeeKinematicTools::cosThetaElectrons_SC(zeeCandidates[myBestZ], ele1EnergyCorrection, ele2EnergyCorrection) /
            ZeeKinematicTools::cosThetaElectrons_TK(
                zeeCandidates[myBestZ], ele1EnergyCorrection, ele2EnergyCorrection) -
        1.);

    if (!mcProducer_.empty()) {
      h1_zMassResol_->Fill(mass - myGenZMass);

      //reco-mc association map - begin

      std::map<HepMC::GenParticle*, const reco::GsfElectron*> myMCmap;

      std::vector<const reco::GsfElectron*> dauElectronCollection;

      dauElectronCollection.push_back(zeeCandidates[myBestZ].first->getRecoElectron());
      dauElectronCollection.push_back(zeeCandidates[myBestZ].second->getRecoElectron());

      fillMCmap(&dauElectronCollection, mcEle, myMCmap);
      fillEleInfo(mcEle, myMCmap);
      //h_DiffZMassDistr_[loopFlag_]->Fill( (mass-myGenZMass) );
    }

    //PUT f(eta) IN OUR Zee ALGORITHM
    theAlgorithm_->addEvent(zeeCandidates[myBestZ].first,
                            zeeCandidates[myBestZ].second,
                            MZ * sqrt(ele1EnergyCorrection * ele2EnergyCorrection));

    h1_reco_ZMass_->Fill(ZeeKinematicTools::calculateZMass_withTK(zeeCandidates[myBestZ]));

    h1_reco_ZMassCorr_->Fill(ZeeKinematicTools::calculateZMassWithCorrectedElectrons_withTK(
        zeeCandidates[myBestZ], ele1EnergyCorrection, ele2EnergyCorrection));

    int c1st = zeeCandidates[myBestZ].first->getRecoElectron()->classification();
    int c2nd = zeeCandidates[myBestZ].second->getRecoElectron()->classification();
    if (c1st < 100 && c2nd < 100)
      h1_reco_ZMassCorrBB_->Fill(ZeeKinematicTools::calculateZMassWithCorrectedElectrons_withTK(
          zeeCandidates[myBestZ], ele1EnergyCorrection, ele2EnergyCorrection));

    if (c1st >= 100 && c2nd >= 100)
      h1_reco_ZMassCorrEE_->Fill(ZeeKinematicTools::calculateZMassWithCorrectedElectrons_withTK(
          zeeCandidates[myBestZ], ele1EnergyCorrection, ele2EnergyCorrection));

    mass4tree = ZeeKinematicTools::calculateZMassWithCorrectedElectrons_withTK(
        zeeCandidates[myBestZ], ele1EnergyCorrection, ele2EnergyCorrection);

    massDiff4tree = ZeeKinematicTools::calculateZMassWithCorrectedElectrons_withTK(
                        zeeCandidates[myBestZ], ele1EnergyCorrection, ele2EnergyCorrection) -
                    myGenZMass;

    //      h_ZMassDistr_[loopFlag_]->Fill(ZeeKinematicTools::calculateZMassWithCorrectedElectrons_withTK(zeeCandidates[myBestZ],ele1EnergyCorrection,ele2EnergyCorrection));

    myTree->Fill();
  }

#ifdef DEBUG
  std::cout << "Added event to algorithm" << std::endl;
#endif

  return kContinue;
}
//end of ZeeCalibration::duringLoop

// Called at beginning of loop
void ZeeCalibration::startingNewLoop(unsigned int iLoop) {
  std::cout << "[ZeeCalibration] Starting loop number " << iLoop << std::endl;

  theAlgorithm_->resetIteration();

  resetVariables();

  resetHistograms();

#ifdef DEBUG
  std::cout << "[ZeeCalibration] exiting from startingNewLoop" << std::endl;
#endif
}

// Called at end of loop
edm::EDLooper::Status ZeeCalibration::endOfLoop(const edm::EventSetup& iSetup, unsigned int iLoop) {
  double par[3];
  double errpar[3];
  double zChi2;
  int zIters;

  ZIterativeAlgorithmWithFit::gausfit(h1_reco_ZMass_, par, errpar, 2., 2., &zChi2, &zIters);

  h2_zMassVsLoop_->Fill(loopFlag_, par[1]);

  h2_zMassDiffVsLoop_->Fill(loopFlag_, (par[1] - MZ) / MZ);

  h2_zWidthVsLoop_->Fill(loopFlag_, par[2]);

  //////////////////FIT Z PEAK

  std::cout << "[ZeeCalibration] Ending loop " << iLoop << std::endl;
  //RUN the algorithm
  theAlgorithm_->iterate();

  const std::vector<float>& optimizedCoefficients = theAlgorithm_->getOptimizedCoefficients();
  const std::vector<float>& optimizedCoefficientsError = theAlgorithm_->getOptimizedCoefficientsError();
  //const std::vector<float>& weightSum = theAlgorithm_->getWeightSum();
  const std::vector<float>& optimizedChi2 = theAlgorithm_->getOptimizedChiSquare();
  const std::vector<int>& optimizedIterations = theAlgorithm_->getOptimizedIterations();

  //#ifdef DEBUG
  std::cout << "Optimized coefficients " << optimizedCoefficients.size() << std::endl;
  //#endif

  //  h2_coeffVsLoop_->Fill(loopFlag_, optimizedCoefficients[75]); //show the evolution of just 1 ring coefficient (well chosen...)

  //////////////define NewCalibCoeff - begin
  for (unsigned int ieta = 0; ieta < optimizedCoefficients.size(); ieta++) {
    NewCalibCoeff[ieta] = calibCoeff[ieta] * optimizedCoefficients[ieta];

    h2_chi2_[loopFlag_]->Fill(ringNumberCorrector(ieta), optimizedChi2[ieta]);
    h2_iterations_[loopFlag_]->Fill(ringNumberCorrector(ieta), optimizedIterations[ieta]);
  }
  //////////////define NewCalibCoeff - end

  coefficientDistanceAtIteration[loopFlag_] =
      computeCoefficientDistanceAtIteration(calibCoeff, NewCalibCoeff, optimizedCoefficients.size());

  std::cout << "Iteration # : " << loopFlag_ << " CoefficientDistanceAtIteration "
            << coefficientDistanceAtIteration[loopFlag_] << std::endl;
  std::cout << "size " << optimizedCoefficients.size() << std::endl;

  for (unsigned int ieta = 0; ieta < optimizedCoefficients.size(); ieta++) {
    calibCoeff[ieta] *= optimizedCoefficients[ieta];
    calibCoeffError[ieta] =
        calibCoeff[ieta] * sqrt(pow(optimizedCoefficientsError[ieta] / optimizedCoefficients[ieta], 2) +
                                pow(calibCoeffError[ieta] / calibCoeff[ieta], 2));
    //calibCoeffError[ieta] = optimizedCoefficientsError[ieta];

#ifdef DEBUG
    std::cout << ieta << " " << optimizedCoefficients[ieta] << std::endl;
#endif

    std::vector<DetId> ringIds;

    if (calibMode_ == "RING")
      ringIds = EcalRingCalibrationTools::getDetIdsInRing(ieta);

    if (calibMode_ == "MODULE")
      ringIds = EcalRingCalibrationTools::getDetIdsInModule(ieta);

    if (calibMode_ == "ABS_SCALE" || calibMode_ == "ETA_ET_MODE")
      ringIds = EcalRingCalibrationTools::getDetIdsInECAL();

    for (unsigned int iid = 0; iid < ringIds.size(); ++iid) {
      if (ringIds[iid].subdetId() == EcalBarrel) {
        EBDetId myEBDetId(ringIds[iid]);
        h2_xtalRecalibCoeffBarrel_[loopFlag_]->SetBinContent(
            myEBDetId.ieta() + 86,
            myEBDetId.iphi(),
            100 * (calibCoeff[ieta] * initCalibCoeff[ieta] - 1.));  //fill TH2 with recalibCoeff
      }

      if (ringIds[iid].subdetId() == EcalEndcap) {
        EEDetId myEEDetId(ringIds[iid]);
        if (myEEDetId.zside() < 0)
          h2_xtalRecalibCoeffEndcapMinus_[loopFlag_]->SetBinContent(
              myEEDetId.ix(),
              myEEDetId.iy(),
              100 * (calibCoeff[ieta] * initCalibCoeff[ieta] - 1.));  //fill TH2 with recalibCoeff

        if (myEEDetId.zside() > 0)
          h2_xtalRecalibCoeffEndcapPlus_[loopFlag_]->SetBinContent(
              myEEDetId.ix(),
              myEEDetId.iy(),
              100 * (calibCoeff[ieta] * initCalibCoeff[ieta] - 1.));  //fill TH2 with recalibCoeff
      }

      ical->setValue(ringIds[iid], *(ical->getMap().find(ringIds[iid])) * optimizedCoefficients[ieta]);
    }
  }

  /////////dump residual miscalibration at each loop

  for (int k = 0; k < theAlgorithm_->getNumberOfChannels(); k++) {
    bool isNearCrack =
        (abs(ringNumberCorrector(k)) == 1 || abs(ringNumberCorrector(k)) == 25 || abs(ringNumberCorrector(k)) == 26 ||
         abs(ringNumberCorrector(k)) == 45 || abs(ringNumberCorrector(k)) == 46 || abs(ringNumberCorrector(k)) == 65 ||
         abs(ringNumberCorrector(k)) == 66 || abs(ringNumberCorrector(k)) == 85 || abs(ringNumberCorrector(k)) == 86 ||
         abs(ringNumberCorrector(k)) == 124);

    if (!isNearCrack) {
      //	h2_miscalRecalParz_[iLoop]->Fill( initCalibCoeff[k], 1./calibCoeff[k] );
      h1_mcParz_[iLoop]->Fill(initCalibCoeff[k] * calibCoeff[k] - 1.);

      if (k < 170) {
        //h2_miscalRecalEBParz_[iLoop]->Fill( initCalibCoeff[k], 1./calibCoeff[k] );
        h1_mcEBParz_[iLoop]->Fill(initCalibCoeff[k] * calibCoeff[k] - 1.);
      }

      if (k >= 170) {
        //h2_miscalRecalEEParz_[iLoop]->Fill( initCalibCoeff[k], 1./calibCoeff[k] );
        h1_mcEEParz_[iLoop]->Fill(initCalibCoeff[k] * calibCoeff[k] - 1.);
      }
    }
  }

  /////////////////////////
  double parResidual[3];
  double errparResidual[3];
  double zResChi2;
  int zResIters;

  ZIterativeAlgorithmWithFit::gausfit(h1_mcParz_[iLoop], parResidual, errparResidual, 3., 3., &zResChi2, &zResIters);
  //h1_mcParz_[iLoop]->Fit("gaus");

  h2_residualSigma_->Fill(loopFlag_ + 1, parResidual[2]);
  loopArray[loopFlag_] = loopFlag_ + 1;
  sigmaArray[loopFlag_] = parResidual[2];
  sigmaErrorArray[loopFlag_] = errparResidual[2];

  std::cout << "Fit on residuals, sigma is " << parResidual[2] << " +/- " << errparResidual[2] << std::endl;

  /////////////////////
  outputFile_->cd();

  //  h2_miscalRecalParz_[iLoop]->Write();
  h1_mcParz_[iLoop]->Write();

  //h2_miscalRecalEBParz_[iLoop]->Write();
  h1_mcEBParz_[iLoop]->Write();

  //h2_miscalRecalEEParz_[iLoop]->Write();
  h1_mcEEParz_[iLoop]->Write();
  h2_xtalRecalibCoeffBarrel_[loopFlag_]->Write();
  h2_xtalRecalibCoeffEndcapPlus_[loopFlag_]->Write();
  h2_xtalRecalibCoeffEndcapMinus_[loopFlag_]->Write();

  /////////dump residual miscalibration at each loop

  loopFlag_++;

#ifdef DEBUG
  std::cout << " loopFlag_ is " << loopFlag_ << std::endl;
#endif

  if (iLoop == theMaxLoops - 1 || iLoop >= theMaxLoops)
    return kStop;
  else
    return kContinue;
}

void ZeeCalibration::bookHistograms() {
  h1_eventsBeforeEWKSelection_ = new TH1F("h1_eventsBeforeEWKSelection", "h1_eventsBeforeEWKSelection", 5, 0, 5);
  h1_eventsAfterEWKSelection_ = new TH1F("h1_eventsAfterEWKSelection", "h1_eventsAfterEWKSelection", 5, 0, 5);

  h1_eventsBeforeBorderSelection_ =
      new TH1F("h1_eventsBeforeBorderSelection", "h1_eventsBeforeBorderSelection", 5, 0, 5);
  h1_eventsAfterBorderSelection_ = new TH1F("h1_eventsAfterBorderSelection", "h1_eventsAfterBorderSelection", 5, 0, 5);

  h1_seedOverSC_ = new TH1F("h1_seedOverSC", "h1_seedOverSC", 400, 0., 2.);

  myZeePlots_->bookHLTHistograms();

  h1_borderElectronClassification_ =
      new TH1F("h1_borderElectronClassification", "h1_borderElectronClassification", 55, -5, 50);
  h1_preshowerOverSC_ = new TH1F("h1_preshowerOverSC", "h1_preshowerOverSC", 400, 0., 1.);

  h2_fEtaBarrelGood_ = new TH2F("fEtaBarrelGood", "fEtaBarrelGood", 800, -4., 4., 800, 0.8, 1.2);
  h2_fEtaBarrelGood_->SetXTitle("Eta");
  h2_fEtaBarrelGood_->SetYTitle("1/fEtaBarrelGood");

  h2_fEtaBarrelBad_ = new TH2F("fEtaBarrelBad", "fEtaBarrelBad", 800, -4., 4., 800, 0.8, 1.2);
  h2_fEtaBarrelBad_->SetXTitle("Eta");
  h2_fEtaBarrelBad_->SetYTitle("1/fEtaBarrelBad");

  h2_fEtaEndcapGood_ = new TH2F("fEtaEndcapGood", "fEtaEndcapGood", 800, -4., 4., 800, 0.8, 1.2);
  h2_fEtaEndcapGood_->SetXTitle("Eta");
  h2_fEtaEndcapGood_->SetYTitle("1/fEtaEndcapGood");

  h2_fEtaEndcapBad_ = new TH2F("fEtaEndcapBad", "fEtaEndcapBad", 800, -4., 4., 800, 0.8, 1.2);
  h2_fEtaEndcapBad_->SetXTitle("Eta");
  h2_fEtaEndcapBad_->SetYTitle("1/fEtaEndcapBad");

  for (int i = 0; i < 2; i++) {
    char histoName[50];

    sprintf(histoName, "h_eleEffEta_%d", i);
    h_eleEffEta_[i] = new TH1F(histoName, histoName, 150, 0., 2.7);
    h_eleEffEta_[i]->SetXTitle("|#eta|");

    sprintf(histoName, "h_eleEffPhi_%d", i);
    h_eleEffPhi_[i] = new TH1F(histoName, histoName, 400, -4., 4.);
    h_eleEffPhi_[i]->SetXTitle("Phi");

    sprintf(histoName, "h_eleEffPt_%d", i);
    h_eleEffPt_[i] = new TH1F(histoName, histoName, 200, 0., 200.);
    h_eleEffPt_[i]->SetXTitle("p_{T}(GeV/c)");
  }

  h2_xtalMiscalibCoeffBarrel_ =
      new TH2F("h2_xtalMiscalibCoeffBarrel", "h2_xtalMiscalibCoeffBarrel", 171, -85, 85, 360, 0, 360);
  h2_xtalMiscalibCoeffEndcapMinus_ =
      new TH2F("h2_xtalMiscalibCoeffEndcapMinus", "h2_xtalMiscalibCoeffEndcapMinus", 100, 0, 100, 100, 0, 100);
  h2_xtalMiscalibCoeffEndcapPlus_ =
      new TH2F("h2_xtalMiscalibCoeffEndcapPlus", "h2_xtalMiscalibCoeffEndcapPlus", 100, 0, 100, 100, 0, 100);

  h2_xtalMiscalibCoeffBarrel_->SetXTitle("ieta");
  h2_xtalMiscalibCoeffBarrel_->SetYTitle("iphi");

  h2_xtalMiscalibCoeffEndcapMinus_->SetXTitle("ix");
  h2_xtalMiscalibCoeffEndcapMinus_->SetYTitle("iy");

  for (int i = 0; i < 25; i++) {
    char histoName[50];
    sprintf(histoName, "h_ESCEtrueVsEta_%d", i);

    h_ESCEtrueVsEta_[i] = new TH2F(histoName, histoName, 150, 0., 2.7, 300, 0., 1.5);
    h_ESCEtrueVsEta_[i]->SetXTitle("|#eta|");
    h_ESCEtrueVsEta_[i]->SetYTitle("E_{SC,raw}/E_{MC}");

    sprintf(histoName, "h_ESCEtrue_%d", i);

    h_ESCEtrue_[i] = new TH1F(histoName, histoName, 300, 0., 1.5);

    sprintf(histoName, "h2_chi2_%d", i);
    h2_chi2_[i] = new TH2F(histoName, histoName, 1000, -150, 150, 1000, -1, 5);

    sprintf(histoName, "h2_iterations_%d", i);
    h2_iterations_[i] = new TH2F(histoName, histoName, 1000, -150, 150, 1000, -1, 15);

    sprintf(histoName, "h_ESCcorrEtrueVsEta_%d", i);

    h_ESCcorrEtrueVsEta_[i] = new TH2F(histoName, histoName, 150, 0., 2.7, 300, 0., 1.5);
    h_ESCcorrEtrueVsEta_[i]->SetXTitle("|#eta|");
    h_ESCcorrEtrueVsEta_[i]->SetYTitle("E_{SC,#eta-corr}/E_{MC}");

    sprintf(histoName, "h_ESCcorrEtrue_%d", i);

    h_ESCcorrEtrue_[i] = new TH1F(histoName, histoName, 300, 0., 1.5);

    sprintf(histoName, "h2_xtalRecalibCoeffBarrel_%d", i);
    h2_xtalRecalibCoeffBarrel_[i] = new TH2F(histoName, histoName, 171, -85, 85, 360, 0, 360);

    h2_xtalRecalibCoeffBarrel_[i]->SetXTitle("ieta");
    h2_xtalRecalibCoeffBarrel_[i]->SetYTitle("iphi");

    sprintf(histoName, "h2_xtalRecalibCoeffEndcapMinus_%d", i);
    h2_xtalRecalibCoeffEndcapMinus_[i] = new TH2F(histoName, histoName, 100, 0, 100, 100, 0, 100);
    h2_xtalRecalibCoeffEndcapMinus_[i]->SetXTitle("ix");
    h2_xtalRecalibCoeffEndcapMinus_[i]->SetYTitle("iy");

    sprintf(histoName, "h2_xtalRecalibCoeffEndcapPlus_%d", i);
    h2_xtalRecalibCoeffEndcapPlus_[i] = new TH2F(histoName, histoName, 100, 0, 100, 100, 0, 100);
    h2_xtalRecalibCoeffEndcapPlus_[i]->SetXTitle("ix");
    h2_xtalRecalibCoeffEndcapPlus_[i]->SetYTitle("iy");
  }

  /*
  for (int i=0;i<15;i++)
    {
                                                                                                                             
      char histoName[50];

      sprintf(histoName,"h_DiffZMassDistr_%d",i);
      h_DiffZMassDistr_[i] = new TH1F(histoName,histoName, 400, -20., 20.);
      h_DiffZMassDistr_[i]->SetXTitle("M_{Z, reco} - M_{Z, MC}");
      h_DiffZMassDistr_[i]->SetYTitle("events");

      sprintf(histoName,"h_ZMassDistr_%d",i);
      h_ZMassDistr_[i] = new TH1F(histoName,histoName, 200, 0., 150.);
      h_ZMassDistr_[i]->SetXTitle("RecoZmass (GeV)");
      h_ZMassDistr_[i]->SetYTitle("events");

    }
  */

  h1_zMassResol_ = new TH1F("zMassResol", "zMassResol", 200, -50., 50.);
  h1_zMassResol_->SetXTitle("M_{Z, reco} - M_{Z, MC}");
  h1_zMassResol_->SetYTitle("events");

  h1_eleEtaResol_ = new TH1F("eleEtaResol", "eleEtaResol", 100, -0.01, 0.01);
  h1_eleEtaResol_->SetXTitle("#eta_{reco} - #eta_{MC}");
  h1_eleEtaResol_->SetYTitle("events");

  h1_electronCosTheta_TK_ = new TH1F("electronCosTheta_TK", "electronCosTheta_TK", 100, -1, 1);
  h1_electronCosTheta_TK_->SetXTitle("cos #theta_{12}");
  h1_electronCosTheta_TK_->SetYTitle("events");

  h1_electronCosTheta_SC_ = new TH1F("electronCosTheta_SC", "electronCosTheta_SC", 100, -1, 1);
  h1_electronCosTheta_SC_->SetXTitle("cos #theta_{12}");
  h1_electronCosTheta_SC_->SetYTitle("events");

  h1_electronCosTheta_SC_TK_ = new TH1F("electronCosTheta_SC_TK", "electronCosTheta_SC_TK", 200, -0.1, 0.1);
  h1_electronCosTheta_SC_TK_->SetXTitle("cos #theta_{12}^{SC}/ cos #theta_{12}^{TK} - 1");
  h1_electronCosTheta_SC_TK_->SetYTitle("events");

  h1_elePhiResol_ = new TH1F("elePhiResol", "elePhiResol", 100, -0.01, 0.01);
  h1_elePhiResol_->SetXTitle("#phi_{reco} - #phi_{MC}");
  h1_elePhiResol_->SetYTitle("events");

  h1_zEtaResol_ = new TH1F("zEtaResol", "zEtaResol", 200, -1., 1.);
  h1_zEtaResol_->SetXTitle("#eta_{Z, reco} - #eta_{Z, MC}");
  h1_zEtaResol_->SetYTitle("events");

  h1_zPhiResol_ = new TH1F("zPhiResol", "zPhiResol", 200, -1., 1.);
  h1_zPhiResol_->SetXTitle("#phi_{Z, reco} - #phi_{Z, MC}");
  h1_zPhiResol_->SetYTitle("events");

  h1_nEleReco_ = new TH1F("nEleReco", "Number of reco electrons", 10, -0.5, 10.5);
  h1_nEleReco_->SetXTitle("nEleReco");
  h1_nEleReco_->SetYTitle("events");

  //  h1_occupancyVsEta_ = new TH1F("occupancyVsEta","occupancyVsEta",EcalRingCalibrationTools::N_RING_TOTAL,0,(float)EcalRingCalibrationTools::N_RING_TOTAL);

  h1_occupancyVsEta_ = new TH1F("occupancyVsEta", "occupancyVsEta", 249, -124, 124);
  h1_occupancyVsEta_->SetYTitle("Weighted electron statistics");
  h1_occupancyVsEta_->SetXTitle("Eta channel");

  h1_weightSumMeanBarrel_ = new TH1F("weightSumMeanBarrel", "weightSumMeanBarrel", 10000, 0, 10000);
  h1_weightSumMeanEndcap_ = new TH1F("weightSumMeanEndcap", "weightSumMeanEndcap", 10000, 0, 10000);

  h1_occupancy_ = new TH1F("occupancy", "occupancy", 1000, 0, 10000);
  h1_occupancy_->SetXTitle("Weighted electron statistics");

  h1_occupancyBarrel_ = new TH1F("occupancyBarrel", "occupancyBarrel", 1000, 0, 10000);
  h1_occupancyBarrel_->SetXTitle("Weighted electron statistics");

  h1_occupancyEndcap_ = new TH1F("occupancyEndcap", "occupancyEndcap", 1000, 0, 10000);
  h1_occupancyEndcap_->SetXTitle("Weighted electron statistics");

  h1_eleClasses_ = new TH1F("eleClasses", "eleClasses", 301, -1, 300);
  h1_eleClasses_->SetXTitle("classCode");
  h1_eleClasses_->SetYTitle("#");

  myZeePlots_->bookZMCHistograms();

  myZeePlots_->bookZHistograms();

  myZeePlots_->bookEleMCHistograms();

  myZeePlots_->bookEleHistograms();

  h1_ZCandMult_ = new TH1F("ZCandMult", "Multiplicity of Z candidates in one event", 10, -0.5, 10.5);
  h1_ZCandMult_->SetXTitle("ZCandMult");

  h1_reco_ZMass_ = new TH1F("reco_ZMass", "Inv. mass of 2 reco Electrons", 200, 0., 150.);
  h1_reco_ZMass_->SetXTitle("reco_ZMass (GeV)");
  h1_reco_ZMass_->SetYTitle("events");

  h1_reco_ZMassCorr_ = new TH1F("reco_ZMassCorr", "Inv. mass of 2 corrected reco Electrons", 200, 0., 150.);
  h1_reco_ZMassCorr_->SetXTitle("reco_ZMass (GeV)");
  h1_reco_ZMassCorr_->SetYTitle("events");

  h1_reco_ZMassCorrBB_ = new TH1F("reco_ZMassCorrBB", "Inv. mass of 2 corrected reco Electrons", 200, 0., 150.);
  h1_reco_ZMassCorrBB_->SetXTitle("reco_ZMass (GeV)");
  h1_reco_ZMassCorrBB_->SetYTitle("events");

  h1_reco_ZMassCorrEE_ = new TH1F("reco_ZMassCorrEE", "Inv. mass of 2 corrected reco Electrons", 200, 0., 150.);
  h1_reco_ZMassCorrEE_->SetXTitle("reco_ZMass (GeV)");
  h1_reco_ZMassCorrEE_->SetYTitle("events");

  //  h2_coeffVsEta_= new TH2F("h2_calibCoeffVsEta","h2_calibCoeffVsEta",EcalRingCalibrationTools::N_RING_TOTAL,0, (double)EcalRingCalibrationTools::N_RING_TOTAL, 200, 0., 2.);

  h2_coeffVsEta_ = new TH2F("h2_calibCoeffVsEta", "h2_calibCoeffVsEta", 249, -124, 125, 200, 0., 2.);
  h2_coeffVsEta_->SetXTitle("Eta channel");
  h2_coeffVsEta_->SetYTitle("recalibCoeff");

  h2_coeffVsEtaGrouped_ =
      new TH2F("h2_calibCoeffVsEtaGrouped", "h2_calibCoeffVsEtaGrouped", 200, 0., 3., 200, 0.6, 1.4);
  h2_coeffVsEtaGrouped_->SetXTitle("|#eta|");
  h2_coeffVsEtaGrouped_->SetYTitle("recalibCoeff");

  h2_zMassVsLoop_ = new TH2F("h2_zMassVsLoop", "h2_zMassVsLoop", 1000, 0, 40, 90, 80., 95.);

  h2_zMassDiffVsLoop_ = new TH2F("h2_zMassDiffVsLoop", "h2_zMassDiffVsLoop", 1000, 0, 40, 100, -1., 1.);
  h2_zMassDiffVsLoop_->SetXTitle("Iteration");
  h2_zMassDiffVsLoop_->SetYTitle("M_{Z, reco peak} - M_{Z, true}");

  h2_zWidthVsLoop_ = new TH2F("h2_zWidthVsLoop", "h2_zWidthVsLoop", 1000, 0, 40, 100, 0., 10.);

  h2_coeffVsLoop_ = new TH2F("h2_coeffVsLoop", "h2_coeffVsLoop", 1000, 0, 40, 100, 0., 2.);

  h2_residualSigma_ = new TH2F("h2_residualSigma", "h2_residualSigma", 1000, 0, 40, 100, 0., .5);

  h2_miscalRecal_ = new TH2F("h2_miscalRecal", "h2_miscalRecal", 500, 0., 2., 500, 0., 2.);
  h2_miscalRecal_->SetXTitle("initCalibCoeff");
  h2_miscalRecal_->SetYTitle("1/RecalibCoeff");

  h2_miscalRecalEB_ = new TH2F("h2_miscalRecalEB", "h2_miscalRecalEB", 500, 0., 2., 500, 0., 2.);
  h2_miscalRecalEB_->SetXTitle("initCalibCoeff");
  h2_miscalRecalEB_->SetYTitle("1/RecalibCoeff");

  h2_miscalRecalEE_ = new TH2F("h2_miscalRecalEE", "h2_miscalRecalEE", 500, 0., 2., 500, 0., 2.);
  h2_miscalRecalEE_->SetXTitle("initCalibCoeff");
  h2_miscalRecalEE_->SetYTitle("1/RecalibCoeff");

  h1_mc_ = new TH1F("h1_residualMiscalib", "h1_residualMiscalib", 200, -0.2, 0.2);
  h1_mcEB_ = new TH1F("h1_residualMiscalibEB", "h1_residualMiscalibEB", 200, -0.2, 0.2);
  h1_mcEE_ = new TH1F("h1_residualMiscalibEE", "h1_residualMiscalibEE", 200, -0.2, 0.2);

  for (int i = 0; i < 25; i++) {
    char histoName[50];
    /*     
	     sprintf(histoName,"h2_miscalRecalParz_%d",i);
	     h2_miscalRecalParz_[i] = new TH2F(histoName,histoName,500, 0., 2., 500, 0., 2.);
	     h2_miscalRecalParz_[i]->SetXTitle("initCalibCoeff");
	     h2_miscalRecalParz_[i]->SetYTitle("1/recalibCoeff");
	     
	     sprintf(histoName,"h2_miscalRecalEBParz_%d",i);
	     h2_miscalRecalEBParz_[i] = new TH2F(histoName,histoName,500, 0., 2., 500, 0., 2.);
	     h2_miscalRecalEBParz_[i]->SetXTitle("initCalibCoeff");
	     h2_miscalRecalEBParz_[i]->SetYTitle("1/recalibCoeff");
	     
      sprintf(histoName,"h2_miscalRecalEEParz_%d",i);
      h2_miscalRecalEEParz_[i] = new TH2F(histoName,histoName,500, 0., 2., 500, 0., 2.);
      h2_miscalRecalEEParz_[i]->SetXTitle("initCalibCoeff");
      h2_miscalRecalEEParz_[i]->SetYTitle("1/recalibCoeff");
      */

    sprintf(histoName, "h1_residualMiscalibParz_%d", i);
    h1_mcParz_[i] = new TH1F(histoName, histoName, 200, -0.2, 0.2);
    sprintf(histoName, "h1_residualMiscalibEBParz_%d", i);
    h1_mcEBParz_[i] = new TH1F(histoName, histoName, 200, -0.2, 0.2);
    sprintf(histoName, "h1_residualMiscalibEEParz_%d", i);
    h1_mcEEParz_[i] = new TH1F(histoName, histoName, 200, -0.2, 0.2);
  }
}

double ZeeCalibration::fEtaBarrelBad(double scEta) const {
  float p0 = 1.00153e+00;
  float p1 = 3.29331e-02;
  float p2 = 1.21187e-03;

  double x = (double)fabs(scEta);

  return 1. / (p0 + p1 * x * x + p2 * x * x * x * x);
}

double ZeeCalibration::fEtaEndcapGood(double scEta) const {
  // f(eta) for the first 3 classes (100, 110 and 120)
  // Ivica's new corrections 01/06
  float p0 = 1.06819e+00;
  float p1 = -1.53189e-02;
  float p2 = 4.01707e-04;

  double x = (double)fabs(scEta);

  return 1. / (p0 + p1 * x * x + p2 * x * x * x * x);
}

double ZeeCalibration::fEtaEndcapBad(double scEta) const {
  float p0 = 1.17382e+00;
  float p1 = -6.52319e-02;
  float p2 = 6.26108e-03;

  double x = (double)fabs(scEta);

  return 1. / (p0 + p1 * x * x + p2 * x * x * x * x);
}

double ZeeCalibration::fEtaBarrelGood(double scEta) const {
  float p0 = 9.99782e-01;
  float p1 = 1.26983e-02;
  float p2 = 2.16344e-03;

  double x = (double)fabs(scEta);

  return 1. / (p0 + p1 * x * x + p2 * x * x * x * x);
}

//////////////////////////////////new part

void ZeeCalibration::fillMCmap(const std::vector<const reco::GsfElectron*>* electronCollection,
                               const std::vector<HepMC::GenParticle*>& mcEle,
                               std::map<HepMC::GenParticle*, const reco::GsfElectron*>& myMCmap) {
  for (unsigned int i = 0; i < mcEle.size(); i++) {
    float minDR = 0.1;
    const reco::GsfElectron* myMatchEle = nullptr;
    for (unsigned int j = 0; j < electronCollection->size(); j++) {
      float dr = EvalDR(mcEle[i]->momentum().pseudoRapidity(),
                        (*(*electronCollection)[j]).eta(),
                        mcEle[i]->momentum().phi(),
                        (*(*electronCollection)[j]).phi());
      if (dr < minDR) {
        myMatchEle = (*electronCollection)[j];
        minDR = dr;
      }
    }
    myMCmap.insert(std::pair<HepMC::GenParticle*, const reco::GsfElectron*>(mcEle[i], myMatchEle));
  }
}

float ZeeCalibration::EvalDR(float Eta, float Eta_ref, float Phi, float Phi_ref) {
  if (Phi < 0)
    Phi = 2 * TMath::Pi() + Phi;
  if (Phi_ref < 0)
    Phi_ref = 2 * TMath::Pi() + Phi_ref;
  float DPhi = Phi - Phi_ref;
  if (fabs(DPhi) > TMath::Pi())
    DPhi = 2 * TMath::Pi() - fabs(DPhi);

  float DEta = Eta - Eta_ref;

  float DR = sqrt(DEta * DEta + DPhi * DPhi);
  return DR;
}

float ZeeCalibration::EvalDPhi(float Phi, float Phi_ref) {
  if (Phi < 0)
    Phi = 2 * TMath::Pi() + Phi;
  if (Phi_ref < 0)
    Phi_ref = 2 * TMath::Pi() + Phi_ref;
  return (Phi - Phi_ref);
}

void ZeeCalibration::fillEleInfo(std::vector<HepMC::GenParticle*>& mcEle,
                                 std::map<HepMC::GenParticle*, const reco::GsfElectron*>& associationMap) {
  for (unsigned int i = 0; i < mcEle.size(); i++) {
    h_eleEffEta_[0]->Fill(fabs(mcEle[i]->momentum().pseudoRapidity()));
    h_eleEffPhi_[0]->Fill(mcEle[i]->momentum().phi());
    h_eleEffPt_[0]->Fill(mcEle[i]->momentum().perp());

    std::map<HepMC::GenParticle*, const reco::GsfElectron*>::const_iterator mIter = associationMap.find(mcEle[i]);
    if (mIter == associationMap.end())
      continue;

    if ((*mIter).second) {
      const reco::GsfElectron* myEle = (*mIter).second;

      h_eleEffEta_[1]->Fill(fabs(mcEle[i]->momentum().pseudoRapidity()));
      h_eleEffPhi_[1]->Fill(mcEle[i]->momentum().phi());
      h_eleEffPt_[1]->Fill(mcEle[i]->momentum().perp());
      h1_eleEtaResol_->Fill(myEle->eta() - mcEle[i]->momentum().eta());
      h1_elePhiResol_->Fill(myEle->phi() - mcEle[i]->momentum().phi());

      const reco::SuperCluster* mySC = &(*(myEle->superCluster()));
      if (/*fabs(mySC->position().eta()) < 2.4*/ true) {
        //      if(myEle->classification()>=100)std::cout<<"mySC->preshowerEnergy()"<<mySC->preshowerEnergy()<<std::endl;

        h_ESCEtrue_[loopFlag_]->Fill(mySC->energy() / mcEle[i]->momentum().e());
        h_ESCEtrueVsEta_[loopFlag_]->Fill(fabs(mySC->position().eta()), mySC->energy() / mcEle[i]->momentum().e());

        double corrSCenergy = (mySC->energy()) / getEtaCorrection(myEle);
        h_ESCcorrEtrue_[loopFlag_]->Fill(corrSCenergy / mcEle[i]->momentum().e());
        h_ESCcorrEtrueVsEta_[loopFlag_]->Fill(fabs(mySC->position().eta()), corrSCenergy / mcEle[i]->momentum().e());

        //	      std::vector<DetId> mySCRecHits = mySC->seed()->getHitsByDetId();

        h1_seedOverSC_->Fill(mySC->seed()->energy() / mySC->energy());
        h1_preshowerOverSC_->Fill(mySC->preshowerEnergy() / mySC->energy());
      }
    }
  }
}

int ZeeCalibration::ringNumberCorrector(int k) {
  int index = -999;

  if (calibMode_ == "RING") {
    if (k >= 0 && k <= 84)
      index = k - 85;

    if (k >= 85 && k <= 169)
      index = k - 84;

    if (k >= 170 && k <= 208)
      index = -k + 84;

    if (k >= 209 && k <= 247)
      index = k - 123;

  }

  else if (calibMode_ == "MODULE") {
    if (k >= 0 && k <= 71)
      index = k - 72;

    if (k >= 72 && k <= 143)
      index = k - 71;
  }
  return index;
}

double ZeeCalibration::getEtaCorrection(const reco::GsfElectron* ele) {
  double correction(1.);

  int c = ele->classification();
  if (c == 0 || c == 10 || c == 20)
    correction = fEtaBarrelGood(ele->superCluster()->eta());

  if (c == 100 || c == 110 || c == 120)
    correction = fEtaEndcapGood(ele->superCluster()->eta());

  if (c == 30 || c == 31 || c == 32 || c == 33 || c == 34)
    correction = fEtaBarrelBad(ele->superCluster()->eta());

  if (c == 130 || c == 131 || c == 132 || c == 133 || c == 134)
    correction = fEtaEndcapBad(ele->superCluster()->eta());

  return correction;
}

std::pair<DetId, double> ZeeCalibration::getHottestDetId(const std::vector<std::pair<DetId, float> >& mySCRecHits,
                                                         const EBRecHitCollection* ebhits,
                                                         const EERecHitCollection* eehits) {
  double maxEnergy = -9999.;
  const EcalRecHit* hottestRecHit = nullptr;

  std::pair<DetId, double> myPair(DetId(0), -9999.);

  for (std::vector<std::pair<DetId, float> >::const_iterator idIt = mySCRecHits.begin(); idIt != mySCRecHits.end();
       idIt++) {
    if (idIt->first.subdetId() == EcalBarrel) {
      hottestRecHit = &(*(ebhits->find((*idIt).first)));

      if (hottestRecHit == &(*(ebhits->end()))) {
        std::cout << "@@@@@@@@@@@@@@@@@@@@@@@@@@@ NO RECHIT FOUND SHOULD NEVER HAPPEN" << std::endl;
        continue;
      }
    } else if (idIt->first.subdetId() == EcalEndcap) {
      hottestRecHit = &(*(eehits->find((*idIt).first)));
      if (hottestRecHit == &(*(eehits->end()))) {
        std::cout << "@@@@@@@@@@@@@@@@@@@@@@@@@@@ NO RECHIT FOUND SHOULD NEVER HAPPEN" << std::endl;
        continue;
      }
    }

    //std::cout<<"[getHottestDetId] hottestRecHit->energy() "<<hottestRecHit->energy()<<std::endl;

    if (hottestRecHit && hottestRecHit->energy() > maxEnergy) {
      maxEnergy = hottestRecHit->energy();

      myPair.first = hottestRecHit->id();
      myPair.second = maxEnergy;
    }

  }  //end loop to find hottest RecHit

  //std::cout<<"[ZeeCalibration::getHottestDetId] going to return..."<<std::endl;

  return myPair;
}

bool ZeeCalibration::xtalIsOnModuleBorder(EBDetId myEBDetId) {
  bool myBool(false);

  short ieta = myEBDetId.ieta();
  short iphi = myEBDetId.iphi();

  //  std::cout<<"[xtalIsOnModuleBorder] ieta: "<<ieta<<" iphi "<<iphi<<std::endl;

  myBool = (abs(ieta) == 1 || abs(ieta) == 25 || abs(ieta) == 26 || abs(ieta) == 45 || abs(ieta) == 46 ||
            abs(ieta) == 65 || abs(ieta) == 66 || abs(ieta) == 85);

  for (int i = 0; i < 19; i++) {
    if (iphi == (20 * i + 1) || iphi == 20 * i)
      myBool = true;
  }

  return myBool;
}

float ZeeCalibration::computeCoefficientDistanceAtIteration(float v1[250], float v2[250], int size) {
  float dist(0.);

  for (int i = 0; i < size; i++) {
    //    std::cout<< "[ZeeCalibration::computeCoefficientDistanceAtIteration] Adding term "<<pow( v1[i]-v2[i], 2 )<<" from v1 "<<v1[i]<<" and v2 "<<v2[i]<<std::endl;

    bool isNearCrack = false;

    if (calibMode_ == "RING") {  //exclude non-calibrated rings from computation

      isNearCrack = (abs(ringNumberCorrector(i)) == 1 || abs(ringNumberCorrector(i)) == 25 ||
                     abs(ringNumberCorrector(i)) == 26 || abs(ringNumberCorrector(i)) == 45 ||
                     abs(ringNumberCorrector(i)) == 46 || abs(ringNumberCorrector(i)) == 65 ||
                     abs(ringNumberCorrector(i)) == 66 || abs(ringNumberCorrector(i)) == 85 ||
                     abs(ringNumberCorrector(i)) == 86 || abs(ringNumberCorrector(i)) == 124);
    }

    if (!isNearCrack)
      dist += pow(v1[i] - v2[i], 2);
  }

  dist = sqrt(dist) / size;

  return dist;
}

void ZeeCalibration::resetVariables() {
  BBZN = 0;
  EBZN = 0;
  EEZN = 0;
  BBZN_gg = 0;
  EBZN_gg = 0;
  EEZN_gg = 0;

  BBZN_tt = 0;
  EBZN_tt = 0;
  EEZN_tt = 0;

  BBZN_t0 = 0;
  EBZN_t0 = 0;
  EEZN_t0 = 0;

  TOTAL_ELECTRONS_IN_BARREL = 0;
  TOTAL_ELECTRONS_IN_ENDCAP = 0;

  GOLDEN_ELECTRONS_IN_BARREL = 0;
  GOLDEN_ELECTRONS_IN_ENDCAP = 0;
  SILVER_ELECTRONS_IN_BARREL = 0;
  SILVER_ELECTRONS_IN_ENDCAP = 0;
  SHOWER_ELECTRONS_IN_BARREL = 0;
  SHOWER_ELECTRONS_IN_ENDCAP = 0;
  CRACK_ELECTRONS_IN_BARREL = 0;
  CRACK_ELECTRONS_IN_ENDCAP = 0;

  BARREL_ELECTRONS_BEFORE_BORDER_CUT = 0;
  BARREL_ELECTRONS_AFTER_BORDER_CUT = 0;

  return;
}

void ZeeCalibration::resetHistograms() {
  h1_eventsBeforeEWKSelection_->Reset();
  h1_eventsAfterEWKSelection_->Reset();

  h1_eventsBeforeBorderSelection_->Reset();
  h1_eventsAfterBorderSelection_->Reset();

  for (int i = 0; i < 2; i++) {
    h_eleEffEta_[i]->Reset();
    h_eleEffPhi_[i]->Reset();
    h_eleEffPt_[i]->Reset();
  }

  h1_seedOverSC_->Reset();
  h1_preshowerOverSC_->Reset();

  h1_eleEtaResol_->Reset();
  h1_elePhiResol_->Reset();

  h1_zMassResol_->Reset();

  h1_electronCosTheta_TK_->Reset();
  h1_electronCosTheta_SC_->Reset();
  h1_electronCosTheta_SC_TK_->Reset();

  h2_fEtaBarrelGood_->Reset();
  h2_fEtaBarrelBad_->Reset();
  h2_fEtaEndcapGood_->Reset();
  h2_fEtaEndcapBad_->Reset();
  h1_eleClasses_->Reset();

  h1_ZCandMult_->Reset();
  h1_reco_ZMass_->Reset();
  h1_reco_ZMassCorr_->Reset();
  h1_reco_ZMassCorrBB_->Reset();
  h1_reco_ZMassCorrEE_->Reset();
  h1_occupancyVsEta_->Reset();
  h1_occupancy_->Reset();
  h1_occupancyBarrel_->Reset();
  h1_occupancyEndcap_->Reset();

  return;
}

void ZeeCalibration::printStatistics() {
  std::cout << "[ CHECK ON BARREL ELECTRON NUMBER ]"
            << " first " << BARREL_ELECTRONS_BEFORE_BORDER_CUT << " second " << TOTAL_ELECTRONS_IN_BARREL << std::endl;

  std::cout << "[ EFFICIENCY OF THE BORDER SELECTION ]"
            << (float)BARREL_ELECTRONS_AFTER_BORDER_CUT / (float)BARREL_ELECTRONS_BEFORE_BORDER_CUT << std::endl;

  std::cout << "[ EFFICIENCY OF THE GOLDEN SELECTION ] BARREL: "
            << (float)GOLDEN_ELECTRONS_IN_BARREL / (float)TOTAL_ELECTRONS_IN_BARREL
            << " ENDCAP: " << (float)GOLDEN_ELECTRONS_IN_ENDCAP / (float)TOTAL_ELECTRONS_IN_ENDCAP << std::endl;

  std::cout << "[ EFFICIENCY OF THE SILVER SELECTION ] BARREL: "
            << (float)SILVER_ELECTRONS_IN_BARREL / (float)TOTAL_ELECTRONS_IN_BARREL
            << " ENDCAP: " << (float)SILVER_ELECTRONS_IN_ENDCAP / (float)TOTAL_ELECTRONS_IN_ENDCAP << std::endl;

  std::cout << "[ EFFICIENCY OF THE SHOWER SELECTION ] BARREL: "
            << (float)SHOWER_ELECTRONS_IN_BARREL / (float)TOTAL_ELECTRONS_IN_BARREL
            << " ENDCAP: " << (float)SHOWER_ELECTRONS_IN_ENDCAP / (float)TOTAL_ELECTRONS_IN_ENDCAP << std::endl;

  std::cout << "[ EFFICIENCY OF THE CRACK SELECTION ] BARREL: "
            << (float)CRACK_ELECTRONS_IN_BARREL / (float)TOTAL_ELECTRONS_IN_BARREL
            << " ENDCAP: " << (float)CRACK_ELECTRONS_IN_ENDCAP / (float)TOTAL_ELECTRONS_IN_ENDCAP << std::endl;

  std::ofstream fout("ZeeStatistics.txt");

  if (!fout) {
    std::cout << "Cannot open output file.\n";
  }

  fout << "ZeeStatistics" << std::endl;

  fout << "##########################RECO#########################" << std::endl;
  fout << "##################Zee with Barrel-Barrel electrons: " << BBZN << std::endl;

  fout << "Golden-Golden fraction: " << (float)BBZN_gg / BBZN << " 3-3 fraction is " << (float)BBZN_tt / BBZN
       << " 3-whatever fraction is " << (float)BBZN_t0 / BBZN << std::endl;
  fout << "##################Zee with Barrel-Endcap electrons: " << EBZN << std::endl;
  fout << "Golden-Golden fraction: " << (float)EBZN_gg / EBZN << " 3-3 fraction is " << (float)EBZN_tt / EBZN
       << " 3-whatever fraction is " << (float)EBZN_t0 / EBZN << std::endl;
  fout << "##################Zee with Endcap-Endcap electrons: " << EEZN << std::endl;
  fout << "Golden-Golden fraction: " << (float)EEZN_gg / EEZN << " 3-3 fraction is " << (float)EEZN_tt / EEZN
       << " 3-whatever fraction is " << (float)EEZN_t0 / EEZN << std::endl;

  fout << "\n" << std::endl;

  fout << "##########################GEN#########################" << std::endl;
  fout << "##################Zee with Barrel-Barrel electrons: " << (float)MCZBB / NEVT << std::endl;
  fout << "##################Zee with Barrel-Endcap electrons: " << (float)MCZEB / NEVT << std::endl;
  fout << "##################Zee with Endcap-Endcap electrons: " << (float)MCZEE / NEVT << std::endl;

  fout.close();
}