#! /bin/bash
# Last edited on 2024-04-01 17:04:59 by stolfi

usage="$0 [FILE.sid|FNUM]"

# Displays an image file in SID format.
# Either give the SID file name, or the VMS page number.

if [[  $# != 1  ]]; then
  echo "** usage: ${usage}" 1>&2; exit 1
fi

name="$1"; shift

# Classify argument, get Beinecke file name (with dir) and fnum
if [[ "/${name}" =~ /.*[.]sid  ]]; then
  sidfile="${name}"
  tbl=( `grep "${sidfile%.*}" sidfile-to-fnum.tbl | head -1` )
  if [[  ${#tbl[@]} -eq 0  ]]; then
    echo "SID file ${sidfile%.*} not in table" 1>&2
    blfile="NONE"
    fnum="???"
  elif [[ ${#tbl[@]} -eq 2 ]]; then
    blfile="${tbl[1]}.sid"
    fnum="${tbl[2]}"
  else
    echo "** table bug: (${tbl[@]})" 1>&2; exit 1
  fi
elif [[ "/${name}" =~ /f[0-9].*  ]]; then 
  fnum="${name}"
  tbl=( `grep "${fnum}" sidfile-to-fnum.tbl | head -1` )
  if [[  ${#tbl[@]} -eq 0  ]]; then
    echo "no Beinecke sid file for page ${fnum}" 1>&2; exit 1
  elif [[  $#tbl == 2  ]]; then
    blfile="${tbl[1]}.sid"
    sidfile="${blfile##*/}"
    echo "page ${fnum} is in ${blfile}" 1>&2
  else
    echo "** table bug: (${tbl[*]})" 1>&2; exit 1
  fi
else
  echo "** ${name}: bad argument" 1>&2; 
  echo "usage: ${usage}"; exit 1
fi

# If the SID file is not present, try to get it from Beinecke:
if [[ ! ( -r ${sidfile} ) ]]; then
  if [[  "/${blfile}" == "/NONE"  ]]; then 
    echo "** file ${sidfile} not present and not in Beinecke site" 1>&2; 
  else 
    echo "** fetching ${blfile} from Beinecke site"  1>&2;
    wget -nv "http://130.132.81.124/VOYNICHIMG/sids/${blfile}"
  fi
fi

# If we still don't have the file, give up:
if [[ ! ( -s ${sidfile} ) ]]; then
  echo "** file ${sidfile} not found" 1>&2; exit 1
fi

# Display it with the lousy MrSID viewer:
MrSID -w 800 -h 800 -i ${sidfile}
