#!/usr/bin/env python3
#
# Copyright (C) 2011 Chad Hanna
# Copyright (C) 2019 Patrick Godwin
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

## @file
# This program makes a summary web page of a gstlal inspiral analysis.

import sys, os, glob, shutil, time
import re
import subprocess
import json

from optparse import OptionParser
from ligo.scald import report

ABOUT_URL = 'https://docs.google.com/document/d/12wJjCz8L1UczqRm86q3-EFnpnIZ2FHPSwKR_kym2L5g/pub?embedded=true'
SCHEDULE_URL = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vR1XwazhZYoVbMXFZCq_s2rlzyNwcF0xC4kyhnKrCeXFSWte-2jRodL590RU3PsoX4OVypYyAZ7Nl_8/pubhtml?widget=true&amp;headers=false'
IMAGE_URL = 'https://results.ligo.uwm.edu/~gstlalcbc/share/vis/gstlal.png'


def load_json(path):
	with open(path, 'r') as f:
		return json.loads(f.read())


def parse_command_line():
	parser = OptionParser(usage = "%prog [options] [file ...]", description = "%prog summary web page")
	parser.add_option("--webserver-dir", help = "Set the directory for the webserver.  Required.  Example /archive/home/channa/public_html/highmass_months_23-24_summary_page")
	parser.add_option("--open-box", action = "store_true", help = "Produce open box page")
	parser.add_option("--output-user-tag", action = "append", metavar = "name", help = "Set the basename for image search")
	parser.add_option("--title", default="gstlal_inspiral offline analysis")
	parser.add_option("--glob-path", help = "This is the path to search for images")

	opts, filenames = parser.parse_args()
	return opts, filenames


#
# Setup
#

opts, files = parse_command_line()

thisreport = report.Report('gstlal analysis', image=IMAGE_URL)

try:
	os.makedirs(opts.webserver_dir)
except OSError:
	pass
try:
	os.makedirs(opts.webserver_dir+'_lite')
except OSError:
	pass


#
# Add the page tabs
#


summary = report.Tab('Summary')
injparams = report.Tab('Injection Parameters')
injrecovery = report.Tab('Injection Recovery')
sens = report.Tab('Search Sensitivity')
back = report.Tab('Background')
money = report.Tab('Money Plots')
about_doc = report.Tab('About', url=ABOUT_URL)
sched_doc = report.Tab('Schedule', url=SCHEDULE_URL)


#
# Add summary page content to the summary page tab
#

summary += report.Header('Summary')

tabledata = load_json(os.path.join(opts.glob_path, '%s_plot_summary.json' % opts.output_user_tag[0]))
summary += report.Table('Search Summary').save(tabledata, opts.webserver_dir)

tabledata = load_json(os.path.join(opts.glob_path, '%s_segment_table.json' % opts.output_user_tag[0]))
summary += report.Table('Segments').save(tabledata, opts.webserver_dir)

summary += report.Description("This page was generated on %s by %s in the working directory: %s" % (time.strftime("%Y-%m-%d %H:%M"), os.environ["USER"], os.environ["PWD"]))

thisreport += summary

#
# Add injection parameter content
#

injparams += report.Header('Injection Parameters')
injparams += report.Description("Injections are the addition of simulated signals into the gravitational wave strain data.  They are useful for diagnosing the pipeline and measuring the sensitivity.  Care is taken to ensure that the input distribution is sensible.  The remaining sections describe the input distributions for the injections.  They are not necessarily what is analyzed since the analyzed segments are not used for determining the injection sets (i.e. injections may be scheduled for times when a detector is not even functioning).")
injparams += report.Description("The following plots are typically produced by injection waveform type.  Several injection runs of the same waveform (with different random seeds) are often done.  Here all runs of the same waveform type are shown together.")

imgfooter = "Above are the injected mass parameters for the simulations done.  Typically injections are done uniformally in component mass unless the waveform approximant cannot support certain mass ratios."
injparams += report.ImageGrid("Injected Parameters (m1 and m2)", grid_size=2, footer=imgfooter).glob(os.path.join(opts.glob_path, '*6_sim_dist_m1_m2*.png'))

imgfooter = "Unless doing a directed search injections are uniform in time.  Although the correct distance distribution would be uniform in volume typically logarithmic injections are done"
injparams += report.ImageGrid("Injected Parameters time and distance", grid_size=2, footer=imgfooter).glob(os.path.join(opts.glob_path, '*6_sim_dist_time_distance*.png'))

