File: AdunIOManager.m

package info (click to toggle)
adun.app 0.8.2-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 6,824 kB
  • ctags: 713
  • sloc: objc: 49,683; ansic: 4,680; sh: 523; python: 79; makefile: 67; cpp: 33
file content (1169 lines) | stat: -rwxr-xr-x 32,308 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
/*
   Project: Adun

   Copyright (C) 2005 Michael Johnston & Jordi Villa-Freixa

   Author: Michael Johnston

   This application 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; either
   version 2 of the License, or (at your option) any later version.

   This application 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
   Library General Public License for more details.

   You should have received a copy of the GNU General Public
   License along with this library; if not, write to the Free
   Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA.
*/
#include "AdunKernel/AdunIOManager.h"
#include "AdunKernel/AdunDataSource.h"

static id ioManager;

@implementation AdIOManager

/*
 * Connecting to and disconnecting from the local
 * AdServer instance
 */

- (BOOL) connectToServer: (NSError**) error;
{
	NSDebugLLog(@"Server", 
		@"Server debug - Attempting to  connecting to AdServer using message ports");

	serverConnection = [NSConnection connectionWithRegisteredName: @"AdunServer" 
				host: nil];
	
	if(serverConnection == nil)
	{
		NSDebugLLog(@"Server",
			@"Server debug - Unable to find AdunServer on message ports.");
		NSDebugLLog(@"Server", 
			@"Server debug - Checking for a distributed computing enabled server");
		serverConnection = [NSConnection connectionWithRegisteredName: @"AdunServer" 
				host: nil 
				usingNameServer: [NSSocketPortNameServer sharedInstance]];
	}

	if(serverConnection != nil)
	{
		[serverConnection retain];
		serverProxy = [[serverConnection rootProxy] retain];
	
		NSDebugLLog(@"Server", @"Server debug - Connected to server");
		NSDebugLLog(@"Server" ,
			@"Server debug - Stats are %@", 
			[[serverProxy connectionForProxy] statistics]);

		//supply interface using an NSProtocolChecker
	
		checkerInterface = [NSProtocolChecker protocolCheckerWithTarget: self 
						protocol: @protocol(AdCommandInterface)];
		[checkerInterface retain];
		[serverProxy useInterface: checkerInterface 
			forProcess:  [[NSProcessInfo processInfo] processIdentifier]];
		return YES;
	}
	else
	{
		*error = AdCreateError(AdunCoreErrorDomain,
				AdCoreConnectionError,
				@"Unable to connect to server",
				@"If the program is being run from the server this error\
				 is fatal.",
				@"Check the server is still running.\n \
				If it is send the program logs and the server logs to the Adun developers");

		return NO;
	}	
}


- (void) closeConnection: (NSError*) error
{
	NSDebugLLog(@"Server", @"Server debug - Closing connection to server. Statistics are %@", 
			[[serverProxy connectionForProxy] statistics]);
	NSDebugLLog(@"Server", @"Server debug - Connection %@", [serverProxy connectionForProxy]);
	[serverProxy closeConnectionForProcess: [[NSProcessInfo processInfo] processIdentifier]
			error: error];
	[serverProxy release];
	[serverConnection invalidate];
	[serverConnection release];
	[checkerInterface release];
	serverProxy = nil;
}

- (void) acceptRequests
{
	int pid;

	if(serverConnection != nil)
	{
		pid = [[NSProcessInfo processInfo] processIdentifier];
		[serverProxy acceptingRequests: pid];
	}
}

- (void) sendControllerResults: (NSArray*) results
{
	if(serverConnection != nil)
	{
		[serverProxy controllerData: results 
			forProcess: [[NSProcessInfo processInfo] processIdentifier]];
	}
	else
		NSWarnLog(@"Can't send controller results - Not connected to an AdunServer instance");
}

- (BOOL) isConnected
{
	if(serverConnection != nil)
		return YES;
	else
		return NO;
}

/*
 * Creation
 */

+ (id) appIOManager
{
	if(ioManager == nil)
		ioManager = [AdIOManager new];
	return ioManager;
}

