#include <iostream>
#include <list>
#include <string>
#include <map>

using namespace std;

int main(int argc, char* argv[])
{
        if(argc != 2){
                cout << "Usage: sort_archive archive-file" << endl; 
                return 0;
        }


	FILE *aFile;
	char line[256];

	map<string,string> sortbytitle;
	map<string,string> sortbynumber;

	string title;
	string id;
	
	aFile = fopen (argv[1],"r");
	if (aFile == NULL) 
		printf("Error: Konnte %s nicht oeffnen",argv[1]);
        else 
        {
                while(!feof(aFile))
                {
                        // Hole Zeile aus Crontab
                        fgets (line , 256 , aFile);

			
			char * pch;
			pch = strtok (line,"|");
		
			int col = 0;
			while (pch != NULL)
			{
				//printf ("%s\n",pch);
				if(col == 0)
					title = pch;
				if(col == 1)
					id = pch;
				
				pch = strtok (NULL, " ,.\n");
				
				col++;
			}
			sortbytitle[title] = id;
			sortbynumber[id] = title;
		}
	}
	
	//Ausgabe von sortbytitle
	FILE *oFile;

	oFile = fopen ("/tmp/sortbytitle","w+");
	if (oFile == NULL) 
		printf("Error: Konnte /tmp/sortbytitle nicht anlegen.\n");
        else 
	{
		map<string,string>::iterator i;
		for (i = sortbytitle.begin(); i != sortbytitle.end(); i++)
		{
			const char* ctitle = ((*i).first).c_str();
			const char* cid = ((*i).second).c_str();
			fputs (ctitle,oFile);
			fputs (" - ",oFile);
			fputs (cid,oFile);
			fputs ("\n",oFile);
		
		//	cout << (*i).first << " " << (*i).second << endl;
		}
	}
	fclose(oFile);
	
	//Ausgabe von sortbynumber
	oFile = fopen ("/tmp/sortbynumber","w+");
	if (oFile == NULL) 
		printf("Error: Konnte /tmp/sortbynumber nicht anlegen");
        else 
	{
		map<string,string>::iterator i;
		for (i = sortbynumber.begin(); i != sortbynumber.end(); i++)
		{
			const char* ctitle = ((*i).second).c_str();
			const char* cid = ((*i).first).c_str();
			fputs (cid,oFile);
			fputs (" ",oFile);
			fputs (ctitle,oFile);
			fputs ("\n",oFile);

		//	cout << (*i).first << " " << (*i).second << endl;
		}
	}
	fclose(oFile);
}


