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


// 38 in, to '-' to end
// File Data:
// Thu Apr 25 13:09:04 2002[210196063] - 128.226.143.124-216.103.185.211 ihl 20 ttl 113 id 61648 offs 1480 MF

#define TMP_FILE "temp_log.txt"
#define MATCH 5000

void PrintUsage()
{
	cout << "USAGE:"<<endl;
	cout << "log_sort.exe in_file out_file"<<endl;
}

int ParseFile(ifstream fin, ofstream fout)
{
	char cBuff[2048];
	int i;

	if(fin.eof() || fout.fail())
	{
		cout << "\nError with files..."<<endl;
		return 0;
	}
	
	do
	{
		fin.getline(cBuff, 2048);
		i = 38; // distance into line for IP start
		while(cBuff[i] != '-')
		{
			fout.put(cBuff[i]);
			i++;
		}

		fout.put('\n');

	}while(!fin.eof());


	return 1;
}

int RemDup(ifstream fin, ofstream fout)
{
	int iMatch = 0;
	char cBuff[1024][256];
	char cBuff2[256];
	int i, j;
	int iHasPrint = 0;

	if(fin.eof() || fout.fail())
	{
		cout << "\nError with files..."<<endl;
		return 0;
	}

	i = 0;
	while(!fin.eof())
	{
		fin.getline(cBuff2, 256);
		iMatch = 0;
		for(j = 0; j< i; j++)
		{
			if(strcmp(cBuff2, cBuff[j]) == 0)
				iMatch++;
		}

		if(iMatch == 0)
		{
			strcpy(cBuff[i], cBuff2);
			i++;
		}
	}

	for(j = 0; j < i; j++)
	{
		cout << cBuff[j]<<endl;
		fout.write(cBuff[j], (int)strlen(cBuff[j]));
		fout.write("\r\n", 2);
	}

	return 1;
}

int main(int argc, char **argv)
{
	ifstream fin;
	ofstream fout;

	if(argc < 2)
	{
		PrintUsage();
		return 0;
	}

	fin.open(argv[1], ios::binary);
	if(fin.fail())
	{
		cout << "Could not open file: \"" << argv[1] <<"\""<<endl; 
		return 0;
	}

	fout.open(TMP_FILE, ios::binary);
	if(fout.fail())
	{
		cout << "Could not open file:\"" << TMP_FILE << "\""<<endl;
		fin.close();
	}

	ParseFile(fin, fout);

	fin.close();
	fout.close();

	fin.open(TMP_FILE, ios::binary);
	if(fin.fail())
	{
		cout << "Could not open file: \"" << TMP_FILE <<"\""<<endl; 
		return 0;
	}

	fout.open(argv[2], ios::binary);
	if(fout.fail())
	{
		cout << "Could not open file:\"" << argv[2] << "\""<<endl;
		fin.close();
	}

	RemDup(fin, fout);

	fout.close();
	fin.close();

	_unlink(TMP_FILE);

	return 0;
}
