#!/usr/bin/env python
"""
Pastes a stamp image back into a larger image from which it was cut. Stamp image
must contain the STAMPSLC keyword in the FITS header, a Numpy-like [Y,X] slice
representing the area of the original image to be pasted into.
Additional keyword arguments can be supplied in -<keyword> <value> format. See
the docstring for fitsstamp.paste_stamps for additional information.
Understood keyword arguments:
{0}

Examples:
fitsstamp_paste target_image.fits stamp1.fits stamp2.fits stamp3.fits
fitsstamp_paste target_image.fits stamp.fits -target_ext SCI
To overwrite target_image.fits instead of creating a new file:
fitsstamp_paste target_image.fits stamp.fits -output_name target_image.fits
"""

import fitsstamp
import sys
import textwrap
from inspect import getargspec
from ast import literal_eval


def print_doc():
    arg_names, _args, _kw, arg_vals = getargspec(fitsstamp.paste_stamps)
    arg_names = arg_names[-len(arg_vals):]
    arg_list = ', '.join(['-'+nm for nm in arg_names])
    arg_list = '\n'.join(textwrap.wrap(arg_list, 80))
    print(__doc__.format(arg_list))

if __name__ == '__main__':
    # Process command line arguments to be passed to cut_stamps function
    cl_args = dict()
    arg_names = getargspec(fitsstamp.paste_stamps)[0]
    for arg_name in arg_names:
        try:
            arg_ind = sys.argv.index('-'+arg_name)
        except ValueError:
            continue
        try:
            cl_args[arg_name] = sys.argv[arg_ind+1]
            del sys.argv[arg_ind:arg_ind+2]
        except IndexError:
            print_doc()
            exit(1)
        # convert ints, floats, bool etc. to python literals. Bare string
        # (without additional quotes) will raise ValueError and remain unchanged
        try:
            cl_args[arg_name] = literal_eval(cl_args[arg_name])
        except (ValueError, SyntaxError):
            pass

    try:
        orig_img = sys.argv[1]
        stamp_imgs = sys.argv[2:]
    except IndexError:
        print_doc()
        exit(1)

    pasted = fitsstamp.paste_stamps(orig_img, stamp_imgs, **cl_args)
    print('Pasted {0:d} stamps into {1}'.format(len(stamp_imgs), pasted))
