
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <fstream>
#include <iostream>

#include "photos.h"

using namespace std;

void chomp( char* s ) {
	while ( *s ) {
		if ( *s == '\n' ) {
			*s = '\0';
		} else {
			s++;
		}
	}
}

bool read_line( char** color, int* count, FILE* f ) {
	if ( fgets( *color, 63, f ) == NULL ) {
		return false;
	}
	chomp( *color );
	char* n = strchr( *color, ':' );
	if ( n == NULL ) {
		fprintf( stderr, "format error (%s)\n", *color );
		exit(-1);
	}
	*n = '\0';
	n++;
	*count = atoi(n);
	return true;
}

int main( int argc, char** argv ) {
	if ( argc != 3 ) {
		printf("usage: color_dist <id1> <id2>\n");
		return -1;
	}
	int id1 = atoi(argv[1]);
	int id2 = atoi(argv[2]);

	char filename1[1000];
	char filename2[1000];
	sprintf( filename1, DATA_DIR "sorted_histograms/%d.txt", id1 );
	sprintf( filename2, DATA_DIR "sorted_histograms/%d.txt", id2 );

	//ifstream in1(filename1);
	//ifstream in2(filename2);
	FILE* in1 = fopen(filename1,"r");
	FILE* in2 = fopen(filename2,"r");
	if ( in1 == NULL ) {
		fprintf( stderr, "Unable to open %s\n", filename1 );
		return -1;
	}
	if ( in2 == NULL ) {
		fprintf( stderr, "Unable to open %s\n", filename2 );
		return -1;
	}

	double l1_dist = 0;
	double l2_dist = 0.0;
	double linf_dist = 0;

	int x1, x2, diff;
	char color1_buffer[64];
	char color2_buffer[64];
	char *color1 = color1_buffer;
	char *color2 = color2_buffer;
	bool file1 = true;
	bool file2 = true;
	file1 = read_line( &color1, &x1, in1 );
	file2 = read_line( &color2, &x2, in2 );
	while ( file1 && file2 ) {
		int cmp = strcmp( color1, color2 );
		if ( cmp == 0 ) {
			diff = abs(x1-x2);
			file1 = read_line( &color1, &x1, in1 );
			file2 = read_line( &color2, &x2, in2 );
		} else {
			if ( cmp > 0 ) {
				diff = x2;
				file2 = read_line( &color2, &x2, in2 );
			} else {
				diff = x1;
				file1 = read_line( &color1, &x1, in1 );
			}
		}
		l1_dist += diff;
		l2_dist += ((float)diff) * ((float)diff);
		if ( diff > linf_dist ) {
			linf_dist = diff;
		}
	}
	while ( file1 ) {
		diff = x1;
		l1_dist += diff;
		l2_dist += ((float)diff) * ((float)diff);
		if ( diff > linf_dist ) {
			linf_dist = diff;
		}
		file1 = read_line( &color1, &x1, in1 );
	}
	while ( file2 ) {
		diff = x2;
		l1_dist += diff;
		l2_dist += ((float)diff) * ((float)diff);
		if ( diff > linf_dist ) {
				linf_dist = diff;
		}
		file2 = read_line( &color2, &x2, in2 );
	}
	l2_dist = sqrt( l2_dist );
	printf( "L1: %lf\n", l1_dist );
	printf( "L2: %lf\n", l2_dist );
	printf( "Linf: %lf\n", linf_dist );

	//in1.close();
	//in2.close();
	fclose( in1 );
	fclose( in2 );

	return 0;
}