imgfooter = "Unless doing a directed search injections are uniform on the sky."
injparams += report.ImageGrid("Injected Parameters RA and DEC", grid_size=2, footer=imgfooter).glob(os.path.join(opts.glob_path, '*6_sim_dist_ra_dec*.png'))

imgfooter = "Unless doing a directed search injections are uniform in sin(inclination) and polarizations."
injparams += report.ImageGrid("Injected Parameters inclination and polarization", grid_size=2, footer=imgfooter).glob(os.path.join(opts.glob_path, '*6_sim_dist_inc_pol*.png'))

imgfooter = "The Z component spins of the injection set.  Often injections are done without spin, so don't be surprised if these are zero."
injparams += report.ImageGrid("Injected Parameters Z component spin", grid_size=2, footer=imgfooter).glob(os.path.join(opts.glob_path, '*6_sim_dist_spin1z_spin2z*.png'))

thisreport += injparams

#
# Add injection accuracy content
#

injrecovery += report.Header("Injection Accuracy")
injrecovery += report.Description("The accuracy of recovered parameters aids at diagnosing the performance of the pipeline as well as hinting at the possibility of measuring certain parameters.  Mass parameters for the low mass search are often recovered better than mass parameters for the high mass search.")

injrecovery += report.ImageGrid("Mchirp Parameter Accuracy", grid_size=3, footer="Accuracy of chirp mass").glob(os.path.join(opts.glob_path, '*2_mchirp_acc_frac_*.png'))

injrecovery += report.ImageGrid("Eta Parameter Accuracy", grid_size=3, footer="Accuracy of eta").glob(os.path.join(opts.glob_path, '*2_eta_acc_frac_*.png'))

injrecovery += report.ImageGrid("Total Mass Parameter Accuracy", grid_size=3, footer="Accuracy of total mass").glob(os.path.join(opts.glob_path, '*2_mtotal_acc_frac_*.png'))

injrecovery += report.ImageGrid("Time Parameter Accuracy", grid_size=3, footer="Accuracy of time").glob(os.path.join(opts.glob_path, '*2_t_acc_*.png'))

injrecovery += report.ImageGrid("Effective Spin Accuracy", grid_size=3, footer="Accuracy of mass-weighted spin").glob(os.path.join(opts.glob_path, '*2_chi_acc_scatter*.png'))

injrecovery += report.ImageGrid("SNR Recovery", grid_size=3, footer="Injected expected SNR vs recovered SNR").glob(os.path.join(opts.glob_path, '*2_snr_*.png'))

imgfooter = "This is the distance at which you should see a 1.4 1.4 Msun binary at SNR 8. The first panel shows the time evolution of the horizon distance and the second panel shows the same information in histogram form."
injrecovery += report.ImageGrid("Horizon distance", grid_size=1, footer=imgfooter).glob(os.path.join(opts.glob_path, '*HORIZON*.png'))

#
# Add injection missed / found content
#

injrecovery += report.Header("Injection Missed/Found")
injrecovery += report.Description("""Measuring the found and missed injections as a function of various parameters aids in diagnosing the pipeline as well as providing the expected sensitivity of the pipeline to real signals.  The plots in this section show the missed and found injections as a for the various IFO times for coincident triggers. We allow double coincident events so some categories can have multiple types of found injections (for  example H1L1 and H1H2L1 triggers in H1H2L1 time).  Because of ambiguity concerning the time of an injection and the injection window it is occasionally possible to find an injection in more detectors than what the "time" refers to.  For example, an injection's geocentric end time might be in H1L1 time but that might occur near a boundary where H2 was also on.  Thus one could find an H1L1 injection in H1H2L1 time.""")

injrecovery += report.Header("Found / Missed Summary Table")
for tag in opts.output_user_tag:
	tabledata = load_json(os.path.join(opts.glob_path, '%s_injection_summary.json' % tag))
	injrecovery += report.Description("Summary of missed and found injections broken up by detector time for %s" % tag)
	injrecovery += report.Table('Injection Summary Table for %s' % tag).save(tabledata, opts.webserver_dir)

