#include "util.h"

int empty(int element) {
    return element == -1 ? 1 : 0;
}

void primesieve(int *array, int limit) {
    /* generate array with numbers */
    for (int i = 0; i < limit; i++)
        array[i] = i + 1;

    /* filter non primes */
    for (int i = 0; i < limit; i++) {
        /* skip 0 / 1 */
        if (array[i] == 0 || array[i] == 1)
            continue;
        /* skip already replaced instances */
        if (empty(array[i]))
            continue;
        /* check rest of array for coprimeness */
        for (int p = i + 1; p < limit - i + 1; p++) {
            /* skip already replaces instances */
            if (empty(array[p]))
                continue;
            /* check coprimeness of values in current iteration */
            if (array[p] % array[i] == 0)
                array[p] = -1;
        }
    }
}

void printintarray(int *array, int arrayc) {
    putnumber(array[0]);
    for (int i = 1; i < arrayc; i++) {
        if (empty(array[i]))
            continue;
	//putchar(' ');
        putnumber(array[i]);
    }
    //putchar('\n');
}

//int main(int argc, char **argv) {
int main(void) {
/*
    if (argc < 2) {
	puts("usage: ps limit\n");
    }
*/
    puts("hello world, this is primesieve\n");

    int limit = 100;
    //sscanf(argv[1], "%i", &limit);
    int primes[limit];

    // initiate the sieving
    primesieve(primes, limit);

    // print results
    printintarray(primes, limit);

    return 0;
}
