#! /bin/sh
#++++++++++++++++
#.IDENTIFICATION tycepo
#.LANGUAGE       Bourne-shell
#.AUTHOR         Francois Ochsenbein [CDS]
#.ENVIRONMENT    
#.KEYWORDS       
#.VERSION  1.0   19-Apr-2002
#.VERSION  1.1   16-Mar-2012: Bourne shell version
#.VERSION  1.2   08-Aug-2016: Don't use the index
#.PURPOSE        Get the Tycho Epoch Photometry
#.COMMENTS       We assume as input = Tycho Number(s)
#----------------

if [ $# -lt 1 ]; then
    echo "Usage: tycepo tyc1-tyc2-tyc3 [tyc1-tyc2-tyc3]..."
    exit 0
fi

dir=`dirname $0`	# Data share same root directory

while [ $# -gt 0 ]; do
    tyc=`echo $1 | awk -F- '{printf("%04d %d %s",$1,$2,$3)}'`
    nw=`echo $tyc | wc -w`
    if [ $nw -eq 2 ]; then
	tyc="$tyc 1"
    elif [ $nw -ne 3 ]; then
	echo "++++Bad Tycho number (must be tyc1-tyc2-tyc3): $1"
	exit 1
    fi
    shift
    tyc1=`echo $tyc | cut -d' ' -f1`
    tyc23=`echo $tyc | cut -d' ' -f2-3|tr ' ' -`
    fgz=$dir/tep`echo $tyc1 | cut -c1-2`/$tyc1.gz
    tycp=`echo $tyc | tr ' -' '||'`
    zcat $fgz | awk -F\| -v ID="$tycp" '
    BEGIN{split(ID,t)} 
    /^$/{p++;if(found>0) exit}
    /^ *[1-9][0-9]*[\|]/ { if((($1-t[1])==0)&&(($2-t[2])==0)&&(($3-t[3])==0)) {
       print "#", $0;
       if(found==0) print "    z |  PAz | Dmas|s.e.| Fit |Flags"; found++ }next}
    {print}'
    #o=`look $tyc23= $fgz.idx | cut -d= -f2`
    #echo "#....In file $fgz, at offset: $o"
    #tail -c +${o} $fgz | gzip -cd | awk '/^$/{p++}\
    #   NR==2{ printf("JD-2440000| BTmag| s.e.| BTbg | VTmag| s.e.| VTbg |"); \
    #   print "    z |  PAz | Dmas|s.e.| Fit |Flags"}\
    #   {print; if (p>0) exit}'
done