injrecovery += report.Header('Found / Missed Plots')
for tag in opts.output_user_tag:
	visible = 'ALL_LLOID_COMBINED' in tag

	plots = os.path.join(opts.glob_path, '*%s*1_d_vs_mchirp_*.png' % tag)
	imgfooter = "Distance of found and missed injections as a function of chirp mass: %s" % tag
	injrecovery += report.ImageGrid("Distance vs. chirp mass: %s" % tag, grid_size=2, footer=imgfooter, visible=visible).glob(plots)

	plots = os.path.join(opts.glob_path, '*%s*1_deff_vs_mchirp_*.png' % tag)
	imgfooter = "Effective distance of found and missed injections as a function of chirp mass: %s" % tag
	injrecovery += report.ImageGrid("Effective distance vs. chirp mass: %s" % tag, grid_size=2, footer=imgfooter, visible=visible).glob(plots)

	plots = os.path.join(opts.glob_path, '*%s*1_chirpdist_vs_mchirp_*.png' % tag)
	imgfooter = "Chirp distance of found and missed injections as a function of chirp mass.  For low mass systems the chirp mass scales out of the expected amplitude.  The chirp distance utilizes this and rescales the distance to be appropriate for a NS-NS binary.  At low total mass the missed/found barrier should be flat on this plot: %s" % tag
	injrecovery += report.ImageGrid("Chirp distance vs. chirp mass: %s" % tag, grid_size=2, footer=imgfooter, visible=visible).glob(plots)

injrecovery += report.Header("Found / Missed Total Mass")
for tag in opts.output_user_tag:
	visible = 'ALL_LLOID_COMBINED' in tag
	plots = os.path.join(opts.glob_path, '%s*1_deff_vs_mtotal_*.png' % tag)
	imgfooter = "Effective distance of found and missed injections as a function of total mass: %s" % tag
	injrecovery += report.ImageGrid("Effective distance vs. total mass: %s" % tag, grid_size=2, footer=imgfooter, visible=visible).glob(plots)

injrecovery += report.Header("Found / Missed Eta")
for tag in opts.output_user_tag:
	visible = 'ALL_LLOID_COMBINED' in tag
	plots = os.path.join(opts.glob_path, '*%s*1_chirpdist_vs_eta_*.png' % tag)
	imgfooter = "Effective distance of found and missed injections as a function of symmetric mass ratio eta: %s" % tag
	injrecovery += report.ImageGrid("Effective distance vs. eta: %s" % tag, grid_size=2, footer=imgfooter, visible=visible).glob(plots)

injrecovery += report.Header("Found / Missed Time")
for tag in opts.output_user_tag:
	visible = 'ALL_LLOID_COMBINED' in tag
	plots = os.path.join(opts.glob_path, '*%s*1_deff_vs_t_*.png' % tag)
	imgfooter = "Effective distance of found and missed injections as a function of time: %s" % tag
	injrecovery += report.ImageGrid("Effective distance vs. time: %s" % tag, grid_size=2, footer=imgfooter, visible=visible).glob(plots)

injrecovery += report.Header("Found / Missed Spin")
for tag in opts.output_user_tag:
	visible = 'ALL_LLOID_COMBINED' in tag
	plots = os.path.join(opts.glob_path, '*%s*1_deff_vs_chi_*.png' % tag)
	imgfooter = "Effective distance of found and missed injections as a function of mass-weighted spin: %s" % tag
	injrecovery += report.ImageGrid("Effective distance vs. mass-weighted spin: %s" % tag, grid_size=2, footer=imgfooter, visible=visible).glob(plots)

injrecovery += report.Header("Found / Missed Expected SNR")
for tag in opts.output_user_tag:
	visible = 'ALL_LLOID_COMBINED' in tag

	plots = os.path.join(opts.glob_path, '*%s*1_dec_expsnr_vs_mchirp_*.png' % tag)
	imgfooter = "Expected SNR of found and missed injections as a function of chirp mass: %s" % tag
	injrecovery += report.ImageGrid("Expected SNR vs. chirp mass: %s" % tag, grid_size=2, footer=imgfooter, visible=visible).glob(plots)

	plots = os.path.join(opts.glob_path, '*%s*1_dec_expsnr_vs_mtotal_*.png' % tag)
	imgfooter = "Expected SNR of found and missed injections as a function of total mass: %s" % tag
	injrecovery += report.ImageGrid("Expected SNR vs. total mass: %s" % tag, grid_size=2, footer=imgfooter, visible=visible).glob(plots)

	plots = os.path.join(opts.glob_path, '*%s*1_dec_expsnr_vs_eta_*.png' % tag)
	imgfooter = "Expected SNR of found and missed injections as a function of symmetric mass ratio eta: %s" % tag
	injrecovery += report.ImageGrid("Expected SNR vs. eta: %s" % tag, grid_size=2, footer=imgfooter, visible=visible).glob(plots)

	plots = os.path.join(opts.glob_path, '*%s*1_dec_expsnr_vs_cgi_*.png' % tag)
	imgfooter = "Expected SNR of found and missed injections as a function of mass-weighted spin: %s" % tag
	injrecovery += report.ImageGrid("Expected SNR vs. mass-weighted spin: %s" % tag, grid_size=2, footer=imgfooter, visible=visible).glob(plots)

	plots = os.path.join(opts.glob_path, '*%s*1_dec_expsnr_vs_t_*.png' % tag)
	imgfooter = "Expected SNR of found and missed injections as a function of time: %s" % tag
	injrecovery += report.ImageGrid("Expected SNR vs. time: %s" % tag, grid_size=2, footer=imgfooter, visible=visible).glob(plots)