- (id) init
{
	NSMutableDictionary *defaults = [NSMutableDictionary dictionary];

	if(ioManager != nil)
		return ioManager;

	if((self = [super init]))
	{
		if(ioManager == nil)
			ioManager = self;

		fileManager = [NSFileManager defaultManager];
		fileStreams = [NSMutableDictionary new];
		[fileStreams setObject: [NSValue valueWithPointer: stdout]
				forKey: @"Standard"];
		[fileStreams setObject: [NSValue valueWithPointer: stderr] 
				forKey: @"Error"];
		simulationData = nil;		
		outputDir = controllerOutputDir = nil;
		adunDir = controllerDir = extensionDir = pluginDir = nil;
		logFile = errorFile = nil;
		simulatorTemplate = nil;
		externalObjects = nil;
		adunInfo = [NSProcessInfo processInfo];
		runMode = AdCoreUnknownRunMode;
		processedArgs = NO;
		validArgs = [[NSArray alloc] initWithObjects:
				@"-RunMode",
				@"-Template",
				@"-SimulationOutputDir",
				@"-ControllerOutputDir",
				@"-ExternalObjects", 
				nil];

		//Setup defaults
		[defaults setObject: @"AdunCore.log" forKey: @"LogFile"];
		[defaults setObject: @"AdunCore.errors" forKey: @"ErrorFile"];
		[defaults setObject: [NSNumber numberWithBool: YES] forKey: @"RedirectOutput"];
		[defaults setObject: [NSNumber numberWithBool: YES] forKey: @"CreateLogFiles"];
		[defaults setObject: NSHomeDirectory() forKey: @"ProgramDirectoryLocation"];
		[[NSUserDefaults standardUserDefaults] registerDefaults:defaults];
		[[NSUserDefaults standardUserDefaults] synchronize];
	}

	return self;
}

- (void) dealloc
{
	[self closeAllStreams];
	[fileStreams release];
	if(serverProxy != nil)
		[self closeConnection: nil];

	[logFile release];
	[errorFile release];
	[adunDir release];
	[controllerDir release];
	[extensionDir release];
	[pluginDir release];
		
	[outputDir release];
	[controllerOutputDir release];
	[validArgs release];

	[simulationData release];
	[writeModeStorage release];
	
	[simulatorTemplate release];
	[externalObjects release];

	ioManager = nil;
	[super dealloc];
}

- (BOOL) processCommandLine: (NSError**) error
{
	NSMutableArray* arguments, *invalidArgs;
	id value;
	NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];

	if(processedArgs == YES)
		return YES;

	arguments = [[[NSProcessInfo processInfo] arguments] mutableCopy];
	invalidArgs = [NSMutableArray array];

	[arguments removeObjectAtIndex: 0];

	//FIXME: Check all args are valid
	/*argumentEnum = [processedArgs keyEnumerator];		
	while(argument = [argumentEnum nextObject])
		if(![validArgs containsObject: argument])
			[invalidArgs addObject: argument];

	if([invalidArgs count] > 0)
	{
		*error = AdCreateError(AdunCoreErrorDomain,
				AdCoreArgumentsError,
				@"Invalid arguements detected",
				[NSString stringWithFormat: @"The following arguements are not supported - %@", invalidArgs],
				@"Remove these arguements from the command line");
		return NO;
	}*/

	/*
	 * Check if the run mode is specified.
	 * If its not default to AdCoreCommandLineRunMode.
	 * If it is check that its CommandLine or Server.
	 * If its neither of these set an error.
	 */
	if((value = [userDefaults stringForKey: @"RunMode"]) != nil)
	{
		if([value isEqual: @"CommandLine"])
		{
			GSPrintf(stdout, @"RunMode == CommandLine\n");
			runMode = AdCoreCommandLineRunMode;
		}	
		else if([value isEqual: @"Server"])
		{
			GSPrintf(stdout, @"RunMode == Server\n");
			runMode = AdCoreServerRunMode;
		}	
		else
		{
			*error = AdCreateError(AdunCoreErrorDomain,
				AdCoreArgumentsError,
				@"Invalid arguement detected",
				[NSString stringWithFormat: @"Invalid value for RunMode supplies - %@", value],
				@"Type 'AdunCore' without arguments to see the valid values");
			return NO;	
		}
	}
	else	
	{
		GSPrintf(stdout, @"RunMode not explicitly specified - ");
		GSPrintf(stdout, @"Defaulting to command line\n");
		runMode = AdCoreCommandLineRunMode;
	}	

	/*
	 * If the run mode is AdCoreCommandLineRunMode 
	 * then a template must be supplied. 
	 */
	if(runMode == AdCoreCommandLineRunMode)
	{
		if((value = [userDefaults stringForKey: @"Template"]) == nil)
		{
			*error = AdCreateError(AdunCoreErrorDomain,
				AdCoreArgumentsError,
				@"Missing required arguement",
			 	@"Template arguement required when running from command line",
				@"Type 'AdunCore' for arguement help.");
			return NO;	
		}	
	}

	fflush(stdout);
	processedArgs = YES;
	
	return YES;
}

