#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <jpeglib.h>
#include <argtable2.h>
#include <string.h>
#include <math.h>

const char * input_file;
const char * output_file;
const char * filter;
double times;
double percent;

JSAMPARRAY row_pointers = NULL;
JDIMENSION width;
JDIMENSION height;
int num_components;
int quality = 75;
J_COLOR_SPACE color_space;


unsigned char clamp(double val) {
    if (val > 255.0) return 255;
    if (val < 0.0) return 0;
    return (unsigned char)round(val);
}

void negate() {
    if (color_space != JCS_RGB) return;
    for (int y = 0; y < height; y++) {
        JSAMPROW row = row_pointers[y];
        for (int x = 0; x < width; x++) {
            JSAMPROW ptr = &(row[x * 3]);
            ptr[0] = 255 - ptr[0];
            ptr[1] = 255 - ptr[1];
            ptr[2] = 255 - ptr[2];
        }
    }
}

void brightness(double k) {
    if (color_space != JCS_RGB) return;
    double factor = k / 100.0;
    for (int y = 0; y < height; y++) {
        JSAMPROW row = row_pointers[y];
        for (int x = 0; x < width; x++) {
            JSAMPROW ptr = &(row[x * 3]);
            for (int c = 0; c < 3; c++) {
                ptr[c] = clamp((double)ptr[c] + (factor * (double)ptr[c]));
            }
        }
    }
}

void contrast(double t) {
    if (color_space != JCS_RGB) return;
    for (int y = 0; y < height; y++) {
        JSAMPROW row = row_pointers[y];
        for (int x = 0; x < width; x++) {
            JSAMPROW ptr = &(row[x * 3]);
            for (int c = 0; c < 3; c++) {
                ptr[c] = clamp(t * ((double)ptr[c] - 127.0) + 127.0);
            }
        }
    }
}

void sepia() {
    if (color_space != JCS_RGB) return;
    for (int y = 0; y < height; y++) {
        JSAMPROW row = row_pointers[y];
        for (int x = 0; x < width; x++) {
            JSAMPROW ptr = &(row[x * 3]);
            double r = (double)ptr[0];
            double g = (double)ptr[1];
            double b = (double)ptr[2];

            ptr[0] = clamp(0.393 * r + 0.769 * g + 0.189 * b);
            ptr[1] = clamp(0.349 * r + 0.686 * g + 0.168 * b);
            ptr[2] = clamp(0.272 * r + 0.534 * g + 0.131 * b);
        }
    }
}

void abort_(const char * s, ...) {
    va_list args;
    va_start(args, s);
    vfprintf(stderr, s, args);
    fprintf(stderr, "\n");
    va_end(args);
    abort();
}

void read_jpeg_file(const char *filename) {
    struct jpeg_decompress_struct cinfo;
    struct jpeg_error_mgr jerr;
    FILE *infile = fopen(filename, "rb");
    if (!infile) abort_("Error opening input jpeg file %s!", filename);

    cinfo.err = jpeg_std_error(&jerr);
    jpeg_create_decompress(&cinfo);
    jpeg_stdio_src(&cinfo, infile);
    jpeg_read_header(&cinfo, TRUE);
    jpeg_start_decompress(&cinfo);

    width = cinfo.output_width;
    height = cinfo.output_height;
    num_components = cinfo.out_color_components;
    color_space = cinfo.out_color_space;

    row_pointers = (JSAMPARRAY) malloc(sizeof(JSAMPROW) * height);
    for (int y = 0; y < height; y++) {
        row_pointers[y] = (JSAMPROW) malloc(width * num_components);
    }

    while (cinfo.output_scanline < cinfo.image_height) {
        jpeg_read_scanlines(&cinfo, &row_pointers[cinfo.output_scanline], 1);
    }

    jpeg_finish_decompress(&cinfo);
    jpeg_destroy_decompress(&cinfo);
    fclose(infile);
}

void write_jpeg_file(const char *filename) {
    struct jpeg_compress_struct cinfo;
    struct jpeg_error_mgr jerr;
    FILE *outfile = fopen(filename, "wb");
    if (!outfile) abort_("Error opening output jpeg file %s!", filename);

    cinfo.err = jpeg_std_error(&jerr);
    jpeg_create_compress(&cinfo);
    jpeg_stdio_dest(&cinfo, outfile);

    cinfo.image_width = width;
    cinfo.image_height = height;
    cinfo.input_components = num_components;
    cinfo.in_color_space = color_space;
    jpeg_set_defaults(&cinfo);
    jpeg_set_quality(&cinfo, quality, TRUE);

    jpeg_start_compress(&cinfo, TRUE);
    while (cinfo.next_scanline < cinfo.image_height) {
        jpeg_write_scanlines(&cinfo, &row_pointers[cinfo.next_scanline], 1);
    }

    jpeg_finish_compress(&cinfo);
    jpeg_destroy_compress(&cinfo);
    fclose(outfile);

    for (int y = 0; y < height; y++) free(row_pointers[y]);
    free(row_pointers);
}

void process_file() {
    if (strcmp(filter, "negate") == 0) negate();
    else if (strcmp(filter, "brightness") == 0) brightness(percent);
    else if (strcmp(filter, "contrast") == 0) contrast(times);
    else if (strcmp(filter, "sepia") == 0) sepia();
    else printf("Unknown filter: %s\n", filter);
}

int main(int argc, char **argv) {

    struct arg_file *input_file_arg = arg_file1("i", "in-file", "<input>", "Input JPEG File");
    struct arg_file *output_file_arg = arg_file1("o", "out-file", "<output>", "Output JPEG File");
    struct arg_str *filter_arg = arg_str1("f", "filter", "<filter>", "Filter (negate, brightness, contrast, sepia)");
    struct arg_dbl *times_arg = arg_dbl0("t", "times", "<t>", "Contrast multiplier");
    struct arg_dbl *percent_arg = arg_dbl0("p", "percent", "<k>", "Brightness percent");
    struct arg_lit *help = arg_lit0("h", "help", "Print this help and exit");
    struct arg_end *end = arg_end(20);

    void *argtable[] = {input_file_arg, output_file_arg, filter_arg, times_arg, percent_arg, help, end};

    if (arg_nullcheck(argtable) != 0) {
        printf("error: insufficient memory\n");
        return 1;
    }

    int nerrors = arg_parse(argc, argv, argtable);

    if (help->count > 0) {
        printf("Usage: point");
        arg_print_syntax(stdout, argtable, "\n");
        printf("Options:\n");
        arg_print_glossary(stdout, argtable, "  %-25s %s\n");
        arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
        return 0;
    }

    if (nerrors > 0) {
        arg_print_errors(stderr, end, "point");
        printf("Try 'point --help' for more information.\n");
        arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
        return 1;
    }

    input_file = input_file_arg->filename[0];
    output_file = output_file_arg->filename[0];
    filter = filter_arg->sval[0];
    times = (times_arg->count > 0) ? times_arg->dval[0] : 1.0;
    percent = (percent_arg->count > 0) ? percent_arg->dval[0] : 0.0;

    read_jpeg_file(input_file);
    process_file();
    write_jpeg_file(output_file);

    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
    return 0;
}