#!/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

pth=$( dirname "$0" )

case "$pth" in
  /* )
    ;; # already absolute
  *  )
    pth=$(cd "$pth" && pwd)
    ;;
esac

case ":$PATH:" in
  *:"$pth":* )
    ;;
  * )
    PATH="$PATH:$pth"
    export PATH
    ;;
esac

# handle common flags - dot command is equivalent of "source"

if [ ! -f "$pth"/xcommon.sh ]
then
  echo "ERROR: Unable to find '$pth/xcommon.sh' file" >&2
  exit 1
fi

. "$pth"/xcommon.sh

# initialize specific flags

FindArchiveFolder

FindPostingsFolder

FindDataFolder

seconds_start=$(date "+%s")

for i in {1..100}
do
  echo $(( ( 1 + RANDOM % 30000) * 1000 + ( RANDOM % 1000) ))
done |
sort -n |
uniq |
xfetch -db pubmed |
xtract -pattern PubmedArticle -element MedlineCitation/PMID ArticleTitle |
( while IFS=$'\t' 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
  res=$( xsearch -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 )

ascend_mesh_tree() {
  var="${1%\*}"
  while :
  do
    frst=$( xinfo -count "$var* [TREE]" )
    scnd=$( cat "${dataBase}/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
}

echo ""
xinfo -fields

echo ""
xinfo -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 ""

seconds_end=$(date "+%s")
seconds=$((seconds_end - seconds_start))
echo "$seconds seconds"