injrecovery += report.Header("Missed Table")
for tag in opts.output_user_tag:
	tabledata = load_json(os.path.join(opts.glob_path, '%s_missed_summary.json' % tag))
	injrecovery += report.Table('Missed Injection Table for %s' % tag).save(tabledata, opts.webserver_dir)

thisreport += injrecovery

#
# Add sensitivity content
#

sens += report.Header('Sensitivity')

sens += report.Description("""This page shows plots that characterize the overall sensitivity of the search. The detection rate is directly proportional to the observed sensitive volume, which is a function of the significance threshold used to identify candidates. These plots are useful for determining how sensitive the search was to the input injection population. Since the search sensitivity is a strong function of the intrinsic parameters of the target source, we break down the sensitive into bins of these parameters. Here we show the sensitivity as a function of source type: BNS mchirp between 0.8 and 2, NSBH between 2 and 4.5, BBH between 4.5 and 45.0, IMBH between 45.0 and 450.0""")

for tag in opts.output_user_tag:
	visible = 'ALL_LLOID_COMBINED' in tag
	plots = os.path.join(opts.glob_path, '*%s*_BINNED_BY_SOURCE_TYPE*.png' % tag)
	imgfooter = "Binned by source type"
	sens += report.ImageGrid("Sensitive volume (V*T) and mean sensitive distance: %s" % tag, grid_size=3, footer=imgfooter, visible=visible).glob(plots)

thisreport += sens

#
# Add background content
#

back += report.Header('Background')
back += report.Description("This page shows the ingredients that go into ranking events and determining the False alarm probability.")

imgfooter = "Single detector triggers coincident in time-shifted analyses."
back += report.ImageGrid("Background Triggers", grid_size=3, footer=imgfooter).glob(os.path.join(opts.glob_path, '*3_bgparams_*_vs_snr*.png'))
back += report.ImageGrid("SNR Ratios", grid_size=3, footer=imgfooter).glob(os.path.join(opts.glob_path, '*SNR_PDF*.png'))
back += report.ImageGrid("Rates", grid_size=3, footer=imgfooter).glob(os.path.join(opts.glob_path, '*RATES*.png'))

back += report.Header("SNR and chi-squared")
back += report.ImageGrid("Single Detector Background SNR-chisq Distributions", grid_size=3).glob(os.path.join(opts.glob_path, '*BACKGROUND_PDF_SNRCHI2*.png'))
back += report.ImageGrid("Single Detector Signal Chisq (Conditional) Distributions", grid_size=3).glob(os.path.join(opts.glob_path, '*INJECTION_PDF_SNRCHI2*.png'))
back += report.ImageGrid("Single Detector Likelihood Ratios", grid_size=3).glob(os.path.join(opts.glob_path, '*LR_SNRCHI2*.png'))
if opts.open_box:
	back += report.ImageGrid("Single Detector Signal Chisq (Conditional) Distributions: Zero lag", grid_size=3).glob(os.path.join(opts.glob_path, '*ZERO_LAG_PDF_SNRCHI2*.png'))

#
# Add chisq content
#

back += report.Description("The chi-squared test checks that the snr accumulated matches expectation.")

imgfooter = "Chi-squared vs snr for single detectors after coincidence.  Blue points are full data zero lag, red are software injections and black are time slides."
back += report.ImageGrid("Chi-squared Distributions", grid_size=3, footer=imgfooter).glob(os.path.join(opts.glob_path, '*3_chi2_vs_rho_*closedbox*.png'))

imgfooter = "Comparison of SNR in pairs of detectors."
back += report.ImageGrid("Signal-to-Noise Ratio", grid_size=3, footer=imgfooter).glob(os.path.join(opts.glob_path, '*4_rho_*_vs_*closedbox*.png'))

