#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/sysinfo.h>
#include <sys/types.h>
#include <unistd.h>

size_t freadln (char **line, FILE *stream)
{
    char c;
    unsigned int counter = 0;

    fread(&c, 1, 1, stream);
    while ( (c != '\n') && (!feof(stream)) )
    {
        counter += 1;
        (*line) = realloc((*line), counter * sizeof(char));
        (*line)[counter - 1] = c;

        fread(&c, 1, 1, stream);
    }

    counter += 1;
    (*line) = realloc((*line), counter * sizeof(char));
    (*line)[counter - 1] = '\0';

    return counter - 1;
}

char* s_token (char* str, char* sep, int i)
{
    char *s = (char *) strdup(str);
    char *ret = strtok(s, sep);

    i--;
    while (i > 0){
        ret = strtok(NULL, sep);
        i--;
    }

    if (!ret) return NULL;

    return ret;
}

int main(int ac, char *av[])
{
    FILE *proc_time = NULL;
    char *line = NULL;
    char stat_file[80];

    memset(stat_file, 0, sizeof(stat_file));

    if ( ac < 2 )
    {
        printf("Error: at least one argument is needed!\n");
        exit(1);
    }

    unsigned int pid = atoi(av[1]);

    snprintf(stat_file, sizeof(stat_file), "/proc/%d/stat", pid);
    proc_time = fopen(stat_file, "r");
    if ( !proc_time )
    {
        printf("Some strange error occurred while opening the file!\n");
        exit(1);
    }

    freadln(&line, proc_time);
    char *jiff_from_boot_str = s_token(line, " ", 22);
    long int jiff_from_boot = atoi(jiff_from_boot_str);

    printf("Process %d started at: %d jiffies\n", pid, jiff_from_boot);

    struct sysinfo sys_inf;
    sysinfo(&sys_inf);

    printf("Seconds since boot: %ld\n", sys_inf.uptime);

    long int jiffies_per_sec = sysconf(_SC_CLK_TCK);

    printf("Jiffies per second: %ld\n", jiffies_per_sec);

    long int proc_rtime = sys_inf.uptime - jiff_from_boot/jiffies_per_sec;

    printf("Process running time: %ld secs\n", proc_rtime);

    return 0;
}


