/*

	Cr‚ation de LINK sous MagiC >= 4.02

*/

#include	"stdio.h"
#include	"tos.h"
#include	"atarierr.h"
#include	"string.h"
#include	"portab.h"

#define MAX_LEN 128

LOCAL BYTE line[MAX_LEN],statement[MAX_LEN],par1[MAX_LEN];

VOID	main(VOID);
WORD	ProcessFile(BYTE *filename);
static void ProcessLine(BYTE *line, BYTE *s, BYTE *p1, LONG limit);
static BYTE *trim (BYTE *str);
VOID MakeLink ( UBYTE *source, UBYTE *link );

VOID	main(VOID)
{
	ProcessFile("link.inf");
}


WORD	ProcessFile(BYTE *filename)
{
FILE *file_handle;
LONG	lines=0;

	file_handle = fopen(filename,"r");
	
	if (file_handle == NULL)
	{
		return(-33);
	}
	
	while ( fgets(line, MAX_LEN, file_handle) != NULL )
	{
		lines++;
		if ( (*line != ';') && (*line != '#') && (*line != '\0') )
		{
			ProcessLine(line, statement, par1, MAX_LEN);
			if ( (*statement != EOS) && (*par1 != EOS) )
			{
				MakeLink( statement, par1 );
			}
		}
	}
	fclose(file_handle);
return(TRUE);
}

/* Extraction des elements (tokens) d'une chaine */

static void ProcessLine(BYTE *line, BYTE *s, BYTE *p1, LONG limit)
{
char	*pos,*token;
long	i;
	
	for(i=0;line[i]!=0;i++)	if(line[i]==9)	line[i]=32;	/* Allow TAB */

	pos = strchr(line, ';');
	if (pos) *pos = EOS;
	
	pos = strchr(line, '\n');
	if (pos) *pos = EOS;
	
	token = strtok(line, " ");
	
	*s = *p1 = EOS;
	
	if (token)
	{
		*s=0;
		strncat(s, token, limit);
		strlwr(s);
		
		token = strtok(NULL, " ");
		
		if (token)
		{
			*p1=0;
			strncat(p1, token,limit);
		}
	}
}

/*-----------------------------------------------------------------------*
 * Suppression des espaces & tab en d‚but et fin de chaine <str>               *
 *-----------------------------------------------------------------------*/

static BYTE *trim (BYTE *str)
{
register char *s;
register int i = 0;
BYTE chaine[MAX_LEN+1];

  while ( (*(str + i) == ' ') || (*(str + i) == 0x09 ) )    i++;
  *chaine=0;
  strncat (chaine, (str + i),MAX_LEN);

  s = chaine + strlen (chaine) - 1;
  for( ; ((*s == ' ')||(*s == 0x09)) && (s >= chaine) ; *s-- = 0);
  *str=0;
  strncat (str, chaine,MAX_LEN);

return (str);
}

VOID MakeLink ( UBYTE *source, UBYTE *link )
{
	if ( Fsymlink ( source, link ) != E_OK ) /* pas OK */
	{
		printf("\n\aLINK Installation error %s on %s\n",source, link);
	}
}
