#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <err.h>
#include "../lpi.h"

int
main(int argc, char *argv[])
{
    int fd;
    int openFlag;
    int numBytes;
    int i;

    openFlag = O_WRONLY | O_APPEND | O_CREAT;
    if (argc < 3)
        errx(EXIT_FAILURE, "usage: %s filename num-bytes [x]", argv[0]);

    if ((errno = toInt(argv[2], &numBytes)) != 0)
        err(EXIT_FAILURE, "num-bytes");

    if (argc >= 4) {
        if (strcmp(argv[3], "x") == 0)
            openFlag &= ~O_APPEND;
        else
            errx(EXIT_FAILURE, "argv[3] must be x");
    }

    fd = open(argv[1], openFlag, S_IRUSR | S_IWUSR);
    if (fd == -1)
        err(EXIT_FAILURE, "%s", argv[1]);

    for (i = 0; i < numBytes; i++) {
        if (! (openFlag & O_APPEND))
            lseek(fd, 0, SEEK_END);

        write(fd, "b", 1);
    }

    exit(EXIT_FAILURE);
}
