#!/bin/bash

echo $i $v

if [ "$i" = xmm ] || [ "$i" = lh ] || [ "$i" = en1 ] ;

then

stilts -Xmx1024m -disk tpipe cmd='sort $1; delcols "jrelflag"' ifmt=fits in=${rootdir}/${i}_ukidss_dr${v}plus_flag.fits.gz out=${rootdir}/tmp-flag.fits

stilts -Xmx1024m -disk tpipe cmd='sort $1' ifmt=fits in=${rootdir}/${i}_ukidss_dr${v}plus_j.fits.gz out=${rootdir}/tmpj.fits
stilts -Xmx1024m -disk tpipe cmd='sort $1' ifmt=fits in=${rootdir}/${i}_ukidss_dr${v}plus_h.fits.gz out=${rootdir}/tmph.fits
stilts -Xmx1024m -disk tpipe cmd='sort $1' ifmt=fits in=${rootdir}/${i}_ukidss_dr${v}plus_k.fits.gz out=${rootdir}/tmpk.fits

stilts -Xmx1024m -disk tjoin fixcols=dups nin=4 ifmt1=fits in1=${rootdir}/tmp-flag.fits suffix1=_delflag ifmt2=fits in2=${rootdir}/tmpj.fits suffix2=_delj ifmt3=fits in3=${rootdir}/tmph.fits suffix3=_delh ifmt4=fits in4=${rootdir}/tmpk.fits suffix4=_delk ocmd='colmeta -name "sourceid" $1' ocmd='delcols "*delflag*" ; delcols "*delj*" ; delcols "*delh*" ; delcols "*delk*" ; replacecol RA radiansToDegrees(RA) ; replacecol Dec radiansToDegrees(Dec) ; colmeta -name "RA" -units "degrees" RA ; colmeta -name "Dec" -units "degrees" Dec' out=${rootdir}/${i}_ukidss_dr${v}plus_merged.fits ofmt=fits;

gzip -f ${rootdir}/${i}_ukidss_dr${v}plus_merged.fits

rm -f ${rootdir}/tmp-flag.fits ${rootdir}/tmpj.fits ${rootdir}/tmph.fits ${rootdir}/tmpk.fits

fi