- (AdCoreRunMode) runMode
{
	return runMode;
}

/*
 * Setup
 */

/**
Checks if path is absolute. If it is  this method returns it.
If its not the last path component is extracted and a new path
is created using the current directory.
*/
- (NSString*) _fixFilePath: (NSString*) path
{
	if(![path isAbsolutePath])
	{
		path = [path lastPathComponent];
		path = [[[NSFileManager defaultManager] 
				currentDirectoryPath] 
				stringByAppendingPathComponent: path];
	}

	return path;
}

- (BOOL) createLogFiles: (NSError**) error
{
	NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];

	//Only create the log files if requested to do so.
	if([userDefaults boolForKey: @"CreateLogFiles"] == NO)
	{
		GSPrintf(stdout, @"Log file creation supressed\n");
		return YES;
	}	

	logFile = [[NSUserDefaults standardUserDefaults] stringForKey: @"LogFile"];
	logFile = [self _fixFilePath: logFile];
	[logFile retain];

	if(![[NSFileManager defaultManager] isWritableFileAtPath:
		 [logFile stringByDeletingLastPathComponent]])
	{
		[logFile release];
		logFile = [[userDefaults 
				volatileDomainForName: NSRegistrationDomain]
				valueForKey:@"LogFile"];
		[logFile retain];		
		NSWarnLog(@"Invalid value for user default 'LogFile' (%@). The specificed directory is not writable",
			logFile);
		NSWarnLog(@"Switching to registered default %@", logFile);
		if(![[NSFileManager defaultManager] 
			isWritableFileAtPath:
			 [logFile stringByDeletingLastPathComponent]])
		{
			*error = AdCreateError(AdunCoreErrorDomain,
					AdCoreLogFileError,
				 	[NSString stringWithFormat: 
						@"Default log file (%@) not writable.", logFile],
					@"This error may also indicate that a user supplied value for the LogFile default is invalid",
					@"Check the write permissions on the adun/ directory.");
			return NO;		
		}
	} 
	GSPrintf(stdout, @"Log file is %@\n", logFile);
	fflush(stdout);

	errorFile = [[NSUserDefaults standardUserDefaults] stringForKey: @"ErrorFile"];
	errorFile = [self _fixFilePath: errorFile];
	[errorFile retain];
	if(![[NSFileManager defaultManager] isWritableFileAtPath:
		 [errorFile stringByDeletingLastPathComponent]])
	{
		[errorFile release];
		errorFile = [[userDefaults
				volatileDomainForName: NSRegistrationDomain]
				valueForKey:@"ErrorFile"];
		[errorFile retain];		
		NSWarnLog(@"Invalid value for user default 'ErrorFile' (%@). The specificed directory is not writable", 
			errorFile);
		NSWarnLog(@"Switching to registered default %@", errorFile);
		if(![[NSFileManager defaultManager] 
			isWritableFileAtPath:
			 [errorFile stringByDeletingLastPathComponent]])
		{
			*error = AdCreateError(AdunCoreErrorDomain,
					AdCoreLogFileError,
				 	@"Default error file (%@) not writable.",
					@"This error may also indicate that a user supplied value for the ErrorFile default is invalid",
					@"Check the write permissions on the adun/ directory.");
			return NO;		
		}
	} 

	GSPrintf(stdout, @"Error file is %@\n", errorFile);
	fflush(stderr);
	freopen([errorFile cString], "w", stderr);
	freopen([logFile cString], "w", stdout);

	return YES;
}

/**
Check directory sets an error if a file is in the way of the directory.
It returns NO if the directory does not exist
*/
- (BOOL) _checkDirectory: (NSString*) directoryPath error: (NSError**) error
{
	BOOL isDir;

	if([fileManager fileExistsAtPath: directoryPath isDirectory: &isDir])
	{
		if(!isDir)
		{
			*error = AdCreateError(AdunCoreErrorDomain,
				AdCoreDirectoryStructureError,
				[NSString stringWithFormat: 
				@"A non-directory file exists at %@", directoryPath],
				@"The required directory cannot be created as the file is in the way.",
				@"Move or remove the file");

			return NO;
		}

		return YES;
	}

	return NO;
}

- (BOOL) _createDirectory: (NSString*) directoryPath error: (NSError**) error

