from astropy.io import fits
import numpy as np
from scipy import interpolate
from read_frameinfo import *


def calc_err_fr(framename):
  info = read_fi('frame_info')

  filters_number={}
  filters_number['u']=0
  filters_number['g']=1
  filters_number['r']=2
  filters_number['i']=3
  filters_number['z']=4

  photofieldname=info['photo_field']

  hdulist = fits.open(framename)
  scidata = hdulist[0].data
  filt = hdulist[0].header['FILTER']
  fits_info = hdulist[3].data[0]
  sky = hdulist[2].data['ALLSKY']
  x_arr = hdulist[2].data['XINTERP']
  y_arr = hdulist[2].data['YINTERP']
  print sky.shape
  interpole = interpolate.interp2d(np.arange(0, sky.shape[2], 1), np.arange(0,sky.shape[1] , 1), sky, kind = 'linear')

  height=len(x_arr[0])
  width=len(y_arr[0])
  sky_stretched=np.zeros((width,height), dtype=np.float)

  print x_arr.shape
  print y_arr.shape
  print scidata.shape

  sky_stretched = interpole(x_arr[0], y_arr[0])

  calib_vec = hdulist[1].data
  calibration = np.zeros((width,height), dtype=np.float)
  calibration[:] = calib_vec
  dn = scidata/calibration + sky_stretched
  print calibration.shape

  hdulist_photoField = fits.open(photofieldname)
  filt_num=filters_number[filt]
  dat=hdulist_photoField[1].data
  photoField_row={}
  for row in dat:
    if (row['FIELD']==fits_info['FIELD']) & (row['CAMCOL']==fits_info['CAMCOL']) & (row['RERUN']==fits_info['RERUN']) & (row['RUN']==fits_info['RUN']):
      photoField_row = row
      break
  dark_variance = photoField_row['DARK_VARIANCE'][filt_num]
  gain = photoField_row['GAIN'][filt_num]

  print dark_variance,'   ', gain


  dn_err = np.sqrt(dn/gain+dark_variance)
  img_err = dn_err*calibration

  stddiv = np.std(img_err.ravel(), axis=0)
  mean = np.mean(img_err.ravel(), axis=0)


  print mean, '   ', stddiv,'  ',(mean/stddiv)

  hdu = fits.PrimaryHDU(data=img_err)
  hdulist = fits.HDUList([hdu])
  hdulist.writeto('err.fits', clobber=True)


  hdu = fits.PrimaryHDU(data=sky_stretched)
  hdulist = fits.HDUList([hdu])
  hdulist.writeto('sky_stretched.fits', clobber=True)