/* <<< 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 scanfile (int i, int showinfo)
{
    struct stat
	statbuf;
    register FILE
	*f;
    char
	buf [1000];
    time_t
	now;
    struct tm
	*loctime;
    register int
	old_offset,
	current_offset;

    /* check that file is still here */ 
    if (stat (finfo [i].name, &statbuf))
    {
	if (finfo [i].active)
	{
	    warning ("File %s has disappeared", finfo [i].name);
	    finfo [i].active = 0;
	}
	return;
    }

    /* check for reappeared files */
    if (! finfo [i].active)
    {
	warning ("File %s has reappeared", finfo [i].name);
	finfo [i].active = 1;
	finfo [i].offset = 0;
    }

    current_offset = statbuf.st_size;
    old_offset = finfo [i].offset;
    finfo [i].offset = current_offset;

    /* just adjust offset if we don't have to show it */ 
    if (! showinfo)
	return;

    /* check that file hasn't shortened */
    if (current_offset < old_offset)
    {
	warning ("File %s has shortened", finfo [i].name);
	return;
    }

    /* check that something at all happened */
    if (current_offset == old_offset)
	return;

    /* now open the file */
    if (! (f = fopen (finfo [i].name, "r")) )
    {
	warning ("Cannot read %s: %s", finfo [i].name, strerror (errno));
	finfo [i].active = 0;
	return;
    }

    /* create first text: HH:MM:SS file */
    buf [0] = '\0';
    if (printtime)
    {
	time (&now);
	loctime = localtime (&now);
	sprintf (buf, "%2.2d:%2.2d'%2.2d ",
		loctime->tm_hour, loctime->tm_min, loctime->tm_sec);
    }
    if (printname)
    {
	strcat (buf, finfo [i].name);
	strcat (buf, " ");
    }
    if (newline)
	strcat (buf, "\n");

    if (printtime || printname)
	addline (buf, finfo [i].colorindex);
    
    fseek (f, old_offset, SEEK_SET);
    
    while (1)
    {
	fgets (buf, linelen + 1, f);
	if (feof (f))
	    break;

	addline (buf, finfo [i].colorindex);
    }

    flushline ();
    fclose (f);
}