{
	if(![fileManager createDirectoryAtPath: directoryPath
		 attributes: nil])
	{

		*error = AdCreateError(AdunCoreErrorDomain,
				AdCoreDirectoryStructureError,
				[NSString stringWithFormat: 
					@"Unable to create missing directory %@", directoryPath],
				@"This is probably because the containing directory is not writable",
				@"Change the permissions of the containing directory to allow file creation");

		return NO;
	}
	
	NSWarnLog(@"Created missing directory %@", directoryPath);
	
	return YES;
}

- (BOOL) checkProgramDirectories: (NSError**) error
{
	NSArray* directoryArray;
	NSEnumerator* directoryEnum;
	NSString* currentDirectory;
	id directory;

//This should perhaps be checking if for FREEBSD
//Im not sure what the cause of the case insenstive filenames is.
#if __FREEBSD__	
	adunDir = [[[NSUserDefaults standardUserDefaults] 
			stringForKey: @"ProgramDirectoryLocation"]
			stringByAppendingPathComponent: @".adun"];
#else			
	adunDir = [[[NSUserDefaults standardUserDefaults] 
			stringForKey: @"ProgramDirectoryLocation"]
			stringByAppendingPathComponent: @"adun"];	
#endif					
	
	pluginDir = [adunDir stringByAppendingPathComponent: @"Plugins"];
	controllerDir = [pluginDir stringByAppendingPathComponent: @"Controllers"];
	extensionDir = [pluginDir stringByAppendingPathComponent: @"Extensions"];
	
	[adunDir retain];
	[pluginDir retain];
	[controllerDir retain];
	[extensionDir retain];
	
	directoryArray = [NSArray arrayWithObjects: 
				adunDir,
				pluginDir,
				controllerDir,
				extensionDir,
				nil];
	
	/*
	 * Check program directory exists and is writable.
	 * Check Plugins directory exists and is writable.
	 * Check Plugin/Controllers directory exists and is writable.
	 * Check Plugin/Extensions directory exists and is writable.
	 *
	 * If anything is missing create it. If we cant create it set an error.
	 */
	
	directoryEnum = [directoryArray objectEnumerator];
	while((directory = [directoryEnum nextObject]))
		if(![self _checkDirectory: directory error: error])
		{
			/*
			 * If checkDirectory:error set an error we return immediately..
			 * Otherwise we try to create the missing directory.
			 */

			if(*error != nil)
				return NO;

			if(![self _createDirectory: directory error: error])
				return NO;
		}		

	//Check the current working directory is accessible & writable
	//if not fall back to adun/
	currentDirectory = [[NSFileManager defaultManager] currentDirectoryPath];
	if(currentDirectory == nil ||
		![[NSFileManager defaultManager] isWritableFileAtPath: currentDirectory] )
	{
		NSWarnLog(@"Current directory is not accessible. Changing to %@", adunDir);
		[[NSFileManager defaultManager] 
			changeCurrentDirectoryPath: adunDir];
			
	}	
				
	GSPrintf(stdout, @"Adun Directory: %@\n", adunDir);
	GSPrintf(stdout, @"Plugin Directory: %@\n", pluginDir);

	return YES;
}

/* 
 * Loading of simulation data
 */

- (BOOL) _loadServerData: (NSError**) error
{
	if(![self isConnected])
	{
		/*
		 * An external object should detect if we are in 
		 * AdCoreServerRunMode and the connection state before this 
		 * calling this method. Hence we could be here due to a 
		 * programmatic error.
		 *
		 * However it is also possible the server crashed after the connection
		 * was made. Therefore we set an error instead of raising
		 * an exception.
		 */
		*error = AdCreateError(AdunCoreErrorDomain,
				AdCoreInvalidTemplateError,
				@"Attempt to retrieve server data failed",
				@"Program not connected to server and in AdCoreServerRunMode.",
				@"This is possibly due to a server crash. However it could also indicate a bug in the program.");	
		return NO;
	}

	GSPrintf(stdout, @"Retrieving data from the server.\n");
	
	simulatorTemplate = [serverProxy templateForProcess: 
				[[NSProcessInfo processInfo] processIdentifier]];			
	externalObjects = [serverProxy externalObjectsForProcess: 
				[[NSProcessInfo processInfo] processIdentifier]];
	
	if(simulatorTemplate == nil)	
	{
		*error = AdCreateError(AdunCoreErrorDomain,
				AdCoreInvalidTemplateError,
				@"Error loading template",
				@"Server returned nil for template.", 
				@"Notify the developers of the error sending the template used to create this simulation.");	
		return NO;
	}
	
	if(externalObjects == nil || [externalObjects count] == 0)	
	{
		*error = AdCreateError(AdunCoreErrorDomain,
				AdCoreInvalidTemplateError,
				@"Error retrieving simulation object",
				@"The server did not supply any data for the simulation",
				@"Notify the developers of the error sending the template used to create this simulation.");	
		return NO;
	}

	[simulatorTemplate retain];
	[externalObjects retain];

	return YES;
}

