#!/usr/bin/env python

import os,sys,re
import pyfits

if not os.path.exists('../rawdata'):
    print 'no ../rawdata'
    sys.exit()
if not os.path.exists('./ffiles'):
    print 'no ./ffiles'
    sys.exit()

flag1=0
flag2=0
flag3=0
rlist=os.listdir('../rawdata')
for v in rlist:
    if re.search('fits$',v):
        pref=v[1:8]
        flag1=1
    elif re.search('fits.ic$',v):
        pref=v[1:8]
        flag2=1
    elif re.search('fits.fz$',v):
        pref=v[1:8]
        flag3=1

sumflag=flag1+flag2+flag3
if sumflag==0:
    print 'no fits files in ../rawdata'
    sys.exit()
elif sumflag>1:
    print 'fits extensions mixed'
    sys.exit()
else:
    if flag1==1:
        fext='.fits'
        hnum=0
    elif flag2==1:
        fext='.fits.ic'
        hnum=1
    elif flag3==1:
        fext='.fits.fz'
        hnum=1

flist=os.listdir('./ffiles')
for v in flist:
    if re.search('fits$',v):
        band=v[:1]
        fnum=v[2:6]
        hdr=pyfits.getheader('../rawdata/'+band+pref+fnum+fext,hnum)
        pang1=hdr['POL-AGL1']
        pang2=hdr['POL-AGL2']
        fim=pyfits.open('./ffiles/'+v, mode='update')
        prihdr=fim[0].header
        prihdr.update('POL-AGL1',pang1)
        prihdr.update('POL-AGL2',pang2)
        fim.close()





