#!python3

import sys
from pysat.formula import CNF
import argparse
import pathlib as pl
import bz2

def main():
    f_ext= CNF(from_fp=sys.stdin)
    
    instance_dir = pl.Path(parse_args())

    instance, core_nr = parse_header(f_ext.comments[0])

    ipath = instance_dir / (instance + ".cnf.bz2")

    f = CNF(ipath)    

    f.extend(f_ext)
    f.comments = []

    f.to_fp(sys.stdout,
            comments=["c extension_of:{} nr:{}".format(instance, core_nr)])

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--instance_dir",
                        type=str,
                        default="./instances",
                        help="path to the directoy containing all instances")

    args = parser.parse_args()

    return args.instance_dir
def parse_header(header):
    tokens = header.split(' ')[1:]

    return tokens[0].split(':')[1], int(tokens[1].split(':')[1])
    
if __name__ == "__main__":
    main()
