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

// prtototypes
void scruter(const char* nomfich, int niveau, const char* prefix, int& compteur);
void extraire(const char* nomfich, int niveau, const char* prefix);
bool adres_relatif(const char* nomfich);
int strcpy_nosp(char* s1, const char* s2);

// var globale
int niv_max = 0;

int strcpy_nosp(char* s1, const char* s2)
{
	while (*s2 != '\0') 
	{
		if ( ! isspace(*s2) )
		{
			*s1 = *s2;
			s1++;
		}
		s2++;
	}
	*s1 = '\0';
	return 0;
}

bool adres_relatif(const char* nomfich)
{
	if ( strncmp(nomfich, "http:", (size_t) 5) == 0)
		return false;
	else if ( strncmp(nomfich, "news:", (size_t) 5) == 0)
		return false;
	else if ( strncmp(nomfich, "ftp:", (size_t) 4) == 0)
		return false;
	else if ( strncmp(nomfich, "mailto:", (size_t) 7) == 0)
		return false;
	else if ( strncmp(nomfich, "file:", (size_t) 5) == 0)
		return false;
//	else if ( strncmp(nomfich, "../", (size_t) 3) == 0)
//		return false; // il faudrait suivre les repertoires ...
	else
		return true;
}

void scruter(const char* nomfich, int niveau, const char* prefix, int& compteur)
{

	char prefix2[64];
	if ( (niveau < niv_max) && (adres_relatif(nomfich) ))
	{
		// affichage
		for (int i = 0; i < niveau; ++i)
			printf("      ");
		if (niveau == 0)
			sprintf(prefix2, "%d", compteur);
//			printf("%d %s\n", compteur, nomfich);
		else
//			printf("%s.%d %s\n", prefix, compteur, nomfich);
			sprintf(prefix2, "%s.%d", prefix, compteur);

//		on elimine les tag :
		char* ptr = strchr(nomfich, '#');
		if ( ptr != NULL)
			*ptr = '\0';

		printf("%s %s\n",  prefix2, nomfich);
		extraire(nomfich, niveau, prefix2);
	}
	else
		compteur--;
}

void extraire(const char* nomfich, int niveau, const char* prefix)
{
	FILE* f;
	#define TAIL_LIGN 512
	char ligne[TAIL_LIGN];
	char* ligne2;
	char* ptr = NULL;	// pointeur d'avancement
	char nom[128];
	int compteur = 0;

	f = fopen(nomfich, "r");
	if ( f == NULL)
	{
//		fprintf(stderr, "PB : %s inexistant\n", nomfich);
		return;
	}

	while (fgets(ligne, TAIL_LIGN, f) != NULL)
	{
		ligne2 = ligne;
		while ( (ptr = strstr(ligne2, "HREF")) != NULL )
		{
			char* ptr_deb = strchr(ptr, '"');
			if (ptr_deb != NULL)
			{
				ptr_deb++;
				// strcpy(nom, ptr_deb);
				char* ptr_fin = strchr(ptr_deb, '"');
				if (ptr_fin != NULL)
				{
					*ptr_fin = '\0';
					strcpy_nosp(nom, ptr_deb);
					compteur++;
					scruter(nom, niveau + 1, prefix, compteur);
					ligne2 = ptr_fin + 1;
				}
				else
				{
					fprintf(stderr, "PB : fin de chaine non trouvee dans %s\n",  ptr_deb);
					ligne2 = ptr_deb;
				}
			}
			else
			{
				fprintf(stderr, "PB : debut de chaine non trouvee dans %s\n",  ptr);
				ligne2 = ptr+4;
			}
		}
	}
	fclose(f);
}

int main(int argc, char* argv[])
{
	const int niv_max_def = 5;
	int compteur = 1;

	if ( argc !=  2)
		niv_max = niv_max_def;
	else
		niv_max = atoi(argv[1] );
		
	scruter("index.html", 0, "", compteur);
	return 0;
}
