#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <err.h>
#include <string.h>

#include "tools.h"

void *xmalloc(int size)
{
    void *p;

    p = malloc(size);
    if (!p) {
        fprintf(stderr, "Could not allocate dynamic memory\n");
        exit(1);
    }
    return p;
}

long str2long(const char *str)
{
    int n;
    char *endptr;

    n = strtol(str, &endptr, 10);
    if (errno == ERANGE || !*str || *endptr)
        err(1, str);

    return n;
}

void check_arguments(int argc, const char *program_name)
{
    if (argc < 2) {
        fprintf(stderr, "usage %s <file name>\n", program_name);
        exit(1);
    }
}

int open_file(const char *file_path, int mode)
{
    int fd;

    switch (mode) {
        case 'w':
            fd = open(file_path, O_WRONLY|O_CREAT|O_TRUNC, 0666);
            break;
        case 'e':
            fd = open(file_path, O_WRONLY|O_CREAT|O_EXCL, 0666);
            break;
        case 'm':
            fd = open(file_path, O_RDWR, 0666);
            break;
        case 'r':
            fd = open(file_path, O_RDONLY);
            break;
    }
    if (fd == -1)
        err(1, file_path);

    return fd;
}

void read_data(int fd, int *data, int start)
{
    int rc;

    lseek(fd, start * sizeof(data), SEEK_SET);
    rc = read(fd, data, sizeof(data));
    if (rc != sizeof(data)) {
        fprintf(stderr, "wrong data read\n");
        exit(1);
    }
}

void modify_data(int fd, int *data, int start, int diff)
{
    int original = data[1];

    lseek(fd, start * sizeof(data) + sizeof(data[0]), SEEK_SET);
    data[1] += diff;
    write(fd, &data[1], sizeof(data[1]));
    printf("%d: %d -> %d\n", data[0], original, data[1]);
}

void lock(int fd, int start, int len, struct flock *s)
{
    s->l_type = F_WRLCK;
    s->l_whence = SEEK_SET;
    s->l_start = start;
    s->l_len = len;
    fcntl(fd, F_SETLKW, s);
}