imgfooter = "Comparison of effective distance in pairs of detectors."
back += report.ImageGrid("Effective Distance", grid_size=3, footer=imgfooter).glob(os.path.join(opts.glob_path, '*4_deff_*_vs_*closedbox*.png'))

if opts.open_box:
	back += report.Header('Open Box Results')

	imgfooter = "Chi-squared vs snr for single detectors after coincidence.  Blue points are full data zero lag, red are software injections and black are time slides."
	back += report.ImageGrid("Chi-squared Distributions: Zero lag", grid_size=3, footer=imgfooter).glob(os.path.join(opts.glob_path, '*3_chi2_vs_rho_*openbox*.png'))

	imgfooter = "Comparison of SNR in pairs of detectors."
	back += report.ImageGrid("Signal-to-Noise Ratio: Zero lag", grid_size=3, footer=imgfooter).glob(os.path.join(opts.glob_path, '*4_rho_*_vs_*openbox*.png'))

	imgfooter = "Comparison of effective distance in pairs of detectors."
	back += report.ImageGrid("Effective Distance", grid_size=3, footer=imgfooter).glob(os.path.join(opts.glob_path, '*4_deff_*_vs_*openbox*.png'))

thisreport += back

#
# Add results content
#

money += report.Header('Money Plots')
money += report.Description("This section provides the detection statistic plots and a summary of the loudest event.")

money += report.Header('Closed Box Results')
imgfooter = "Comparison of single time slide event rate to event rate expected from background as a function of threshold."
money += report.ImageGrid("Rate vs. Threshold", grid_size=3, footer=imgfooter).glob(os.path.join(opts.glob_path, '*5_count_vs_*_closedbox*.png'))

tabledata = load_json(os.path.join(opts.glob_path, '%sbgsummary_table.json' % opts.output_user_tag[0]))
money += report.Table('Closed Box Summary Table').save(tabledata, opts.webserver_dir)

if opts.open_box:
	money += report.Header('Open Box Results')
	imgfooter = "Comparison of single time slide event rate to event rate expected from background as a function of threshold."
	money += report.ImageGrid("Rate vs. Threshold", grid_size=3, footer=imgfooter).glob(os.path.join(opts.glob_path, '*5_count_vs_*_openbox*.png'))
	
	tabledata = load_json(os.path.join(opts.glob_path, '%ssummary_table.json' % opts.output_user_tag[0]))
	money += report.Table('Open Box Summary Table').save(tabledata, opts.webserver_dir)

thisreport += money

#
# Add search documentation
#

thisreport += about_doc
thisreport += sched_doc

#
# write the result
#

thisreport.save(opts.webserver_dir)

#
# set up a lite version of the summary page
#

reportlite = report.Report('gstlal analysis', image=IMAGE_URL)

summary = report.Tab('Summary')
about_doc = report.Tab('About', url=ABOUT_URL)
sched_doc = report.Tab('Schedule', url=SCHEDULE_URL)

#
# Summary lite setup
#

summary += report.Header('Summary')

tabledata = load_json(os.path.join(opts.glob_path, '%s_plot_summary.json' % opts.output_user_tag[0]))
summary += report.Table('Search Summary').save(tabledata, opts.webserver_dir+'_lite')

## Include horizon distance plots
imgfooter = "This is the distance at which you should see a 1.4 1.4 Msun binary at SNR 8. The first panel shows the time evolution of the horizon distance and the second panel shows the same information in histogram form."
summary += report.ImageGrid("Horizon distance", grid_size=1, footer=imgfooter).glob(os.path.join(opts.glob_path, '*HORIZON*.png'))

## Include found/missed as function of decisive characteristic SNR
summary += report.Header("Found / Missed Expected SNR")
summary += report.Description("""Measuring the found and missed injections as a function of various parameters aids in diagnosing the pipeline as well as providing the expected sensitivity of the pipeline to real signals.  The plots in this section show the missed and found injections for the various IFO times for coincident triggers.""")

tabledata = load_json(os.path.join(opts.glob_path, '%s_injection_summary.json' % opts.output_user_tag[0]))
footer = "Summary of missed and found injections broken up by detector time for %s" % opts.output_user_tag[0]
summary += report.Table('Injection Summary Table', footer=footer).save(tabledata, opts.webserver_dir+'_lite')

