#!/bin/bash

if [[ -z "$1" ]]; then
  echo "Usage: `basename $0` <acronym> [N]"
  exit 1
fi

new_gloss() {
  echo "$1" > acro.out
  ACRO="$(echo $1 | awk '{print $1}')"
  curl \
   -m 60 \
   --user-agent "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.5) Gecko/20060719 Firefox/1.5.0.5" \
   -s "http://www.acronymfinder.com/af-query.asp?Acronym=${ACRO}&Find=find&string=exact" | \
  grep '<td width="60%" valign="middle" bgcolor="' | \
  sed -r 's/^.*>//g' >> acro.out
}

if [[ -e "acro.out" ]]; then
  ACRO="$(head -n 1 acro.out)"
  if [[ "$ACRO" != "$1" ]]; then
    new_gloss "$1"
  fi
else
  new_gloss "$1"
fi

COUNT=$[$(wc -l acro.out | awk '{print $1}') - 1]

if [[ "$COUNT" -eq "0" ]]; then
  echo "No definitions for $1."
  exit 1
fi

if [[ -n "$2" ]]; then
  if [[ "$2" -gt "$COUNT" && "$2" -gt "0" ]]; then
    echo "No more definitions."
    exit 0
  fi
  NN=$2
  NUM=$[$NN + 1]
else
  NN=1
  NUM=2
fi

GLOSS="$(head -n $NUM acro.out | tail -n 1)"

if [[ -n "$GLOSS" ]]; then
  echo "$NN of $COUNT: $GLOSS"
else
  echo "No definition for $1."
fi

