#!/bin/csh

##########################################################
# Write Header (macro definition)
##########################################################
cat <<'==Part1'
\cgidef{-tex -oglu --ic 
\vCat #1 {{\bf(\A{/viz-bin/VizieR?-meta.foot&-source=#1}{#1})}}
}
\CDShead{CDS Catalogues with additional Material}{VizieR.logo}
%\par\tableofcontents\par 
\begin{enumerate}
'==Part1'

##########################################################
# Select various Contents
# %Contents keeps the list of Contents.
##########################################################

# Create a file "Mcats.lis" which contains (media,catid)

( echo "% METAmor"; \
  asu -b -data -source=METAmor -out=text,catid text="*\vizContent*"; \
  echo "% METAtab"; \
  asu -b -data -source=METAtab -out=explain,catid explain="*\vizContent*" ; \
  echo "% METAcat"; \
  asu -b -data -source=METAcat -out=explain,catid explain="*\vizContent*" ; \
  echo "% end" )\
| gawk -v out="Mcats.lis" 'BEGIN{FS="\t"} \
  function list(t) { print "%====List of various Contents from", t ":"; \
  for(M in Cont) { printf "%% %4d with %s\n", Cont[M], M; Cont[M]=0 }} \
  /^% /{ meta++; if(t!="") list(t); t=substr($1,3); next } \
  { i=index($1, "\\vizContent{"); M=substr($1,i+12); \
     i=index(M,"}")-1; if(i>0) M=substr(M,1,i); gsub(/ /, "", M); \
     i=index(M,"/")-1; if(i>0) M=substr(M,1,i); Cont[M] += 1; \
     printf "%s\t%010d\n", M,$2 > out }' 
sort -u -o Mcats.lis Mcats.lis

# List of various media
acut -d -f1 Mcats.lis | uniq -c | gawk '{ \
 printf "\\item\\Aref{ToC%d}{Catalogues with {\\fg{red3}%s}", NR,$NF; \
 printf " \\quad{\\em(%d)}}\n", $1}'
cat <<'==Part2'
\end{enumerate}
{\small\em(Click on a catalogue name or number to move to the
 corresponding VizieR page)}
\hr
\par
'==Part2'

# List the catalogues with media
( asu -b -data -source=METAcat -sort=catid -out=catid,name,title; echo "%%%"; \
  cat Mcats.lis | sed 's/[&]/\\&/g' ) \
| gawk 'BEGIN{ FS="\t"; \
    a["spectrum"]=" (or SED, line profile)"; \
    a["filter"]  =" (response curves)" }\
  /^%%%/{ sep++; next }\
  #END { print "\\end{tabular}" }\
  { if(sep<1) { t[$1+0] = "\\vCat{" $2 "} \\quad \\soft{" $3 "}"; next } \
    # Here the  input from  Mcats.lis \
    if($1!=M) { if(M!="") print ""; M=$1; # "\\end{tabular}"; M=$1;\
      printf "\n\\section{Catalogues with {\\fg{red3}%s} %s}\n", M, a[M]; \
      print "" } # "\\begin{tabular}{rl}" }\
    print t[$2+0] "\\\\" }'

# Final
cat <<'==Part3'
\CDStail{The Catalogue of Catalogues (\basename{\thefile})}
'==Part3'
exit 0
