#!/usr/bin/env python3 -i
"""
Project histograms from ROOT TH2 gamma-gamma matrix, using pyROOT

Usage:
  project_gg.py -f INPUT_FILE -e E
  project_gg.py -h | --help

Options:
  -h --help         Show this screen.
  -f INPUT_FILE     ROOT input file containing the gamma-gamma matrix
  -e --egate=<gate>  Gate energy [default: 0].
"""

from docopt import docopt  # For command-line argument parsing
from ROOT import TCanvas, TFile, gPad  # pyROOT libraries

def project(energy_gate):
    """
    function to handle the projection of the gamma-gamma matrix.
    Args:
        energy_gate (float): The energy gate to project around.
    """

    # Find the bin corresponding to the given energy gate
    bin = matrix.GetXaxis().FindBin(energy_gate)

    # Project the 2D matrix onto the X-axis for the specified bin range
    h1 = matrix.ProjectionX("_px", bin, bin)

    # Draw the resulting histogram on the canvas
    h1.Draw()

    # Update the canvas to display the histogram
    gPad.Update()

if __name__ == "__main__":
    """
    Entry point of the script. Parses command-line arguments and initializes
    ROOT objects before calling the main function.
    """
    # Parse command-line arguments using docopt
    arguments = docopt(__doc__)
    input_file_name = arguments['-f']  # Path to the ROOT file
    energy_gate = float(arguments['--egate'])  # Convert energy gate to float

    # Initialize the ROOT canvas
    canvas = TCanvas('canvas', 'my canvas')  # Create the canvas globally

    # Open the ROOT file in read mode
    fin = TFile(input_file_name, "READ")

    # Retrieve the gg_matrix from the ROOT file
    matrix_name = "gg_matrix"
    matrix = fin.Get(matrix_name)
    if not matrix:
        raise ValueError(f"The matrix {matrix_name} was not found in the file {input_file_name}.")

    # Call the project function to process the input
    project(energy_gate)