#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Quantify peak intensities
#
# Copyright © 2015-2020 Deutsches Elektronen-Synchrotron DESY,
#                       a research centre of the Helmholtz Association.
#
# Author:
#    2015-2017 Thomas White <taw@physics.org>
#

import sys
import os
import re

f = open(sys.argv[1], 'r')

prog1 = re.compile("^\s*[\d\-\.]+\s+[\d\-\.]+\s+[\d\-\.]+\s+([\d\-\.]+)\s+.+$")

n_peaks = 0
n_patt = 0
total_intens = 0.0

while True:

    fline = f.readline()
    if not fline:
        break

    if fline == '----- Begin chunk -----\n':
        n_patt += 1

    match = prog1.match(fline)
    if match:
        intens = float(match.group(1))
        total_intens += intens
        n_peaks += 1


f.close()

print('{} patterns, %i peaks'.format(n_patt,n_peaks))
print('Mean {:.2f} peaks per pattern'.format(n_peaks/float(n_patt)))
print('Mean {:.2f} ADU per peak'.format(total_intens/float(n_peaks)))
print('Mean {:.2f} ADU total per pattern'.format(total_intens/n_patt))