- (BOOL) _loadCommandLineData: (NSError**) error
{
	NSString* templateFile;
	NSDictionary* dict;
	NSMutableDictionary* temp;
	NSEnumerator* keyEnum;
	id key, object;
	NSError* anError;

	GSPrintf(stdout, @"Retrieving data from the command line.\n");

	//Unarchive data in template file
	templateFile = [[NSUserDefaults standardUserDefaults]
			stringForKey: @"Template"];
	simulatorTemplate = [NSMutableDictionary dictionaryWithContentsOfFile: templateFile];
	//Check that it was unarchived correctly.
	//Further template checks will be performed by an AdTemplateProcessor object.
	if(simulatorTemplate == nil)
	{
		*error = AdCreateError(AdunCoreErrorDomain,
				AdCoreInvalidTemplateError,
				@"Error loading template",
				[NSString stringWithFormat:
					@"Unable to retrieve template from specified file %@", 
					templateFile],
				@"Check the specified file exists and contains a valid template object");	
		
		return NO;
	}
	else
		[simulatorTemplate retain];

	//Read in command line external objects declarations

	anError = nil;
	temp = nil;
	if((dict = [[NSUserDefaults standardUserDefaults] dictionaryForKey: @"ExternalObjects"]) != nil)
	{
		keyEnum = [dict keyEnumerator];
		temp = [NSMutableDictionary dictionary];
		while((key = [keyEnum nextObject]))
		{
			object = [NSKeyedUnarchiver unarchiveObjectWithFile: 
					[dict objectForKey: key]];
			if(object == nil)
			{
				anError = AdCreateError(AdunCoreErrorDomain,
						AdCoreInvalidTemplateError,
						@"Error processing command line objects",
						[NSString stringWithFormat:
							@"Unable to retrieve object from file %@", 
							[dict objectForKey: key]],
						@"Check the specified file exists and contains a valid object");	
				break;
			}
			[temp setObject: object
				forKey: key];
		}
		
		[externalObjects release];
		externalObjects = [temp copy];
	}

	if(anError != nil)
	{
		*error = anError;
		return NO;
	}	
	else
		return YES;	
}

- (BOOL) loadData: (NSError**) error
{
	if(![self processCommandLine: error])
		return NO;

	if(runMode == AdCoreCommandLineRunMode)
		return [self _loadCommandLineData: error];
	else if(runMode == AdCoreServerRunMode)
		return [self _loadServerData: error];
	
	/*
	 * The run mode is still AdCoreUnknownRunMode
	 * This should not happen since processCommandLine:
	 * should set the run mode to one of these two values.
	 * If we are here its due to a bug so raise an exception.
	 */

	 [NSException raise: NSInternalInconsistencyException
		format: @"Bug - Program in AdCoreUnknownRunMode when it should not be."];
}

- (void) setSimulationReferences: (NSDictionary*) inputObjects
{
	NSEnumerator* dataEnum, *keyEnum;
	NSMutableDictionary* templateCopy, *objectReferences;
	id object, key;

	//Set simulation input references
	dataEnum = [inputObjects objectEnumerator];
	while((object = [dataEnum nextObject]))
		if([object isKindOfClass: [AdModelObject class]])
			[simulationData addInputReferenceToObject: object];

	//We need to update the external objects section
	//since it may be empty or have been overridden from the command line
	//If the object doesnt respond to identification we cant add it
	objectReferences = [NSMutableDictionary dictionary];
	keyEnum = [inputObjects keyEnumerator];
	while((key = [keyEnum nextObject]))
	{
		object = [inputObjects objectForKey: key];
		if([object isKindOfClass: [AdModelObject class]])
			[objectReferences setObject: [object identification]
				forKey: key];
	}

	templateCopy = [[simulatorTemplate mutableCopy] autorelease];
	[templateCopy setObject: objectReferences forKey: @"externalObjects"];

	//Add the simulation template to the metadata
	[simulationData setValue: templateCopy
		forMetadataKey: @"Simulation Options"
		inDomain: AdSystemMetadataDomain];

	[NSKeyedArchiver archiveRootObject: simulationData
		toFile: [outputDir stringByAppendingPathComponent: 
			[simulationData identification]]];

	//Send the simulation data object to the interface
	if([self isConnected])
		[serverProxy simulationData: simulationData
			forProcess: [[NSProcessInfo processInfo] processIdentifier]];
}

