/* This file is part of Lcrzo.
*/

int lcrzo_dir_count(const char *dirname,
		    lcrzo_int32 *pcount)
#if defined LCRZODEF_SYSTEM_Unix
{ DIR *thisdir;
  struct dirent *file;
  int ret;
  lcrzo_string filename;
  lcrzo_int32 count;
  struct stat st;
  lcrzo_string cleandirname;

  /* verify if directory exist */
  ret=lcrzo_priv_dirname_removelastslash(dirname, &cleandirname);
  if (ret==LCRZO_ERR_OK)
  { ret=lcrzo_priv_filename_stat_get(cleandirname, &st);
  }
  if (ret!=LCRZO_ERR_OK)
  { lcrzo_string_free(cleandirname);
    return(ret);
  }

  /*open the directory*/
  thisdir=opendir(cleandirname);
  lcrzo_string_free(cleandirname);
  if ( thisdir==NULL ) return(LCRZO_ERR_FUOPENDIR);

  file=readdir(thisdir);
  count=0;
  while (file!=NULL)
  { lcrzo_efr(lcrzo_string_initm_text(file->d_name, &filename),
	      closedir(thisdir););
    if ( strcmp(filename, ".") && strcmp(filename, "..") )
    { /*printf("%s\n", filename);*/
      count++;
    }
    lcrzo_string_free(filename);
    file=readdir(thisdir);
  }
  ret=closedir(thisdir);
 
  if (pcount!=NULL) *pcount=count;
  return(LCRZO_ERR_OK);
}
#elif defined LCRZODEF_SYSTEM_Windows
{ struct _finddata_t fileinfos;
  lcrzo_int32 count;
  lcrzo_string filename;
  long hFile;
  int ret;
  struct stat st;
  lcrzo_string cleandirname;

  /* verify if directory exist */
  ret=lcrzo_priv_dirname_removelastslash(dirname, &cleandirname);
  if (ret==LCRZO_ERR_OK)
  { ret=lcrzo_priv_filename_stat_get(cleandirname, &st);
  }
  if (ret!=LCRZO_ERR_OK)
  { lcrzo_string_free(cleandirname);
    return(ret);
  }

  /* search the first file */
  ret=lcrzo_string_initm_text(cleandirname, &filename);
  lcrzo_string_free(cleandirname);
  if (ret!=LCRZO_ERR_OK) return(ret);
  lcrzo_er(lcrzo_string_appendm_text("\\*", &filename));
  hFile=_findfirst(filename, &fileinfos);
  lcrzo_string_free(filename);
  if (hFile==-1) return(LCRZO_ERR_FUFINDFIRST);

  /* count files */
  count=0;
  do 
  { if ( strcmp(fileinfos.name, ".") && strcmp(fileinfos.name, "..") )
    { count++;
    }
    ret=_findnext(hFile, &fileinfos);
  }
  while (ret==0);
  lcrzo_err_purge();

  /* close */
  ret=_findclose( hFile );
  if (ret==-1) return(LCRZO_ERR_FUFINDCLOSE);

  /* set output value */
  if (pcount!=NULL) *pcount=count;
  return(LCRZO_ERR_OK);
}
#else
 #error "Unknown value for LCRZODEF_SYSTEM"
#endif

