/*
irssi2mirc - Copyright (c) 2003 Teemu Toivola <tst at iki dot fi>

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 dated June, 1991.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program;  if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave., Cambridge, MA 02139, USA.
*/

/*

	gcc -O2 irssi2mirc.c -o irssi2mirc

*/

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

int main(int argc, char *argv[])
{
	FILE *log;
	char logline[1024], line[1024], time[10], nick[64], temp[1024];
	
	if ((argc == 1) || (argc >= 3)) {
		printf("irssi2mirc 1.0 by Teemu Toivola <tst@iki.fi>\n\n");
		printf("Usage: %s <irssilog>\n",argv[0]); 
		exit(0);
	}

	if ((log=fopen(argv[1],"r"))==NULL) {
		fprintf(stderr,"\nError:\nUnable to open logfile \"%s\" for reading.\n\n",argv[1]);
		exit(1);
	}
	
	while (fgets(logline,1024,log)!=NULL) {
		if (logline[2]==':') {
		
			/* normal line */
			if (logline[6]=='<') {
				sscanf(logline,"%s",time);
				sscanf(logline+7,"%[^>]s",nick);
				strcpy(line,logline+9+strlen(nick));
				printf("[%s] <%s> %s",time,nick+1,line);

			/* line containing some action */
			} else if (logline[6]=='-' && logline[7]=='!' && logline[8]=='-') {
				sscanf(logline,"%s",time);
				sscanf(logline+9,"%s",nick);
				
				/* join */
				if (strstr(logline,"has joined")) {
					sscanf(logline+12+strlen(nick),"%[^]]s",temp);
					printf("[%s] *** %s (%s) has joined the channel\n",time,nick,temp);
				
				/* quit */
				} else if (strstr(logline,"has quit")) {
					printf("[%s] *** %s has quit IRC\n",time,nick);
				
				/* topic change */	
				} else if (strstr(logline,"changed the topic of")) {
					strcpy(line,strstr(logline," to: ")+5);
					printf("[%s] *** %s changes topic to %s",time,nick,line);

				/* someone gets kicked */
				} else if (strstr(logline,"was kicked from")) {
					sscanf(logline+27+strlen(nick),"%[^ ]s",temp);
					sscanf(logline+31+strlen(nick)+strlen(temp),"%s",line);
					sscanf(logline+33+strlen(nick)+strlen(temp)+strlen(line),"%[^]]s",temp);
					printf("[%s] *** %s was kicked by %s (%s)\n",time,nick,line,temp);
				}

			/* /me action */
			} else if (logline[7]=='*') {
				sscanf(logline,"%s",time);
				sscanf(logline+9,"%s",nick);
				strcpy(line,logline+10+strlen(nick));
				printf("[%s] * %s %s",time,nick,line);

			}
		}
	}

	fclose(log);
	return 0;
}
