
#include <intuition/gadgetclass.h>
#include <libraries/gadtools.h>
#include <dos/dos.h>

#include <clib/gadtools_protos.h>
#include <clib/exec_protos.h>
#include <clib/alib_protos.h>
#include <clib/dos_protos.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "project.h"

extern struct TagItem gtag[];

BOOL KeepMessages;

struct List *MessList=NULL;

struct MessNode {
    struct Node node;
    char *mess;
};

void FreeMess( void ) {
  struct MessNode *mn,*on;

    if ( MessList ) {
	mn = MessList->lh_Head;
	while( on = mn->node.ln_Succ ) {
	    free( mn->mess );
	    Remove( (struct Node *)mn );
	    free( mn );
	    mn = on;
	}
	free( MessList );
	MessList = NULL;
    }
}

void NewMess( void ) {
    MessList = malloc( sizeof(struct List) );
    NewList( MessList );
}

void AddMess( char *mess ) {
  struct MessNode *mn = malloc( sizeof(struct MessNode) );

    mn->mess = strdup( mess );
    mn->node.ln_Name = mn->mess;
    AddTail( MessList , (struct Node *)mn );
}

void DettachMess( void ) {
    gtag[0].ti_Data = 0;
    GT_SetGadgetAttrsA( MessGadgets[0] , MessWnd , NULL , gtag );
}

void AttachMess( void ) {
    gtag[0].ti_Data = (long)MessList;
    GT_SetGadgetAttrsA( MessGadgets[0] , MessWnd , NULL , gtag );
}

BOOL CheckError( char *file ) {
  struct FileInfoBlock fib;
  char temp[200];
  FILE *in;

    KeepMessages = TRUE;
    if ( ( GetInfo( &fib , file )) && fib.fib_Size ) {
	if ( !MessWnd )
	    OpenMessWindow( );
	DettachMess( );
	if ( !MessList )
	    NewMess( );
	in = fopen( file , "r" );
	InputString( temp , 200 , in );
	while( !feof( in ) ) {
	    if ( strstr( temp , "Error" ) || strstr( temp , "Fatal" ) )
		KeepMessages = FALSE;
	    AddMess( temp );
	    InputString( temp , 200 , in );
	}
	fclose( in );
	AttachMess( );
	return( TRUE );
    }
    return( FALSE );
}

BOOL ViewErrors( char *file ) {
  char *file2;

    if ( !KeepMessages ) {
	if ( MessWnd )
	    DettachMess( );
	FreeMess( );
	NewMess( );
	if ( MessWnd )
	    AttachMess( );
	KeepMessages = TRUE;
    }
    if ( !CheckError( file ) ) {
	file2 = strdup( file );
	file2[ strlen(file2)-1 ] = 0;
	CheckError( file2 );
	free( file2 );
    }
    if ( KeepMessages )
	return( FALSE );
    return( TRUE );
}

int MessListClicked( void )
{
}

int MessCloseWindow( void )
{
    if ( MessWnd ) {
	DettachMess( );
	FreeMess( );
	CloseMessWindow( );
    }
}

int MessNewSize( void )
{
    DettachMess( );
    CloseMessWindow( );
    OpenMessWindow( );
    AttachMess( );
}