/*
 * Output directories
 */

- (BOOL) _createSimulationOutputFiles: (NSError**) error
{
	BOOL success;
	NSString* ident, *dataDirectory, *contents, *name, *link;
	id newLocation;
	AdFileSystemSimulationStorage* readModeStorage;

	//Get simulation data name
	if([simulatorTemplate objectForKey: @"metadata"] != nil)
		name = [[simulatorTemplate objectForKey: @"metadata"]
				objectForKey: @"simulationName"];
	else			
		name = @"output";

	simulationData = [AdSimulationData new];
	[simulationData setValue: name
		forMetadataKey: @"Name"];
	ident = [simulationData identification];

	[NSKeyedArchiver archiveRootObject: simulationData
		toFile: [outputDir stringByAppendingPathComponent: ident]];

	//Create the data directory
	dataDirectory = [outputDir stringByAppendingPathComponent: 
				[NSString stringWithFormat: @"%@_Data", ident]];

	writeModeStorage = [[AdFileSystemSimulationStorage alloc]
				initSimulationStorageAtPath: dataDirectory
				mode: AdSimulationStorageWriteMode
				error: error];
	readModeStorage = [[AdFileSystemSimulationStorage alloc]
			initForReadingSimulationDataAtPath: dataDirectory];
	[simulationData setDataStorage: readModeStorage];
	
	//To aid debugging etc. create a link to the dataDirectory,
	link = [outputDir stringByAppendingPathComponent: name];
	NSDebugLLog(@"AdIOManager", @"Adding link %@", link);
	if([[NSFileManager defaultManager] fileExistsAtPath: link])
	{
		NSDebugLLog(@"AdIOManager", @"Detected link present with same name");
		success = [[NSFileManager defaultManager] 
				removeFileAtPath: link 
				handler: nil];
		if(!success)
			NSWarnLog(@"Unable to remove link - %@", link);
	}		

	if(![[NSFileManager defaultManager] createSymbolicLinkAtPath: link
		pathContent: dataDirectory])
	{
		NSWarnLog(@"Failed to create link to simulation data directory %@", 
			dataDirectory);
	}	

	/**
	 * We redirect the log file output if RedirectOutput is YES.
	 * However before doing so we must check if log files were created
	 * in the first place. If they were not we dont do anything.
	*/

	if([[NSUserDefaults standardUserDefaults] 
		boolForKey: @"CreateLogFiles"] == YES)
	{
		if([[NSUserDefaults standardUserDefaults] 
			boolForKey: @"RedirectOutput"])
		{
			GSPrintf(stdout, 
				@"Attempting to redirect log files to %@\n",
				dataDirectory);
		
			//Move LogFile
			fflush(stdout);
			newLocation = [dataDirectory stringByAppendingPathComponent: 
					[logFile lastPathComponent]];
			if(![[NSFileManager defaultManager] isWritableFileAtPath:
				 [newLocation stringByDeletingLastPathComponent]])
			{
				NSWarnLog(@"Cannot redirect %@ to %@.", logFile, dataDirectory);
			}
			else
			{
				/*
				 * movePath:toPath:handler doesnt work - may have something to
				 * do with the fact that oldLogFile is stderr when we try to move it.
				 * Work around by reading in old file and writing to the new one.
				 */
				contents = [NSString stringWithContentsOfFile: logFile];
				freopen([newLocation cString], "w", stdout);
				GSPrintf(stdout, @"%@\n", contents);
				[[NSFileManager defaultManager] removeFileAtPath: logFile
					handler: nil];
				[logFile release];	
				logFile = [newLocation retain];	
				GSPrintf(stdout, @"Standard log redirected to %@\n", dataDirectory);
			}

			//Move ErrorFile
			fflush(stderr);

			newLocation = [dataDirectory stringByAppendingPathComponent:	
					[errorFile lastPathComponent]];
			if(![[NSFileManager defaultManager] isWritableFileAtPath:
				 [newLocation stringByDeletingLastPathComponent]])
			{
				NSWarnLog(@"Cannot redirect %@ to %@,", errorFile, dataDirectory);
			}
			else
			{
				/*
				 * movePath:toPath:handler doesnt work - may have something to
				 * do with the fact that oldLogFile is stderr when we try to move it.
				 * Work around by reading in old file and writing to the new one.
				 */
				contents = [NSString stringWithContentsOfFile: errorFile];
				freopen([newLocation cString], "w", stderr);
				GSPrintf(stderr, @"%@\n", contents);
				[[NSFileManager defaultManager]
					removeFileAtPath: errorFile
					handler: nil];
				[errorFile release];	
				errorFile = [newLocation retain];	
				GSPrintf(stdout, @"Error log redirected to %@\n", dataDirectory);
			}
		}
	}	

	fflush(stderr);
	fflush(stdout);

	return YES;
}

