#!/bin/csh -f

# Extract entries and string definitions used therein from ~/tex/sources.bib for sources with keys on command line.
# Also called by extractrefs

set debug = 1

set keys = ($*)

set tempbase = /tmp/extractrefs.$USER.$$
set tempout = $tempbase.out
set temppat = $tempbase.pat
set bibfile = ~/tex/sources.bib

empty $tempout

foreach key ($keys)
query $bibfile $key\ | \egrep -v 'comment|oneofmine|url =' >> $tempout
end

# three of same sed following for nested braces
cat $tempout \
  | sed 's+{[^{}]*}++g' | sed 's+{[^{}]*}++g' | sed 's+{[^{}]*}++g' | sed -n 's+ ,.*= \([^ ]*\)+\1+p' | tr '# ' '\012' | \grep -v '^[ 	]*$' | \grep -v '^[0-9]*$' | \egrep -v 'jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec' | sort -u | sed 's+^\(.*\)$+@string{\1 +' > $temppat

set numpats = `cat $temppat | wc -l`

if ( $numpats > 0 ) then
  \fgrep -f $temppat $bibfile
endif

echo ""

cat $tempout

if (! $debug) then
  rm -f $tempbase*
endif
