/* parts of this file from less(1) */
/* less copyright notice:          */

/*   
 *
 * Copyright (c) 1984,1985,1989,1994,1995,1996  Mark Nudelman
 * All rights reserved.
 *
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice in the documentation and/or other materials provided with 
 *    the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN 
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/* ------------------------------------------------------------------------ */

/* FIXME: remove this: */
#include <gtk/gtk.h>

#include <ctype.h>
#include <sys/types.h>
#include <unistd.h>
#include "binfile.h"

#define  BAD_LSEEK       ((off_t)-1)
#define  IS_BINARY_CHAR  01

static char chardef[256];

/*
 * Is it possible to seek on a file descriptor?
 */
int
seekable(int f)
{
  return (lseek(f, (off_t)1, 0) != BAD_LSEEK);
}

/*
 * Is a given character a "binary" character?
 */
int
binary_char(unsigned char c)
{
  c &= 0377;
  return (chardef[c] & IS_BINARY_CHAR);
}

/*
 * Try to determine if a file is "binary".
 * This is just a guess, and we need not try too hard to make it accurate.
 */

int
bin_file(int f)
{
  int i;
  int n;
  unsigned char data[64];
  
  /* Colin: not seekable, so it is apparently a pipe or something... */
  if (!seekable(f))
    return (0);
  /* Colin: again, a pipe or something... */
  if (lseek(f, (off_t)0, 0) == BAD_LSEEK)
    return (0);
  /* Colin: try to read sizeof(data) characters: */
  n = read(f, data, sizeof(data));
  /* Colin: loop over all read chars: */
  for (i = 0;  i < n;  i++) {
    /* Colin: if we found a binary char return with 1 */
    /* Colin: FIXME: this is not safe with umlauts! */
    if (!(isprint(data[i]) || (isspace(data[i])))) 
      /* Colin: this doesn´t work somehow: */
      // if (binary_char(data[i]))
      return (1);
  }
  /* Colin: no binary char found */
  return (0);
}