plots = os.path.join(opts.glob_path, '*%s*1_dec_expsnr_vs_mchirp_*.png' % opts.output_user_tag[0])
imgfooter = "Expected SNR of found and missed injections as a function of chirp mass: %s" % opts.output_user_tag[0]
summary += report.ImageGrid("Expected SNR vs. chirp mass", grid_size=4, footer=imgfooter).glob(plots)

## Include missed injection table
summary += report.Header("Missed Table")
tabledata = load_json(os.path.join(opts.glob_path, '%s_missed_summary.json' % opts.output_user_tag[0]))
summary += report.Table('Missed Injection Table for %s' % opts.output_user_tag[0]).save(tabledata, opts.webserver_dir+'_lite')

## Include search sensitivity binned by source type
summary += report.Header('Search Sensitivity')
summary += report.Description("""These plots characterize the overall sensitivity of the search. The detection rate is directly proportional to the observed sensitive volume, which is a function of the significance threshold used to identify candidates. These plots are useful for determining how sensitive the search was to the input injection population. Here we show the sensitivity as a function of source type: BNS mchirp between 0.8 and 2, NSBH between 2 and 4.5, BBH between 4.5 and 45.0, IMBH between 45.0 and 450.0""")

plots = os.path.join(opts.glob_path, '*%s*_BINNED_BY_SOURCE_TYPE*.png' % opts.output_user_tag[0])
imgfooter = "Binned by source type"
summary += report.ImageGrid("Sensitive volume (V*T) and mean sensitive distance: %s" % opts.output_user_tag[0], grid_size=4, footer=imgfooter, visible=False).glob(plots)

## Include FAP estimation plots
summary += report.Header("SNR and chi-squared")
summary += report.ImageGrid("Single Detector Background SNR-chisq Distributions", grid_size=4).glob(os.path.join(opts.glob_path, '*BACKGROUND_PDF_SNRCHI2*.png'))
summary += report.ImageGrid("Single Detector Signal Chisq (Conditional) Distributions", grid_size=4).glob(os.path.join(opts.glob_path, '*INJECTION_PDF_SNRCHI2*.png'))
if opts.open_box:
	summary += report.ImageGrid("Single Detector Signal Chisq (Conditional) Distributions: Zero lag", grid_size=4).glob(os.path.join(opts.glob_path, '*ZERO_LAG_PDF_SNRCHI2*.png'))

## Include Chi-square distribution plots
summary += report.Header("Chi-squared Distributions")
summary += report.Description("The chi-squared test checks that the snr accumulated matches expectation.")

imgfooter = "Chi-squared vs snr for single detectors after coincidence.  Blue points are full data zero lag, red are software injections and black are time slides."
summary += report.ImageGrid("Chi-squared Distributions", grid_size=3, footer=imgfooter).glob(os.path.join(opts.glob_path, '*3_chi2_vs_rho_*closedbox*.png'))
if opts.open_box:
	summary += report.ImageGrid("Chi-squared Distributions: Zero lag", grid_size=3, footer=imgfooter).glob(os.path.join(opts.glob_path, '*3_chi2_vs_rho_*openbox*.png'))

## Include IFAR, lnL plots + summary table
summary += report.Header('Money Plots')
summary += report.Description("This section provides the detection statistic plots and a summary of the loudest event.")

imgfooter = "Comparison of single time slide event rate to event rate expected from background as a function of threshold."
summary += report.ImageGrid("Rate vs. Threshold", grid_size=3, footer=imgfooter).glob(os.path.join(opts.glob_path, '*5_count_vs_*_closedbox*.png'))

tabledata = load_json(os.path.join(opts.glob_path, '%sbgsummary_table.json' % opts.output_user_tag[0]))
summary += report.Table('Closed Box Summary Table').save(tabledata, opts.webserver_dir+'_lite')

if opts.open_box:
	imgfooter = "Comparison of single time slide event rate to event rate expected from background as a function of threshold."
	summary += report.ImageGrid("Rate vs. Threshold: Zero lag", grid_size=3, footer=imgfooter).glob(os.path.join(opts.glob_path, '*5_count_vs_*_openbox*.png'))
	
	tabledata = load_json(os.path.join(opts.glob_path, '%ssummary_table.json' % opts.output_user_tag[0]))
	summary += report.Table('Open Box Summary Table').save(tabledata, opts.webserver_dir+'_lite')

reportlite += summary

#
# Add search documentation
#

reportlite += about_doc
reportlite += sched_doc

#
# write the result
#

reportlite.save(opts.webserver_dir + "_lite", config_name='report_lite')
