#!/usr/bin/ksh93
################################################################
#### Program: cmp_k93
#### 
#### Description: Emulation of the Unix "cmp" command
#### 
#### Author: Dana French (dfrench@mtxia.com)
####         Copyright 2004
#### 
#### Date: 07/22/2004
#### 
################################################################
function cmp_k93 {
  typeset TRUE="0"
  typeset FALSE="1"
  typeset VERBOSE="${FALSE}"
  typeset VERYVERB="${FALSE}"
  typeset EXITCODE="${TRUE}"
  typeset OPTION
  typeset LINE1
  typeset LINE2

  while getopts ":vV" OPTION
  do
    case "${OPTION}" in
        'v') VERBOSE="${TRUE}";;
        'V') VERYVERB="${TRUE}";;
        '?') print "Syntax: cmp_k93 [-] file ..." && return 4 ;;
    esac
  done
 
  shift $(( ${OPTIND} - 1 ))
  typeset FILE1="${1:?ERROR: First File not specified}"
  typeset FILE2="${2:?ERROR: Second File not specified}"

#### Determine if the first file name is STDIN
  typeset STDIN1="${FALSE}"
  typeset UNIT1="3"
  if [[ "_${FILE1}" = '_-' ]]
  then
    STDIN1="${TRUE}"
    UNIT1="0"
  fi

#### Determine if the second file name is STDIN
  typeset STDIN2="${FALSE}"
  typeset UNIT2="4"
  if [[ "_${FILE2}" = '_-' ]]
  then
    STDIN2="${TRUE}"
    UNIT2="0"
  fi

  (( STDIN1 == TRUE && STDIN2 == TRUE )) &&
    print "ERROR: Only one file may be read from STDIN" &&
    return 3

  (( STDIN1 == FALSE )) && eval exec ${UNIT1}\<"${FILE1}"
  (( STDIN2 == FALSE )) && eval exec ${UNIT2}\<"${FILE2}"

  IFS=""
  NUM="1"
  while read -u ${UNIT1} -r -- LINE1
  do
     read -u ${UNIT2} -r -- LINE2
     if [[ "${LINE1}" != "${LINE2}" ]] 
     then
       EXITCODE="${FALSE}"
       print -u2 "Files are different at line ${NUM}"
       break
     fi
     (( NUM++ ))
  done
  (( STDIN1 == FALSE )) && eval exec ${UNIT1}\<\&-

  if (( EXITCODE == TRUE )) && read -u ${UNIT2} -r -- LINE2
  then
     EXITCODE="${FALSE}"
     print -u2 "Files are different at line ${NUM}"
  fi
  (( STDIN2 == FALSE )) && eval exec ${UNIT2}\<\&-
  return ${EXITCODE}
}
################################################################

cmp_k93 "${@}"