#!/usr/bin/env python3

import os
import sys
import astropy.io.fits as pyfits
import numpy


if __name__ == "__main__":

    in_fn = sys.argv[1]
    ref_fn = sys.argv[2]
    parameter_fn = sys.argv[3]
    out_fn = sys.argv[4]

    # open fits images
    in_hdu = pyfits.open(in_fn)
    ref_hdu = pyfits.open(ref_fn)

    # open fit parameter and get the fitting region
    xmin = ymin = None
    with open(parameter_fn, "r") as pf:
        lines = [l.strip() for l in pf.readlines()]
        for line in lines:
            if line.startswith("H)"):
                # this is the line we need
                items = line.split("H)")[1].split()
                xmin = int(items[0])
                ymin = int(items[2])
                break

    if (xmin is None):
        print("Can't find image region from file %s" % (parameter_fn))
        sys.exit(0)
    print(xmin,ymin)
    
    # now copy the wcs info from reference to input file
    for key in ['CTYPE1', 'CTYPE2',
                'CD1_1', 'CD1_2', 'CD2_1', 'CD2_2',
                'CRVAL1', 'CRVAL2',
                'CRPIX1', 'CRPIX2']:
        in_hdu[0].header[key] = ref_hdu['SCI'].header[key]

    # now account for the position of the cutout
    in_hdu[0].header['CRPIX1'] -= xmin
    in_hdu[0].header['CRPIX2'] -= ymin

    in_hdu.writeto(out_fn, overwrite=True)
    