- (BOOL) _createSimulationOutputDirectory: (NSError**) error
{
	
	outputDir = [[NSUserDefaults standardUserDefaults] 
			stringForKey: @"SimulationOutputDir"];
	if(outputDir == nil)
	{
		outputDir = [[fileManager currentDirectoryPath] 
				stringByAppendingPathComponent: @"SimulationOutput"];
		NSWarnLog(@"Simulation output directory not specified. Defaulting to %@", outputDir);		
	}
	
	[outputDir retain];
	if(![self _checkDirectory: outputDir error: error])
	{
		/*
		 * If checkDirectory:error set an error we return immediately..
		 * Otherwise we try to create the missing directory.
		 */

		if(*error != nil)
			return NO;

		if(![self _createDirectory: outputDir error: error])
			return NO;
	}		

	GSPrintf(stdout, @"Simulation output directory is %@.\n", outputDir);
	
	
	return YES;
}

- (BOOL) createSimulationOutputDirectory: (NSError**) error
{
	NSString* optionsFile;

	if(![self _createSimulationOutputDirectory: error])
		return NO;

	if(![self _createSimulationOutputFiles: error])
		return NO;

	//FIXME: Temporary way to record the options used to
	//generate a simulation

	optionsFile = [[[simulationData dataStorage] 
				storagePath] 
				stringByAppendingPathComponent: @"Template"];
	[simulatorTemplate writeToFile: optionsFile atomically: NO];

	return YES;
}

- (BOOL) createControllerOutputDirectory: (NSError**) error
{
	controllerOutputDir = [[NSUserDefaults standardUserDefaults] 
			stringForKey: @"ControllerOutputDir"];

	if(controllerOutputDir == nil)
	{
		controllerOutputDir = [[fileManager currentDirectoryPath] 
				stringByAppendingPathComponent: @"ControllerOutput"];
		NSWarnLog(@"Controller output directory not specified. Defaulting to %@", controllerOutputDir);		
	}
	
	[controllerOutputDir retain];
	if(![self _checkDirectory: controllerOutputDir error: error])
	{
		/*
		 * If checkDirectory:error set an error we return immediately..
		 * Otherwise we try to create the missing directory.
		 */

		if(*error != nil)
			return NO;

		if(![self _createDirectory: controllerOutputDir error: error])
			return NO;
	}		

	GSPrintf(stdout, @"Controller output directory is %@.\n", controllerOutputDir);

	return YES;
}

/*
 * Input/Output related methods
 */

- (FILE*) openFile: (NSString*) file  usingName: (NSString*) name flag: (NSString*) fileFlag
{
	const char* filename;
	const char* flag;
	FILE* file_p;

	if(file == nil)
	{
		NSWarnLog(@"There is no file called %@\n", file);
		return NULL;
	}
	
	if(![fileManager fileExistsAtPath: file])
		NSWarnLog(@"File %@ does not exist. Will create it if flag indicates\n", file);

	filename = [file cString];
	flag = [fileFlag cString];

	//open the file

	file_p = fopen(filename, flag);
	if(file_p == NULL)
	{
		NSWarnLog(@"File %@ does not exist and flag is %@\n", file, fileFlag);
		return NULL;
	}
	else
		[fileStreams setObject: [NSValue valueWithPointer: file_p] forKey: name];

	return file_p;
}

- (FILE*) getStreamForName: (NSString*) name
{
	return (FILE*)[[fileStreams objectForKey: name] pointerValue];
}

- (void) closeStreamWithName: (NSString*) name
{
	fclose([self getStreamForName: name]);
	[fileStreams removeObjectForKey: name];
}

