#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Find pairs of observations from the same pattern
#
# Copyright © 2014-2020 Deutsches Elektronen-Synchrotron DESY,
#                       a research centre of the Helmholtz Association.
#
# Author:
#    2014-2017 Thomas White <taw@physics.org>
#

import re as regexp

fn1 = "test-0.5.0-satfix.stream"
fn2 = "test-curr.stream"

def find_405(f):
    lines = dict()
    fn = ""
    prog = regexp.compile("^\s+([\d-]+)\s+([\d-]+)\s+([\d-]+)\s+")
    while True:
        fline = f.readline()
        if not fline:
            break
        if fline.find("Image filename: ") != -1:
            fn = fline.split(': ')[1].rstrip("\r\n")
            continue
        match = prog.match(fline)
        if not match:
            continue
        h = int(match.group(1))
        k = int(match.group(2))
        l = int(match.group(3))
        if (h==0) and (k==0) and (l==6):
            lines[fn] = fline
        if (h==0) and (k==0) and (l==-6):
            lines[fn] = fline
    return lines

f = open(fn1, 'r')
flines = find_405(f)
print("{} measurements in {}".format(len(flines),fn1))

g = open(fn2, 'r')
glines = find_405(g)
print("{} measurements in {}".format(len(glines),fn2))

print("\nThe common measurements:\n")
for fn in flines.keys():
    if fn in glines:
        print(fn)
        print(flines[fn].rstrip("\r\n"))
        print(glines[fn])
        print()
        del flines[fn]
        del glines[fn]

print("\nThe measurements only in {}:\n".format(fn1))

for fn in flines.keys():
    print(fn)
    print(flines[fn].rstrip("\r\n"))
    print()

print("\nThe measurements only in {}:\n".format(fn2))

for fn in glines.keys():
    print(fn)
    print(glines[fn].rstrip("\r\n"))
    print("")

