#!/usr/bin/python

# Convert a png image to a fits image

import os
import sys
import numpy as np
import pyfits
import scipy
import scipy.misc
from time import gmtime, strftime  # for utc

if len(sys.argv) == 1:
  print " "
  print "Usage: fits_from_png.py infile.png outfile.fits "
  print " "
  sys.exit("Convert a png image to a fits image\n") 
elif len(sys.argv) ==3:
  infile = sys.argv[1]
  outfile = sys.argv[2]
else:
  print " "
  print "Usage: fits_from_png.py infile.png outfile.fits "
  print " "
  sys.exit("Convert a png image to a fits image\n")
 
# Set a clobber flag True so that images can be overwritten
# Otherwise set it False for safety

clobberflag = True  
  
# Assign image data to numpy array
# Convert color images to grayscale using native flatten option

inimage = scipy.misc.imread(infile, flatten=1)

# Create a fits image structure without checking for data validity

outlist = pyfits.PrimaryHDU(inimage.astype('float32'))

# Provide a new date stamp

file_time = strftime("%Y-%m-%d %H:%M:%S", gmtime())

# Update the new fits header

outhdr = outlist.header
outhdr['DATE'] = file_time
outhdr['history'] = 'Generated by fits_from_png' 
outhdr['history'] = 'Image file '+  infile

# Write the fits file

outlist.writeto(outfile, clobber = clobberflag)

# Exit

exit()

