#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSEnumerator.h>
#import <Foundation/NSString.h>
#import <Foundation/NSSet.h>

#import <ctype.h>
#import <string.h>
#import <stdio.h>

void parse_line(NSString* line, NSMutableSet* results) {
   int len = [line length], i;
   const char* buf = [line UTF8String];

   char ch;
   int octet_num = 0;
   NSMutableString* octet = [[NSMutableString alloc] init];
   NSMutableString* ip = [[NSMutableString alloc] init];

   for (i=0; i<len; i++) {
      ch = buf[i];
 
      if (isdigit(ch)) {
         [octet appendFormat: @"%c", ch];
      } else if (ch == '.') {
         [ip appendFormat: @"%@.", octet];
         [octet setString: @""];
         octet_num ++;
      } else {
         if (octet_num == 3 && [octet length] > 0) {
            [ip appendString: octet];
            [results addObject: ip];
            return;
         }
         
         octet_num = 0;
         [octet setString: @""];
         [ip setString: @""];
      }
   }
   
   [octet release];
   [ip release];
}

void parse_file(NSString* file, NSMutableSet* results) {
   NSString* contents = [NSString stringWithContentsOfFile:file];
   NSEnumerator* enumerator = [[contents componentsSeparatedByString:@"\n"] objectEnumerator];
   NSString* line;

   while (line = [enumerator nextObject]) {
      parse_line(line, results);
   }
}

void print_diff(NSString* fname, NSMutableSet* results1, NSSet* results2) {
   NSMutableSet* diff = [results1 mutableCopyWithZone: NULL];
   [diff minusSet: results2];
   
   NSString* ip;
   NSEnumerator* enumerator = [diff objectEnumerator];
   
   printf("Only in %s [", [fname UTF8String]);
   while (ip = [enumerator nextObject]) {
      printf(" '%s'", [ip UTF8String]);
   }
   printf("]\n");
}

int main(int argc, char* argv[]) {
   NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

   NSString* fname1 = [NSString stringWithUTF8String: argv[1]];
   NSString* fname2 = [NSString stringWithUTF8String: argv[2]];

   NSMutableSet* results1 = [[[NSMutableSet alloc] init] autorelease];
   NSMutableSet* results2 = [[[NSMutableSet alloc] init] autorelease];
   
   parse_file(fname1, results1);
   parse_file(fname2, results2);

   print_diff(fname1, results1, results2);
   print_diff(fname2, results2, results1);

   [pool release];
   return 0;
}
