#include <ext.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

FILE *fp;
char Path[128], *pback, *heap_base, *heap_ptr, *heap_top, *act_file;

void add_link( char *file )
{
  char *pfile, *bufp, buf[128];

  strcpy( buf, pback ); strupr( pfile = file );
  for (;;)
  {
    if ((bufp = strrchr( buf, '\\' )) == 0) return;
    if (strncmp( pfile, "..\\", 3 )) break;
    *bufp = 0; pfile += 3;
  }
  strcpy( bufp + 1, pfile ); pfile = heap_base;
  while (pfile < heap_ptr)
  {
    while (*pfile++);
    if (strcmp( buf + 1, pfile ) == 0) return;
    while (*pfile++);
  }
  strcpy( file, buf + 1 );
  printf( "\t%s%s\n", heap_ptr, file );
  while (*file++); heap_ptr = file;
}

void fill_heap( void )
{
  int  i, flag;
  char *key, *file;

  flag = 0;
  for (;;)
    switch (i = fgetc( fp ))
    {
      case EOF: do
		{ for (;;)
		  {
		    if (act_file == heap_ptr)
		    {
		      fprintf( stderr, " Operation erfolgreich"
				       " abgeschlossen.\n\n" ); return;
		    }
		    while (*act_file++); file = act_file;
		    while (*act_file++);
		    if ((key = strrchr( file, '.' )) == 0) break;
		    if (strcmp( key, ".IMG" ) == 0) continue;
		    if (strcmp( key, ".IFF" ) == 0) continue;
		    if (strcmp( key, ".GEM" ) == 0) continue;
		    if (strcmp( key, ".RSC" ) == 0) continue;
		    if (strcmp( key, ".SAM" ) == 0) continue;
		    if (strcmp( key, ".SND" ) == 0) continue;
		    break;
		  }
		  strcpy( pback + 1, file );
		}
		while (freopen( Path, "rb", fp ) == 0);
      case 0:
      case 10:	flag = 0; break;
      case (unsigned char)'':
	switch (flag)
	{
	  case 0: flag = 1; key = heap_ptr; break;
	  case 1: flag = 2; *key++ = 0; file = key; break;
	  case 2: flag = 0; *key = 0; add_link( file );
			    if (heap_ptr >= heap_top)
			    {
			      fprintf( stderr,
				" Der Speicherplatz hat nicht gereicht,"
				" Operation abgebrochen!\n\n" ); return;
	}		    }
	break;
      default: if (flag) *key++ = i;
}   }

int main( int argc, char **argv )
{
  size_t memleft;

  if (--argc <= 0)
  {
    fprintf( stderr, "\n Aufruf: 1stindex [Pfadname] [>output]\n\n" );
    return 0;
  }
  strcpy( Path, argv[1] );
  if ((pback = strrchr( Path, '\\' )) == 0)
  {
    fprintf( stderr, "\n Bitte kompletten Pfadnamen angeben.\n\n" );
    return 0;
  }
  if ((memleft = coreleft()) <= 32128)
  {
    fprintf( stderr, "\n Nicht gengend Speicherplatz verfgbar!\n\n" );
    return 0;
  }
  heap_base = heap_ptr = act_file = malloc( memleft -= 32000 );
  heap_top = heap_base + memleft - 128;
  if ((fp = fopen( Path, "rb" )) != 0)
  {
    fprintf( stderr, "\n Erstelle Index von %s ...\n", Path );
    fill_heap(); fclose( fp );
  }
  else fprintf( stderr, "\n Fehler beim ffnen!\n\n" );
  free( heap_base ); return 0;
}