#! /usr/bin/env python
#
#
#  A word of caution about masking here:
#  - the fits file needs NaN for masking to work
#  - a numpy    mask = True (1) means the data is bad
#  - in MIRIAD  mask = 1 means the data is good !! 
#  - in CASA    mask = True means ....

import sys
import numpy as np    
import numpy.ma as ma
from astropy.io import fits

#   simple usage
if len(sys.argv) < 4:
    print("Usage: %s file1 file2 file3" % sys.argv[0])
    print("    Takes data from file1 if valid, if invalid, use data from file2")
    print("    write to file3. All files need to be fits image files with 1 extension")
    sys.exit(0)

#   parse command line args
file1 = sys.argv[1]
file2 = sys.argv[2]
file3 = sys.argv[3]

#    get the first file, set the mask (mask=True means data is bad)
hdu1 = fits.open(file1)
data1 = hdu1[0].data
mask1 = ma.masked_array(data1, np.isnan(data1))

#    get the replacement file in case the first is masked
hdu2 = fits.open(file2)
data2 = hdu2[0].data

#    compute the merging of data1 and data2
data3 = np.where(mask1,data2,data1)

#    write out
fits.writeto(file3, data3, hdu1[0].header)
