/*
 * Copyright (c) 1984,1985,1989,1994,1995,1996,1999  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.
 *
 *	$Id$
 */

/* 
 * This code is derived from less-335 as retrieved from the NetBSD 
 * source tree on June 6, 1999.
 */

#include <ctype.h>
#include <stdio.h>
#include <unistd.h>
#include <zlib.h>

#include "grep.h"

/* bin_file() comes from filename.c.  Switched isprint() with 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(FILE *f) {
    int i;
    int n;
    unsigned char data[32];
    
    if (!seekable(f))
	return 0;
    if (fseek(f, (off_t)0, 0) == -1)
	return 0;
    n = fread(data, sizeof(data), 1, f);
    for (i = 0;  i < n;  i++)
	if (!isprint(data[i]))
	    return 1;
    fseek(f, (off_t)0, 0);
    return 0;
}


/* seekable() comes from ch.c.  I removed code for MSDOS and PCDOS.   */

/*
 * Is it possible to seek on a file descriptor?
 */

int seekable(FILE *f) {

    return (fseek(f, (off_t)1, 0) != -1);
}

#if GZ
int gzbin_file(gzFile *f) {
    int i;
    int n;
    unsigned char data[32];

    if (!gzseekable(f))
	return 0;
    if (gzseek(f, (z_off_t)0, 0) == -1)
	return 0;
    n = gzread(f, data, sizeof(data));
    for (i = 0; i < n; i++)
	if (!isprint(data[i]))
	    return 1; 
    gzseek(f, (z_off_t)0, 0);
    return 0;
}

int gzseekable(gzFile *f) {

    return (gzseek(f, (z_off_t)1, 0) != -1);
}
#endif
