#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/file.h>

#include "tools.h"

int main(int argc, char **argv)
{
    int fd, size, sleep_time, first, second, diff;
    int from[2], to[2];
    struct flock s1, s2;

    if (argc < 6) {
        fprintf(stderr, "usage %s <file name> <time interval> "
                "<diff> <first data> <second data>\n", argv[0]);
        exit(1);
    }
    fd = open_file(argv[1], 'm');
    size = lseek(fd, 0, SEEK_END);
    lseek(fd, 0, SEEK_SET);

    sleep_time = str2long(argv[2]);
    diff = str2long(argv[3]);
    first = str2long(argv[4]) - 1;
    second = str2long(argv[5]) - 1;

    lock(fd, first * sizeof(from), sizeof(from), &s1);
    lock(fd, second * sizeof(from), sizeof(from), &s2);

    read_data(fd, from, first);
    read_data(fd, to, second);

    sleep(sleep_time);

    modify_data(fd, from, first, -diff);
    modify_data(fd, to, second, diff);

    s1.l_type = F_UNLCK;
    fcntl(fd, F_SETLKW, &s1);

    s2.l_type = F_UNLCK;
    fcntl(fd, F_SETLKW, &s2);

    close(fd);
    return 0;
}
