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

#include <sys/stat.h>

typedef unsigned int uint;

#ifndef PATH_MAX
#  define PATH_MAX 256
#endif

#ifdef __CYGWIN__
#  define stat64 stat
#else
#  if (defined _MSC_VER) || (defined __MINGW32_VERSION)
#    define stat64 _stati64
#  endif
#endif

uint find_directory( char *dirname ) {
  DIR* dir;
  dirent* ent;
  struct stat64 ents;

  char buffer[PATH_MAX+2];
  char* end = &buffer[PATH_MAX];
  char *p, *q, *src;

  uint ok,c;

  // Copy directory name to buffer
  
  for( src=dirname,p=buffer; (p<end) && src[0]; ) *p++ = *src++;
  *p = '\0';

  dir = opendir( buffer );

  if( dir==0 ) {

    printf ("Cannot open directory %s\n", dirname);
    ok = 0;

  } else {

    while(1) {

      ent = readdir(dir); if( ent==0 ) break;

      // Append file name
      q = p;
      c = (buffer<q) ? q[-1] : ':';
      if( (c!=':') && (c!='/') && (c!='\\') ) *q++ = '/';
      for( src=ent->d_name; (q<end) && src[0]; ) *q++ = *src++;
      *q = '\0';

      if( stat64(buffer,&ents)!=0 ) break;

      if( S_ISDIR(ents.st_mode) ) {
        if( (strcmp(ent->d_name,".")!=0) && (strcmp(ent->d_name,"..")!=0) ) find_directory( buffer );
      } else {
        printf( "%s:%i\n", buffer, uint(ents.st_size) ); 
      }

    }

    closedir( dir );

    ok = 1;
  }

  return ok;
}


int main( int argc, char** argv )  {

  if( argc>1 ) find_directory(argv[1]);

  return 0;
}
