/*---------------------------------------------------------------*/
/*   Copyright (c) 1988 Regents of the University of California  */
/*                 All Rights Reserved                           */
/*---------------------------------------------------------------*/
/*
      @(#)filetype.c	1.3   (UCLA/IGPP)   21 Jan 1994
 */

/*-- FILETYPE -----------------------------------------------------*/
/* Checks a file name passed in a string to see what type of file  */
/* it is.                                                          */
/*                                                                 */
/* Returns:                                                        */
/*    NOREAD	: If file can not be read by you.                  */
/*    NOACCESS	: If path is inaccessable or none existant.        */
/*    DIRFILE	: If directory.                                    */
/*    TEXTFILE	: If text file.                                    */
/*    EXECFILE	: If machine executable                            */
/*                                                                 */
/*  Entry Requirements:                                            */
/*    fs : string containing the name (and path) of file to check  */
/*                                                                 */
/*  Developement History:                                          */
/*    Begun: 02/19/87 - Todd King                                  */
/*                   Under GG44 support                            */
/*    Revised:  4/28/87 - Marco Zagha (files closed properly)      */
/*                   Under GG44 support                            */
/*-----------------------------------------------------------------*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "filetype.h"

filetype(fs)
char *fs;
{
    struct stat stbuf;
    FILE *f;
    int c;

/* Attempt to get stat on file loaded */
    if (stat (fs, &stbuf) == -1) {
	return (NOACCESS);
    }

/* Check if directory */
    if ((stbuf.st_mode & S_IFMT) == S_IFDIR) {
	return (DIRFILE);
    }

/* Good chance its a text file - Must open it to check magic number */
    if ((f=fopen(fs, "r")) == NULL) {
	perror(fs);
	return (NOREAD);
    }

/* Get magic number */
    c = getw(f);

/* Try to see whether it is an text file - Check against valid magic numbers */

    switch ((c | *f->_ptr << 8) & 0177777) {
    case 0405:		/* Not a text file */
    case 0407:
    case 0410:
    case 0411:
    case 0413:
    case 0177545:
    case 046506:	/* Solaris binary */
	fclose (f);
	return (EXECFILE);
    default:		/* Text file */
	fclose (f);
	break;
    }
    return (TEXTFILE);
}
