#!/usr/bin/env cctbx.python

import sys
from cctbx import sgtbx

syminfo_path = sys.argv[1]

def parse_syminfo(path):
    data = {}
    number = None
    with open(path) as f:
        for line in f:
            line = line.strip()
            if line == 'begin_spacegroup':
                assert number is None, line
            elif line == 'end_spacegroup':
                assert number is not None
                assert number in data
                number = None
            elif line.startswith('number '):
                number = int(line[6:])
            elif line.startswith('hklasu ccp4 '):
                asu = line[12:].strip("'").replace('==', '=')
                assert number is not None
                if number in data:
                    assert data[number] == asu
                else:
                    data[number] = asu
    assert len(data) == 230
    return data

hklasu_strings = [
    'l>0 or (l=0 and (h>0 or (h=0 and k>=0)))',
    'k>=0 and (l>0 or (l=0 and h>=0))',
    'h>=0 and k>=0 and l>=0',
    'l>=0 and ((h>=0 and k>0) or (h=0 and k=0))',
    'h>=k and k>=0 and l>=0',
    '(h>=0 and k>0) or (h=0 and k=0 and l>=0)',
    'h>=k and k>=0 and (k>0 or l>=0)',
    'h>=k and k>=0 and (h>k or l>=0)',
    'h>=0 and ((l>=h and k>h) or (l=h and k=h))',
    'k>=l and l>=h and h>=0',
]

def compare_ccp4_and_sgtbx(syminfo_data):
    for s in sgtbx.space_group_symbol_iterator():
        sg = sgtbx.space_group(s.hall())
        sg_type = sgtbx.space_group_type(sg)
        asu = sgtbx.reciprocal_space_asu(sg_type)
        sgtbx_hklasu = asu.reference_as_string().replace('==', '=')
        ccp4_hklasu = syminfo_data[s.number()]
        assert sgtbx_hklasu == ccp4_hklasu
        assert sgtbx_hklasu in hklasu_strings

def main():
    syminfo_data = parse_syminfo(syminfo_path)
    compare_ccp4_and_sgtbx(syminfo_data)
    print('// This table was generated by tools/gen_reciprocal_asu.py.')
    indices = []
    for n in range(1, 231):
        asu_str = syminfo_data[n]
        idx = hklasu_strings.index(asu_str)
        indices.append(str(idx))
    print(', '.join(indices))

main()
