#include <stdio.h>
#include <stddef.h>
#include "coroutine.h"
#include "generator.h"
#include "asleep.h"
#include "task.h"

#include <dirent.h> 
#include <string.h>
#include <stdlib.h>
#include <time.h>

#define DEMO_STACK_SIZE (8192*sizeof(void *))

void *yield_files(void *param){
    bool domore = true;
    char *path = param;
    DIR *d;
    struct dirent *dir;
    int pathlen = strlen(path);
    d = opendir(path);
    if (d) {
        while (domore && (dir = readdir(d)) != NULL) {
            int blklen = pathlen + 1 + strlen(dir->d_name) + 1;
            char *r = malloc(blklen);
            snprintf(r, blklen, "%s/%s", path, dir->d_name);
            domore = Generator_Yield(r);
            if (domore && dir->d_type == DT_DIR) {
                if (strcmp(dir->d_name, ".") != 0 && strcmp(dir->d_name, "..") != 0) {
                    r = malloc(blklen);
                    snprintf(r, blklen, "%s/%s", path, dir->d_name);
                    domore = yield_files(r);
                    free(r);
                }
            }
        }
        closedir(d);
    }

    return (void *)domore;
}

void *gentest(void *param){
    Generator gen;
    Generator_ctor(&gen, DEMO_STACK_SIZE, yield_files, (char *)param);
    int count = 0;
    while(Generator_Next(&gen, &param)){
        printf("%d) %s\n", count, (char *)param);
        free(param);
        if (++count>16000) break;
    }
    Generator_dtor(&gen);

    return param;
}

int main(int argc, char *argv[]) {
    (void)argc;
    (void)argv;

    Coroutine_Run(DEMO_STACK_SIZE, gentest, "..", NULL);

    return 0;
}
