#!/bin/bash

# Public domain notice for all NCBI EDirect scripts is located at:
# https://www.ncbi.nlm.nih.gov/books/NBK179288/#chapter6.Public_Domain_Notice

seconds_start=$(date "+%s")
count=0
for i in {1..100}
do
  echo $(( ( 1 + RANDOM % 30000) * 1000 + ( RANDOM % 1000) ))
done |
sort -n |
uniq |
fetch-pubmed |
xtract -pattern PubmedArticle -element MedlineCitation/PMID ArticleTitle |
( while read uid ttl
do
  if [ "$ttl" = "[Not Available]." ]
  then
    echo "$uid SKIP"
    continue
  fi
  if [ "$ttl" = "Health." ]
  then
    echo "$uid SKIP"
    continue
  fi
  if [ -z "$ttl" ]
  then
    echo "$uid TRIM -- $ttl"
    continue
  fi
  count=$((count + 1))
  res=$( phrase-search -title "$ttl" )
  report="1"
  if [ -z "$res" ]
  then
    echo "$uid NONE -- $ttl"
    continue
  fi
  num=$( echo "$res" | wc -l | tr -d '[:space:]' )
  echo "$res" |
  while read pmid
  do
    if [[ $uid =~ $pmid ]]
    then
      if [ "$num" -lt 2 ]
      then
        echo "$uid OKAY -- $ttl"
      else
        echo "$uid MULT ${num## } -- $ttl"
      fi
      report="0"
      break
    fi
  done
  if [ "$report" -lt 1 ]
  then
    echo "$uid FAIL $num -- $ttl"
  fi
done
seconds_end=$(date "+%s")
seconds=$((seconds_end - seconds_start))
echo "$seconds seconds, $count records"
)

ascend_mesh_tree() {
  var="${1%\*}"
  while :
  do
    frst=$( phrase-search -count "$var* [TREE]" )
    scnd=$( cat $EDIRECT_PUBMED_MASTER/Data/meshconv.xml |
            xtract -pattern Rec -if Tree -equals "$var" -first Code Name )
    printf "${frst}\t${scnd}\n"
    case "$var" in
      *.* ) var="${var%????}" ;;
      *   ) break             ;;
    esac
  done |
  align-columns -g 4
}

if [ -n "${EDIRECT_PUBMED_MASTER}" ] && [ -d "${EDIRECT_PUBMED_MASTER}/Postings" ]
then
  echo ""
  phrase-search -fields

  echo ""
  phrase-search -terms PROP

  echo ""
  cit2pmid -local \
    -title "nucleotide sequences required for tn3 transposition immunity" \
    -author "Kans JA" -author "Casadaban MJ" \
    -journal "J Bacteriol" -year 1989 -volume 171 -issue 4 -page 1904-14

  echo ""
  ascend_mesh_tree "C01.925.782.417.415"

  echo ""
fi