- (void) closeAllStreams
{
	NSEnumerator *enumerator = [fileStreams keyEnumerator];
	id key;

	while((key = [enumerator nextObject]))
		if(![key isEqual:@"Error"] && ![key isEqual: @"Standard"])
			[self closeStreamWithName: key];
}

- (void) saveResults: (NSArray*) anArray
{
	int i = 0;
	NSString* fileName;
	NSEnumerator* resultsEnum;
	id result;

	resultsEnum = [anArray objectEnumerator];
	while((result = [resultsEnum nextObject]))
	{
		if(![result isKindOfClass: [AdDataSet class]])
			[NSException raise: NSInvalidArgumentException
				format: @"Controller results can only be AdDataSet instances.\
				 This indicates a bug in the controller used."];
			
		if([result name] != @"None")
			fileName = [result name];
		else
			fileName = [NSString stringWithFormat: @"results%d.out", i];
			
		fileName = [controllerOutputDir stringByAppendingPathComponent: fileName];
		GSPrintf(stderr, @"Output data set at %@", fileName);	
		[NSKeyedArchiver archiveRootObject: result toFile: fileName];
		i++;
	}	
}

/* 
 * Accessors 
 */

- (NSString*) simulationOutputDirectory 
{
	return [[outputDir retain] autorelease];
}

- (NSString*) controllerOutputDirectory
{
	return [[controllerOutputDir retain] autorelease];
}

- (NSString*) controllerDirectory
{
	return [[controllerDir retain] autorelease];
}

- (NSString*) adunDirectory
{
	return [[adunDir retain] autorelease];
}

- (NSDictionary*) template
{
	return [[simulatorTemplate retain] autorelease];
}

- (NSDictionary*) externalObjects
{
	return [[externalObjects retain] autorelease];
}

- (AdSimulationData*) simulationData
{
	return [[simulationData retain] autorelease];
}

- (id) simulationWriteStorage
{
	return [[writeModeStorage retain] autorelease];
}

/*
 * Commands
 */

- (void) setCore: (id) object
{
	core = object;
}

- (id) core
{
	return core;
}

- (id) execute: (NSDictionary*) commandDict error: (NSError**) errorResult;
{
	NSString* command;
	SEL commandSelector;
	id result;

	NSDebugLLog(@"Execute", @"Recieved %@", commandDict);

	if((command = [commandDict objectForKey: @"command"]) == nil)
		[NSException raise: NSInvalidArgumentException
			format: @"The command dictionary is missing the command key"];
	
	NSDebugLLog(@"Execute", @"Command is %@. Querying core %@ for validity", command, core);

	if(![core validateCommand: command])	
	{
		result = nil;
		*errorResult = AdCreateError(AdunCoreErrorDomain,
					AdCoreCommandError,
					[NSString stringWithFormat: @"The supplied command (%@) is invalid", command],
					nil,
					nil);
		return result;
	}	
	
	commandSelector = NSSelectorFromString([NSString stringWithFormat:@"%@:", command]);
	
	NSDebugLLog(@"Execute", @"Command validated. Exectuing");

	//Catch exceptions raised by any programmatic errors in the command.
	//We convert them to errors, log them, and continue the simulation.
	NS_DURING
	{
		result = [core performSelector: commandSelector 
				withObject: [commandDict objectForKey: @"options"]];
	}
	NS_HANDLER
	{
		NSWarnLog(@"Caught an %@ exception", [localException name]);
		NSWarnLog(@"Reason %@", [localException reason]);
		NSWarnLog(@"User info %@", [localException userInfo]);
		NSWarnLog(@"This exception was generated by dynamic command %@", command);
		NSWarnLog(@"Options were %@", [commandDict objectForKey: @"options"]);
		NSWarnLog(@"Continiuing simulation - there may be errors depending on the nature of the command");
		*errorResult = AdCreateError(AdunCoreErrorDomain,
				AdCoreFatalCommandError,
				[NSString stringWithFormat: 
				@"The dynamic command %@ raised an exception", command],
				@"This is probably due to a programming error in the command",
				@"Notify the adun developers supplying the log for the simulation run");
		return nil;
	}
	NS_ENDHANDLER

	NSDebugLLog(@"Execute", @"Command executed. Results %@", result);
	*errorResult = [core errorForCommand: command];
	NSDebugLLog(@"Execute", @"Error is %@", *errorResult);

	return result;
}

- (NSMutableDictionary*) optionsForCommand: (NSString*) command;
{
	return [core optionsForCommand: command];
}

- (NSArray*) validCommands
{
	return [core validCommands];
}

@end