#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "obj.h"
#include "names.h"

char *ckfmsg = "write error on output";

			/* an optimisation over plain strcmp() */
#define	STREQ(a, b)	(*(a) == *(b) && strcmp((a), (b)) == 0)

extern long obj_type;

int ascmagic(char *buf)
 {
	register int i;
	char	*s, *strtok(), *token;
	register struct names *p;
	extern int nbytes;
	short has_escapes = 0;

	/* these are easy, do them first */
   obj_type = 0L;

	/*
	 * for troff, look for . + letter + letter;
	 * this must be done to disambiguate tar archives' ./file
	 * and other trash from real troff input.
	 */
	if (*buf == '.' && 
		isascii(*(buf+1)) && isalnum(*(buf+1)) &&
		isascii(*(buf+2)) && isalnum(*(buf+2)))
    {
      obj_type = TROFF;
		return 1;
	 }
	if ((*buf == 'c' || *buf == 'C') && 
	    isascii(*(buf + 1)) && isspace(*(buf + 1))) 
    {
		obj_type = FORTRAN;
		return 1;
	 }

	/* look for tokens from names.h - this is expensive! */
	s = buf;
	while ((token = strtok(s, " \t\n\r\f")) != NULL) 
    {
		s = NULL;	/* make strtok() keep on tokin' */
		for (p = names; p < names + NNAMES; p++) 
        {
			 if (STREQ(p->name, token)) 
            {
				  //ckfputs(types[p->type], stdout);
				  obj_type = p->type + 13;
				  return 1;
			   }
		  }
	 }

	switch (is_tar((union record *) buf)) 
    {
		case 1:
			obj_type = TAR_ARCH;
//			ckfputs("tar archive", stdout);
			return 1;
		case 2:
			obj_type = POSIX_TAR_ARCH;
//			ckfputs("POSIX tar archive", stdout);
			return 1;
	 }

	for (i = 0; i < nbytes; i++) {
		if (!isascii(*(buf+i)))
			return 0;	/* not all ascii */
		if (*(buf+i) == '\033')	/* ascii ESCAPE */
			has_escapes ++;
	}

	/* all else fails, but it is ascii... */
	if (has_escapes)
     {
       obj_type = ASCII_ESC;
//		 ckfputs("ascii text (with escape sequences)", stdout);
		}
	else 
     {
       obj_type = ASCII;
//		 ckfputs("ascii text", stdout);
	  }
	return 1;
 }
