//
//  main.m
//  mulle-plist-fix
//
//  Created by Nat! on 11.02.13.
//  Copyright (c) 2013 Nat!. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "NSPropertyListSerialization+MullePlistReader.h"


static NSStringEncoding   encodings[] =
{
   NSUTF8StringEncoding,
   NSUTF16StringEncoding,
   NSUTF16BigEndianStringEncoding,
   NSUTF16LittleEndianStringEncoding,
   NSMacOSRomanStringEncoding,
   0
};


int main (int argc, const char * argv[])
{
   NSAutoreleasePool      *pool;
   NSData                 *data;
   NSPropertyListFormat   format;
   NSString               *error;
   NSString               *s;
   NSString               *path;
   id                     list;
   NSStringEncoding       *p_encoding;
   NSFileHandle           *handle;
   NSFileManager          *fileManager;
   
   pool = [NSAutoreleasePool new];
   
   if( argc > 1)
   {
      fileManager = [NSFileManager defaultManager];

      path   = [fileManager stringWithFileSystemRepresentation:argv[ 1]
                                                        length:strlen( argv[ 1])];
      handle = [NSFileHandle fileHandleForReadingAtPath:path];
   }
   else
      handle = [NSFileHandle fileHandleWithStandardInput];

   data = [handle readDataToEndOfFile];
   if( ! [data length])
   {
      fprintf( stderr, "No data to convert\n");
      return( -1);
   }
   
   list = [NSPropertyListSerialization mullePropertyListFromData:data
                                                mutabilityOption:NSPropertyListImmutable
                                                          format:&format
                                                errorDescription:&error];
   if( ! list)
   {
      fprintf( stderr, "retrying with different encodings...\n");
      
      for( p_encoding = encodings; *p_encoding; p_encoding++)
      {
         s = [[NSString alloc] initWithData:data
                                   encoding:*p_encoding];
         
         list = [NSPropertyListSerialization mullePropertyListFromData:data
                                                      mutabilityOption:NSPropertyListImmutable
                                                                format:&format
                                                      errorDescription:&error];
         
         [s release];
         if( list)
            break;
      }
      
      if( ! list)
      {
         fprintf( stderr, "Conversion of property list failed: %s\n", [error UTF8String]);
         return( -1);;
      }
   }

   printf( "%s", [[list description] UTF8String]);
   return( 0);
}