/* <<< Start of information >>>                                       */
/* ------------------------------------------------------------------ */
/* This file is part of the xwatch program. Copyright (C) Karel Kubat */
/* 1995. All rights reserved. You are permitted to redistribute this  */
/* package, if you include all unmodified sources and all unmodified  */
/* documentation (including this text). You are NOT permitted to      */
/* distribute files of this package with modifications. See the file  */
/* COPYING for more information. When in doubt, mail me at            */
/* karel@icce.rug.nl.                                                 */
/* ------------------------------------------------------------------ */
/* <<< End of information >>>                                         */

#include "xwatch.h"

void addfile (char *filename)
{
    struct stat
	statbuf;
    char
	buf [512],
	fname [1000];
    FILE
	*f;
    register int
	i,
	inode,
	readres;
    int
	red, green, blue;

    /* split filename into name part and colors part */
    if (sscanf (filename, "%[^:]:%d/%d/%d", fname, &red, &green, &blue) < 4)
    {
	strcpy (fname, filename);
	red = fred;
	green = fgreen;
	blue = fblue;
    }

    /* see if file exists */ 
    if (stat (fname, &statbuf))
    {
	if (firstwarnings)
	    warning ("Cannot find %s: %s", fname, strerror (errno));
	return;
    }

    /* see if it's an ordinary file */
    if (! S_ISREG (statbuf.st_mode))
    {
	if (firstwarnings)
	    warning ("%s is not a regular file", fname);
	return;
    }

    inode = statbuf.st_ino;

    /* see if it's a textfile */
    if (! (f = fopen (fname, "r")) )
    {
	if (firstwarnings)
	    warning ("Cannot read %s: %s", fname, strerror (errno));
	return;
    }
    readres = fread (buf, 1, sizeof (buf), f);
    for (i = 0; i < readres; i++)
	if (! buf [i])
	{
	    if (firstwarnings)
		warning ("File %s is a binary file", fname);
	    fclose (f);
	    return;
	}
    fclose (f);

    /* see if we have same file already */
    for (i = 0; i < nfinfo; i++)
	if (finfo [i].inode == inode)
	{
	    if (firstwarnings)
		warning ("Names %s and %s are the the same file",
		     fname, finfo [i].name);
	    return;
	}

    /* after all the checks, add it to our list */ 
    if (! (finfo = (Fileinfo *) realloc (finfo, (nfinfo + 1) *
					 sizeof (Fileinfo))) ||
	! (finfo [nfinfo].name = strdup (fname))
       )
	error ("out of memory");

    finfo [nfinfo].active = 1;
    finfo [nfinfo].inode = inode;
    finfo [nfinfo].offset = statbuf.st_size;
    finfo [nfinfo].colorindex = getcolorindex (red, green, blue);
    nfinfo++;
}
	
