libcw 0.1.1

Core Wars runtime and parser
Documentation
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
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483

use std::collections::{VecDeque, HashMap};

use redcode::types::*;
use redcode::traits;

pub type SimulationResult<T> = Result<T, SimulationError>;
pub type LoadResult<T> = Result<T, LoadError>;

/// Errors that can occur during simulation
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum SimulationError
{
    /// Core was already halted
    Halted,
}

/// Errors that can occur during loading
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum LoadError
{
    /// Validation error: program has invalid length
    InvalidLength,

    /// Validation error: invalid distance between programs
    InvalidDistance,

    /// Load cannot be called with no programs
    EmptyLoad
}

/// Events that can happen during a running simulation
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum SimulationEvent
{
    /// Game ended in a tie
    MaxCyclesReached,

    /// Process split inner contains address of new pc
    Split,

    /// A process terminated
    Terminated,

    /// The Mars halted
    Halted,

    /// A process jumped address
    Jumped,

    /// Skipped happens in all `Skip if ...` instructions
    Skipped,

    /// Nothing happened
    Stepped,
}

/// Core wars runtime
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Mars<T>
    where T: traits::Instruction
{
    /// Mars memory
    pub(super) memory:        Vec<T>,

    /// Instruction register
    pub(super) ir:            T,

    /// Current Pid executing on the Mars
    pub(super) pid:           Pid,

    /// Current program counter
    pub(super) pc:            Address,

    /// Current numbered cycle core is executing
    pub(super) cycle:         usize,

    /// Program counter for each process currently loaded into memory
    pub(super) process_queue: VecDeque<(Pid, VecDeque<Address>)>,

    /// Private storage space for warriors
    pub(super) pspace:        HashMap<Pin, Vec<Value>>,

    /// Has the core finished executing
    pub(super) halted:        bool,

    // Load constraints
    /// Maximum length of programs when loading
    pub(super) max_length:    usize,

    /// Minimum distance between programs when batch loading
    pub(super) min_distance:  usize,

    // Mars information (const)
    /// Mars version
    pub(super) version:       usize,

    /// Size of P-space
    pub(super) pspace_size:   usize,

    // Runtime constraints
    /// Maximum of processes that can be on the process queue at any time
    pub(super) max_processes: usize,

    /// Maximum number of cycles that can pass before a tie is declared
    pub(super) max_cycles:    usize,
}

impl<T> Mars<T>
where T: traits::Instruction
{
    /// Step forward one cycle
    pub fn step(&mut self) -> SimulationResult<SimulationEvent>
    {
        if self.halted() { // can't step after the core is halted
            return Err(SimulationError::Halted);
        }

        else if self.cycle() >= self.max_cycles() {
            self.halted = true;
            return Ok(SimulationEvent::MaxCyclesReached)
        }

        let pc = self.pc();

        // Fetch instruction
        self.ir = self.fetch(pc);
        let (a_mode, b_mode) = (self.ir.a_mode(), self.ir.b_mode());

        // PostIncrement phase
        let predecrement = a_mode == AddressingMode::AIndirectPreDecrement ||
            a_mode == AddressingMode::BIndirectPreDecrement ||
            b_mode == AddressingMode::AIndirectPreDecrement ||
            b_mode == AddressingMode::BIndirectPreDecrement;

        // Preincrement phase
        if predecrement {
            // fetch direct target
            let a_addr = self.calc_addr_offset(pc, self.ir.a());
            let b_addr = self.calc_addr_offset(pc, self.ir.b());
            let mut a = self.fetch(a_addr);
            let mut b = self.fetch(b_addr);

            let (a_a, a_b) = (a.a(), a.b());
            let (b_a, b_b) = (b.a(), b.b());

            // FIXME: combine these into a single match statement
            match a_mode {
                AddressingMode::AIndirectPreDecrement => { a.set_a(a_a + 1); }
                AddressingMode::BIndirectPreDecrement => { a.set_b(a_b + 1); }
                _ => {}
            };

            match b_mode {
                AddressingMode::AIndirectPreDecrement => { b.set_a(b_a + 1); }
                AddressingMode::BIndirectPreDecrement => { b.set_b(b_b + 1); }
                _ => {}
            };

            self.store(a_addr, a);
            self.store(b_addr, b);
        }

        // Execute instruction(updating the program counter and requeing it
        // are handled in this phase)
        let exec_event = self.execute();

        // PostIncrement phase
        let postincrement = a_mode == AddressingMode::AIndirectPostIncrement ||
            a_mode == AddressingMode::BIndirectPostIncrement ||
            b_mode == AddressingMode::AIndirectPostIncrement ||
            b_mode == AddressingMode::BIndirectPostIncrement;

        if postincrement {
            // fetch direct target
            let a_addr = self.calc_addr_offset(pc, self.ir.a());
            let b_addr = self.calc_addr_offset(pc, self.ir.b());
            let mut a = self.fetch(a_addr);
            let mut b = self.fetch(b_addr);

            let (a_a, a_b) = (a.a(), a.b());
            let (b_a, b_b) = (b.a(), b.b());

            // FIXME: combine these into a single match statement
            match a_mode {
                AddressingMode::AIndirectPreDecrement => { a.set_a(a_a + 1); }
                AddressingMode::BIndirectPreDecrement => { a.set_b(a_b + 1); }
                _ => {}
            };

            match b_mode {
                AddressingMode::AIndirectPreDecrement => { b.set_a(b_a + 1); }
                AddressingMode::BIndirectPreDecrement => { b.set_b(b_b + 1); }
                _ => {}
            };
            // store result
            self.store(a_addr, a);
            self.store(b_addr, b);
        }

        // check if there are any more process queues running on the core
        let (pid, q) = self.process_queue.pop_front().unwrap();
        if !q.is_empty() {
            self.process_queue.push_back((pid, q));
        }

        // If no there are no processes left
        if self.process_queue.is_empty() {
            Ok(self.halt())
        } else {
            // Fetch new queue
            let &mut(curr_pid, ref mut curr_q) = self.process_queue.front_mut().unwrap();
            self.pid = curr_pid;
            self.pc = curr_q.pop_front().unwrap();
            self.cycle += 1;
            Ok(exec_event)
        }
    }

    /// Has the core finished its execution. This can mean either a tie has
    /// occurred or a warrior has emerged victoriors
    pub fn halted(&self) -> bool
    {
        self.halted
    }

    /// Halt the Mars
    #[inline]
    fn halt(&mut self) -> SimulationEvent
    {
        self.halted = true;
        SimulationEvent::Halted
    }

    /// Reset the Mars's memory and the process queue
    pub fn reset(&mut self)
    {
        // reset memory
        for e in self.memory.iter_mut() {
            *e = Default::default();
        }

        self.process_queue.clear();

        self.cycle         = 0;
        self.ir            = Default::default();
        self.halted        = true;
    }

    /// Reset the Mar's memory, process queue, AND P-space
    pub fn reset_hard(&mut self)
    {
        self.pspace.clear();
        self.reset();
    }

    /// Load mutliple programs into the Mars, checking their spacing and their
    /// length
    /// # Arguments
    /// * `programs`: programs and load information loaded in a tuple, cannot
    ///     be empty
    /// # Return
    /// `Ok(())` if the load was successful, otherwise an error with the 
    ///     corresponding `SimulationError`
    pub fn load_batch(&mut self, programs: Vec<(Address, Option<Pin>, &Vec<T>)>)
        -> LoadResult<()>
    {
        // TODO: validate margin
        // TODO: correct addresses that are out of bounds by modulo-ing them
        if programs.is_empty() {
            return Err(LoadError::EmptyLoad);
        }

        let valid_margin = true; // TODO

        if valid_margin {
            // load each program
            for &(dest, maybe_pin, ref prog) in programs.iter() {
                let pin = maybe_pin.unwrap_or(self.process_count() as Pid);

                let cycle_memory_iter = (0..self.size())
                    .cycle()
                    .skip(dest as usize)
                    .take(prog.len())
                    .enumerate();

                // copy program into memory
                for (i, j) in cycle_memory_iter {
                    self.memory[j] = prog[i].clone();
                }

                self.pspace.insert(pin, vec![0; self.pspace_size]);

                let mut q = VecDeque::new();
                q.push_front(dest);
                self.process_queue.push_front((pin, q));
            }

            self.halted = false;

            let &mut (curr_pid, ref mut curr_q) = self.process_queue.front_mut()
                .unwrap();

            self.pc = curr_q.pop_front().unwrap();
            self.pid = curr_pid;
                
            Ok(())
        } else {
            Err(LoadError::InvalidDistance)
        }
    }

    /// Get `Pid` currently executing on the core
    ///
    /// # Panics
    /// * Panics is the process queue is empty
    #[inline]
    pub fn pc(&self) -> Address
    {
        self.pc
    }

    /// Get the program counters for all processes
    pub fn pcs(&self) -> Vec<Address>
    {
        let mut pcs = vec![self.pc()];

        for &(_, ref q) in &self.process_queue {
            pcs.extend(q.iter().cloned());
        }

        pcs
    }

    /// Current cycle core is executing
    #[inline]
    pub fn cycle(&self) -> usize
    {
        self.cycle
    }

    /// Get the current `Pid` executing
    #[inline]
    pub fn pid(&self) -> Pid
    {
        self.pid
    }

    /// Get all `Pid`s that are currently active in the order they will be 
    /// executing
    pub fn pids(&self) -> Vec<Pid>
    {
        let mut pids = vec![self.pid()];
        pids.extend(self.process_queue.iter().map(|&(pid, _)| pid));
        pids
    }

    /// Size of memory
    pub fn size(&self) -> usize
    {
        self.memory.len()
    }

    /// Size of private storage space
    #[inline]
    pub fn pspace_size(&self) -> usize
    {
        self.pspace_size
    }

    /// Version of core multiplied by `100`
    #[inline]
    pub fn version(&self) -> usize
    {
        self.version
    }

    /// Maximum number of processes that can be in the core queue
    #[inline]
    pub fn max_processes(&self) -> usize
    {
        self.max_processes
    }

    /// Maximum number of cycles before a tie is declared
    #[inline]
    pub fn max_cycles(&self) -> usize
    {
        self.max_cycles
    }

    /// Maximum number of instructions allowed in a program
    #[inline]
    pub fn max_length(&self) -> usize
    {
        self.max_length
    }

    /// Minimum distance allowed between programs
    pub fn min_distance(&self) -> usize
    {
        self.min_distance
    }

    /// Get immutable reference to memory
    pub fn memory(&self) -> &Vec<T>
    {
        &self.memory
    }

    /// Get an immutable reference to private storage
    pub fn pspace(&self) -> &HashMap<Pin, Vec<Value>>
    {
        &self.pspace
    }

    /// Get the number of processes currently running
    pub fn process_count(&self) -> usize
    {
        self.process_queue.iter().map(|&(_, ref q)| q.len()).sum()
    }

    /// Fetch reference to current queue
    pub fn current_queue(&self) -> Option<&VecDeque<Address>>
    {
        if let Some(&(_, ref q)) = self.process_queue.front() {
            Some(q)
        } else {
            None
        }
    }

    /// Fetch mutable reference to current queue
    fn current_queue_mut(&mut self) -> Option<&mut VecDeque<Address>>
    {
        if let Some(&mut (_, ref mut q)) = self.process_queue.front_mut() {
            Some(q)
        } else {
            None
        }
    }

    /// Execute the instrcution in the `Instruction` register
    #[inline]
    fn execute(&mut self) -> SimulationEvent
    {
        match self.ir.op() {
            OpCode::Dat => self.exec_dat(),
            OpCode::Mov => self.exec_mov(),
            OpCode::Add => self.exec_add(),
            OpCode::Sub => self.exec_sub(),
            OpCode::Mul => self.exec_mul(),
            OpCode::Div => self.exec_div(),
            OpCode::Mod => self.exec_mod(),
            OpCode::Jmp => self.exec_jmp(),
            OpCode::Jmz => self.exec_jmz(),
            OpCode::Jmn => self.exec_jmn(),
            OpCode::Djn => self.exec_djn(),
            OpCode::Spl => self.exec_spl(),
            OpCode::Seq => self.exec_seq(),
            OpCode::Sne => self.exec_sne(),
            OpCode::Slt => self.exec_slt(),
            OpCode::Ldp => self.exec_ldp(),
            OpCode::Stp => self.exec_stp(),
            OpCode::Nop => self.exec_nop(),
        }
    }

    ////////////////////////////////////////////////////////////////////////////
    // Address resolution functions
    ////////////////////////////////////////////////////////////////////////////

    /// Calculate the address after adding an offset
    ///
    /// # Arguments
    /// * `base`: base address
    /// * `offset`: distance from base to calculate
    #[inline]
    fn calc_addr_offset(&self, base: Address, offset: Value) -> Address
    {
        if offset < 0 {
            (base.wrapping_sub(-offset as Address) % self.size() as Address)
        } else {
            (base.wrapping_add(offset as Address) % self.size() as Address)
        }
    }

    /// Get the effective of address of the current `Instruction`. This takes
    /// into account the addressing mode of the field used
    ///
    /// # Arguments
    /// * `use_a_field`: should the A field be used for calculation, or B
    #[inline]
    fn effective_addr(&self, use_a_field: bool) -> Address
    {
        use self::AddressingMode::*;

        // fetch the addressing mode and offset
        let (mode, offset) = if use_a_field { 
            (self.ir.a_mode(), self.ir.a())
        } else {
            (self.ir.b_mode(), self.ir.b())
        };

        let pc = self.pc();

        let direct = self.fetch(self.calc_addr_offset(pc, offset));

        match mode {
            Immediate => pc,
            Direct => self.calc_addr_offset(pc, offset),
            AIndirect
                | AIndirectPreDecrement
                | AIndirectPostIncrement =>
                self.calc_addr_offset(pc, direct.a() + offset),
            BIndirect
                | BIndirectPreDecrement
                | BIndirectPostIncrement =>
                self.calc_addr_offset(pc, direct.b() + offset),
        }
    }

    /// Get the effective of address of the current `Instruction`'s A Field
    ///
    /// An alias for `Mars::effective_addr(true)`
    fn effective_addr_a(&self) -> Address
    {
        self.effective_addr(true)
    }

    /// Get the effective of address of the current `Instruction`'s A Field
    ///
    /// An alias for `Mars::effective_addr(false)`
    fn effective_addr_b(&self) -> Address
    {
        self.effective_addr(false)
    }

    ////////////////////////////////////////////////////////////////////////////
    // Program counter utility functions
    ////////////////////////////////////////////////////////////////////////////

    /// Move the program counter forward
    fn step_pc(&mut self) -> SimulationEvent
    {
        let pc = self.pc();
        self.pc = (pc + 1) % self.size() as Address;
        SimulationEvent::Stepped
    }

    /// Move the program counter forward twice
    fn skip_pc(&mut self) -> SimulationEvent
    {
        let pc = self.pc();
        self.pc = (pc + 2) % self.size() as Address;
        SimulationEvent::Skipped
    }

    /// Jump the program counter by an offset
    ///
    /// # Arguments
    /// * `offset`: amount to jump
    fn jump_pc(&mut self, offset: Value) -> SimulationEvent
    {
        let pc = self.pc();
        self.pc = self.calc_addr_offset(pc, offset);
        SimulationEvent::Jumped
    }

    /// Move the program counter forward by one and then queue the program
    /// counter onto the current queue
    fn step_and_queue_pc(&mut self) -> SimulationEvent
    {
        self.step_pc();

        let pc = self.pc();
        self.current_queue_mut().unwrap().push_back(pc);
        SimulationEvent::Stepped
    }

    /// Move the program counter forward twice and then queue the program
    /// counter onto the current queue
    fn skip_and_queue_pc(&mut self) -> SimulationEvent
    {
        self.skip_pc();

        let pc = self.pc();
        self.current_queue_mut().unwrap().push_back(pc);
        SimulationEvent::Skipped
    }

    /// Jump the program counter by an offset and then queue the program
    /// count onto the current queue
    ///
    /// # Arguments
    /// * `offset`: amount to jump by
    fn jump_and_queue_pc(&mut self, offset: Value) -> SimulationEvent
    {
        self.jump_pc(offset);
        
        // remove old pc
        let pc = self.pc();
        self.current_queue_mut().unwrap().push_back(pc);
        SimulationEvent::Jumped
    }

    ////////////////////////////////////////////////////////////////////////////
    // Storage and retrieval functions
    ////////////////////////////////////////////////////////////////////////////

    /// Store an `Instruction` in memory
    ///
    /// # Arguments
    /// * `addr`: address to store
    /// * `instr`: instruction to store
    fn store(&mut self, addr: Address, instr: T)
    {
        let mem_size = self.size();
        self.memory[addr as usize % mem_size] = instr;
    }

    /// Store an instruction in a specified pspace
    ///
    /// # Arguments
    /// * `pin`: programs pin, used as a lookup key
    /// * `addr`: address in the pspace to store
    /// * `instr`: instruction to store
    fn store_pspace(&mut self, pin: Pin, addr: Address, value: Value)
    {
        if let Some(pspace) = self.pspace.get_mut(&pin) {
            let pspace_size = pspace.len();
            pspace[addr as usize % pspace_size] = value;
        }  else {
            // TODO: create pspace for pin
            unimplemented!();
        }
    }

    /// Store an `Instruction` into the memory location pointed at by the A
    /// field of the instruction loaded into the instruction register
    ///
    /// # Arguments
    /// * `instr`: `Instruction` to store
    fn store_effective_a(&mut self, instr: T)
    {
        let eff_addr = self.effective_addr_a();
        self.store(eff_addr, instr)
    }

    /// Store an `Instruction` into the memory location pointed at by the B
    /// field of the instruction loaded into the instruction register
    ///
    /// # Arguments
    /// * `instr`: `Instruction` to store
    fn store_effective_b(&mut self, instr: T)
    {
        let eff_addr = self.effective_addr_b();
        self.store(eff_addr, instr)
    }

    /// Fetch copy of instruction in memory
    ///
    /// # Arguments
    /// * `addr`: adress to fetch
    fn fetch(&self, addr: Address) -> T
    {
        self.memory[addr as usize % self.size()].clone()
    }

    /// Fetch an instruction from a programs private storage
    ///
    /// # Arguments
    /// * `pin`: pin of program, used as lookup key
    /// * `addr`: address of pspace to access
    fn fetch_pspace(&self, pin: Pin, addr: Address) -> Value
    {
        if let Some(pspace) = self.pspace.get(&pin) {
            pspace[addr as usize % pspace.len()]
        } else {
            // TODO: create new pspace
            unimplemented!();
        }
    }

    /// Fetch copy of instruction pointed at by the A field of the instruction
    /// loaded into the instruction register
    fn fetch_effective_a(&self) -> T
    {
        self.fetch(self.effective_addr_a())
    }

    /// Fetch copy of instruction pointed at by the B field of the instruction
    /// loaded into the instruction register
    fn fetch_effective_b(&self) -> T
    {
        self.fetch(self.effective_addr_b())
    }

    ////////////////////////////////////////////////////////////////////////////
    // Instruction execution functions
    ////////////////////////////////////////////////////////////////////////////

    /// Execute `dat` instruction
    ///
    /// Supported Modifiers: None
    #[inline]
    fn exec_dat(&mut self) -> SimulationEvent
    {
        let _ = self.current_queue_mut().unwrap().pop_front();
        SimulationEvent::Terminated
    }

    /// Execute `mov` instruction
    ///
    /// Supported Modifiers: `A` `B` `AB` `BA` `X` `F` `I`
    #[inline]
    fn exec_mov(&mut self) -> SimulationEvent
    {
        let a     = self.fetch_effective_a();
        let mut b = self.fetch_effective_b();

        let (a_a, a_b) = (a.a(), a.b());

        match self.ir.modifier() {
            Modifier::A => {b.set_a(a_a);},
            Modifier::B => {b.set_b(a_b);},
            Modifier::AB => {b.set_a(a_b);},
            Modifier::BA => {b.set_b(a_a);},
            Modifier::F =>
            {
                b.set_a(a_a);
                b.set_b(a_b);
            },
            Modifier::X =>
            {
                b.set_a(a_b);
                b.set_b(a_a);
            },
            Modifier::I => b = a
        }

        self.store_effective_b(b);
        self.step_and_queue_pc()
    }

    /// Execute `add` instruction
    ///
    /// Supported Modifiers: `A` `B` `AB` `BA` `X` `F`
    #[inline]
    fn exec_add(&mut self) -> SimulationEvent
    {
        // TODO: math needs to be done modulo core size
        let a     = self.fetch_effective_a();
        let mut b = self.fetch_effective_b();

        let (a_a, a_b) = (a.a(), a.b());
        let (b_a, b_b) = (b.a(), b.b());

        match self.ir.modifier() {
            Modifier::A  => { b.set_a((b_a + a_a) % self.size() as Value); }
            Modifier::B  => { b.set_b((b_b + a_b) % self.size() as Value); }
            Modifier::BA => { b.set_a((b_a + a_b) % self.size() as Value); }
            Modifier::AB => { b.set_b((b_b + a_a) % self.size() as Value); }
            Modifier::F
                | Modifier::I =>
            {
                b.set_a((b_a + a_a) % self.size() as Value);
                b.set_b((b_b + a_b) % self.size() as Value);
            }
            Modifier::X =>
            {
                b.set_b((b_b + a_a) % self.size() as Value);
                b.set_a((b_a + a_b) % self.size() as Value);
            }
        }

        self.store_effective_b(b);
        self.step_and_queue_pc()
    }

    /// Execute `sub` instruction
    ///
    /// Supported Modifiers: `A` `B` `AB` `BA` `X` `F`
    #[inline]
    fn exec_sub(&mut self) -> SimulationEvent
    {
        // TODO: math needs to be done modulo core size
        let a     = self.fetch_effective_a();
        let mut b = self.fetch_effective_b();

        let (a_a, a_b) = (a.a(), a.b());
        let (b_a, b_b) = (b.a(), b.b());

        match self.ir.modifier() {
            Modifier::A  => { b.set_a((b_a - a_a) % self.size() as Value); }
            Modifier::B  => { b.set_b((b_b - a_b) % self.size() as Value); }
            Modifier::BA => { b.set_a((b_a - a_b) % self.size() as Value); }
            Modifier::AB => { b.set_b((b_b - a_a) % self.size() as Value); }
            Modifier::F
                | Modifier::I =>
            {
                b.set_a((b_a - a_a) % self.size() as Value);
                b.set_b((b_b - a_b) % self.size() as Value);
            }
            Modifier::X =>
            {
                b.set_b((b_b - a_a) % self.size() as Value);
                b.set_a((b_a - a_b) % self.size() as Value);
            }
        }

        self.store_effective_b(b);
        self.step_and_queue_pc()
    }

    /// Execute `mul` instruction
    ///
    /// Supported Modifiers: `A` `B` `AB` `BA` `X` `F`
    #[inline]
    fn exec_mul(&mut self) -> SimulationEvent
    {
        // TODO: math needs to be done modulo core size
        let a     = self.fetch_effective_a();
        let mut b = self.fetch_effective_b();

        let (a_a, a_b) = (a.a(), a.b());
        let (b_a, b_b) = (b.a(), b.b());

        match self.ir.modifier() {
            Modifier::A  => { b.set_a((b_a * a_a) % self.size() as Value); }
            Modifier::B  => { b.set_b((b_b * a_b) % self.size() as Value); }
            Modifier::BA => { b.set_a((b_a * a_b) % self.size() as Value); }
            Modifier::AB => { b.set_b((b_b * a_a) % self.size() as Value); }
            Modifier::F
                | Modifier::I =>
            {
                b.set_a((b_a * a_a) % self.size() as Value);
                b.set_b((b_b * a_b) % self.size() as Value);
            }
            Modifier::X =>
            {
                b.set_b((b_b * a_a) % self.size() as Value);
                b.set_a((b_a * a_b) % self.size() as Value);
            }
        }

        self.store_effective_b(b);
        self.step_and_queue_pc()
    }

    /// Execute `div` instruction
    ///
    /// Supported Modifiers: `A` `B` `AB` `BA` `X` `F`
    #[inline]
    fn exec_div(&mut self) -> SimulationEvent
    {
        // TODO: math needs to be done modulo core size
        // TODO: division by zero needs to kill the process
        let a     = self.fetch_effective_a();
        let mut b = self.fetch_effective_b();

        let (a_a, a_b) = (a.a(), a.b());
        let (b_a, b_b) = (b.a(), b.b());

        match self.ir.modifier() {
            Modifier::A  => { b.set_a((b_a / a_a) % self.size() as Value); }
            Modifier::B  => { b.set_b((b_b / a_b) % self.size() as Value); }
            Modifier::BA => { b.set_a((b_a / a_b) % self.size() as Value); }
            Modifier::AB => { b.set_b((b_b / a_a) % self.size() as Value); }
            Modifier::F
                | Modifier::I =>
            {
                b.set_a((b_a / a_a) % self.size() as Value);
                b.set_b((b_b / a_b) % self.size() as Value);
            }
            Modifier::X =>
            {
                b.set_b((b_b / a_a) % self.size() as Value);
                b.set_a((b_a / a_b) % self.size() as Value);
            }
        };

        self.store_effective_b(b);
        self.step_and_queue_pc()
    }

    /// Execute `mod` instruction
    ///
    /// Supported Modifiers: `A` `B` `AB` `BA` `X` `F`
    #[inline]
    fn exec_mod(&mut self) -> SimulationEvent
    {
        // TODO: math needs to be done modulo core size
        // TODO: division by zero needs to kill the process
        let a     = self.fetch_effective_a();
        let mut b = self.fetch_effective_b();

        let (a_a, a_b) = (a.a(), a.b());
        let (b_a, b_b) = (b.a(), b.b());

        match self.ir.modifier() {
            Modifier::A  => { b.set_a((b_a % a_a) % self.size() as Value); }
            Modifier::B  => { b.set_b((b_b % a_b) % self.size() as Value); }
            Modifier::BA => { b.set_a((b_a % a_b) % self.size() as Value); }
            Modifier::AB => { b.set_b((b_b % a_a) % self.size() as Value); }
            Modifier::F
                | Modifier::I =>
            {
                b.set_a((b_a % a_a) % self.size() as Value);
                b.set_b((b_b % a_b) % self.size() as Value);
            }
            Modifier::X =>
            {
                b.set_b((b_b % a_a) % self.size() as Value);
                b.set_a((b_a % a_b) % self.size() as Value);
            }
        };

        self.store_effective_b(b);
        self.step_and_queue_pc()
    }

    /// Execute `jmp` instruction
    ///
    /// Supported Modifiers: `B`
    #[inline]
    fn exec_jmp(&mut self) -> SimulationEvent
    {
        match self.ir.a_mode() {
            AddressingMode::Immediate
                | AddressingMode::Direct =>
            {
                let offset = self.ir.a();
                self.jump_and_queue_pc(offset);
            }
            // TODO
            _ => unimplemented!()
        };

        SimulationEvent::Jumped
    }

    /// Execute `jmz` instruction
    ///
    /// Supported Modifiers: `B`
    #[inline]
    fn exec_jmz(&mut self) -> SimulationEvent
    {
        let b = self.fetch_effective_b();
        let offset = self.ir.a(); // TODO: needs to calculate jump offset

        let jump = match self.ir.modifier() {
            Modifier::A
                | Modifier::BA => b.a() == 0,
            Modifier::B
                | Modifier::AB => b.b() == 0,
            Modifier::F
                | Modifier::I
                | Modifier::X => b.a() == 0 && b.b() == 0,
        };

        if jump {
            self.jump_and_queue_pc(offset)
        } else {
            self.step_and_queue_pc()
        }
    }

    /// Execute `jmn` instruction
    ///
    /// Supported Modifiers: `B`
    #[inline]
    fn exec_jmn(&mut self) -> SimulationEvent
    {
        let b = self.fetch_effective_b();
        let offset = self.ir.a(); // TODO: needs to calculate jump offset

        let jump = match self.ir.modifier() {
            Modifier::A
                | Modifier::BA => b.a() != 0,
            Modifier::B
                | Modifier::AB => b.b() != 0,
            Modifier::F
                | Modifier::I
                | Modifier::X => b.a() != 0 && b.b() != 0,
        };

        if jump {
            self.jump_and_queue_pc(offset)
        } else {
            self.step_and_queue_pc()
        }
    }

    /// Execute `djn` instruction
    ///
    /// Supported Modifiers: `B`
    #[inline]
    fn exec_djn(&mut self) -> SimulationEvent
    {
        // predecrement the instruction before checking if its not zero
        let mut b = self.fetch_effective_b();
        let (b_a, b_b) = (b.a(), b.b());

        match self.ir.modifier() {
            Modifier::A
                | Modifier::BA => { b.set_a(b_a - 1); },
            Modifier::B
                | Modifier::AB => { b.set_b(b_b - 1); },
            Modifier::F
                | Modifier::I
                | Modifier::X =>
            {
                b.set_a(b_a - 1);
                b.set_b(b_b - 1);
            }
        };
        self.store_effective_b(b);

        self.exec_jmn()
    }

    /// Execute `spl` instruction
    ///
    /// Supported Modifiers: `B`
    #[inline]
    fn exec_spl(&mut self) -> SimulationEvent
    {
        if self.process_count() < self.max_processes(){
            let target = self.effective_addr_a();

            self.current_queue_mut().unwrap().push_back(target);
            self.step_and_queue_pc();
            SimulationEvent::Split
        } else {
            self.step_and_queue_pc()
        }
    }

    /// Execute `seq` instruction
    ///
    /// Supported Modifiers: `A` `B` `AB` `BA` `X` `F` `I`
    #[inline]
    fn exec_seq(&mut self) -> SimulationEvent
    {
        let a = self.fetch_effective_a();
        let b = self.fetch_effective_b();

        let skip = match self.ir.modifier() {
            Modifier::A       => a.a() == b.b(),
            Modifier::B       => a.b() == b.b(),
            Modifier::BA      => a.a() == b.b(),
            Modifier::AB      => a.b() == b.a(),
            Modifier::X       => a.b() == b.a() &&
                                 a.a() == b.b(),
            Modifier::F
                | Modifier::I => a.a() == b.a() &&
                                 a.b() == b.b(),
        };

        if skip { self.skip_and_queue_pc() } else { self.step_and_queue_pc() }
    }

    /// Execute `sne` instruction
    ///
    /// Supported Modifiers: `A` `B` `AB` `BA` `X` `F` `I`
    #[inline]
    fn exec_sne(&mut self) -> SimulationEvent
    {
        let a = self.fetch_effective_a();
        let b = self.fetch_effective_b();

        let skip = match self.ir.modifier() {
            Modifier::A       => a.a() != b.b(),
            Modifier::B       => a.b() != b.b(),
            Modifier::BA      => a.a() != b.b(),
            Modifier::AB      => a.b() != b.a(),
            Modifier::X       => a.b() != b.a() &&
                                 a.a() != b.b(),
            Modifier::F
                | Modifier::I => a.a() != b.a() &&
                                 a.b() != b.b(),
        };

        if skip { self.skip_and_queue_pc() } else { self.step_and_queue_pc() }
    }

    /// Execute `slt` instruction
    ///
    /// Supported Modifiers: `A` `B` `AB` `BA` `X` `F` `I`
    #[inline]
    fn exec_slt(&mut self) -> SimulationEvent
    {
        let a = self.fetch_effective_a();
        let b = self.fetch_effective_b();

        let skip = match self.ir.modifier() {
            Modifier::A       => a.a() < b.b(),
            Modifier::B       => a.b() < b.b(),
            Modifier::BA      => a.a() < b.b(),
            Modifier::AB      => a.b() < b.a(),
            Modifier::X       => a.b() < b.a() &&
                                 a.a() < b.b(),
            Modifier::F
                | Modifier::I => a.a() < b.a() &&
                                 a.b() < b.b(),
        };

        if skip { self.skip_and_queue_pc() } else { self.step_and_queue_pc() }
    }

    /// Execute `ldp` instruction
    ///
    /// Supported Modifiers: `A` `B` `AB` `BA` `X` `F` `I`
    #[inline]
    fn exec_ldp(&mut self) -> SimulationEvent
    {
        match self.ir.modifier() {
            _ => unimplemented!()
        }
    }

    /// Execute `stp` instruction
    ///
    /// Supported Modifiers: `A` `B` `AB` `BA` `X` `F` `I`
    #[inline]
    fn exec_stp(&mut self) -> SimulationEvent
    {
        match self.ir.modifier() {
            _ => unimplemented!()
        }
    }

    /// Execute 'nop' instruction
    #[inline]
    fn exec_nop(&mut self) -> SimulationEvent
    {
        self.step_and_queue_pc()
    }
}

#[cfg(test)]
mod test
{
    use simulation::MarsBuilder;
    use redcode::traits::Instruction;
    use redcode::Instruction as InstructionStruct;
    use super::*;

    fn mov_test_program(modifier: Modifier) -> Vec<InstructionStruct>
    {
        vec![
            InstructionStruct::new(
                OpCode::Mov,
                modifier,
                1,
                AddressingMode::Direct,
                2,
                AddressingMode::Direct
                ),
            InstructionStruct::new(
                OpCode::Dat,
                Modifier::I,
                1,
                AddressingMode::Direct,
                2,
                AddressingMode::Direct
                ),
            InstructionStruct::new(
                OpCode::Mov,
                Modifier::I,
                3,
                AddressingMode::Direct,
                4,
                AddressingMode::Direct
                )
        ]
    }

    #[test]
    fn test_load_batch_fails_empty_vector()
    {
        let mut mars: Mars<InstructionStruct> = MarsBuilder::new().build();
        assert_eq!(
            Err(LoadError::EmptyLoad),
            mars.load_batch(vec![])
            );
    }

    #[test]
    #[ignore]
    fn test_load_batch_load_fails_invalid_distance()
    {
        let mut mars: Mars<InstructionStruct> = MarsBuilder::new()
            .min_distance(10)
            .build();

        let useless_program = vec![Default::default(); 1];

        // intentionally load the programs with invalid spacings
        let result = mars.load_batch(vec![
            (0, None, &useless_program),
            (1, None, &useless_program),
        ]);
        
        assert_eq!(Err(LoadError::InvalidDistance), result);
    }

    #[test]
    fn test_batch_load_succeeds()
    {
        let mut mars: Mars<InstructionStruct> = MarsBuilder::new()
            .min_distance(10)
            .max_length(10)
            .build();

        let useless_program = vec![Default::default(); 10];

        // intentionally load the programs with invalid spacings
        let result = mars.load_batch(vec![
            (0, None, &useless_program),
            (21, None, &useless_program),
        ]);
        
        assert_eq!(Ok(()), result);
    }

    #[test]
    fn test_step_errors_when_halted()
    {
        let mut mars: Mars<InstructionStruct> = MarsBuilder::new().build();
        let result = mars.step();

        assert_eq!(Err(SimulationError::Halted), result);
    }

    #[test]
    pub fn test_dat()
    {
        let mut mars: Mars<InstructionStruct> = MarsBuilder::new().build_and_load(vec![
            (0, None, &vec![Default::default(); 1])
            ])
            .unwrap();

        let result = mars.step();
        assert_eq!(Ok(SimulationEvent::Halted), result);
        assert_eq!(true, mars.halted());
    }

    #[test]
    fn test_mov_i_mode()
    {
        let prog = mov_test_program(Modifier::I);

        let mut mars: Mars<InstructionStruct> = MarsBuilder::new()
            .build_and_load(vec![
                (0, None, &prog)
            ])
            .unwrap();

        let init_pc    = mars.pc();

        assert_eq!(Ok(SimulationEvent::Stepped), mars.step());
        assert_eq!(prog[1],                      mars.memory()[2]);
        assert_eq!(init_pc + 1,                  mars.pc());
    }

    #[test]
    fn test_mov_a_mode()
    {
        let prog = mov_test_program(Modifier::A);

        let mut mars: Mars<InstructionStruct> = MarsBuilder::new()
            .build_and_load(vec![
                (0, None, &prog)
            ])
            .unwrap();

        let init_pc    = mars.pc();

        assert_eq!(Ok(SimulationEvent::Stepped), mars.step());
        assert_eq!(prog[1].a(),                  mars.memory()[2].a());
        assert_eq!(prog[1].a_mode(),             mars.memory()[2].a_mode());
        assert_eq!(init_pc + 1,                  mars.pc());
    }

    #[test]
    fn test_mov_b_mode()
    {
        let prog = mov_test_program(Modifier::B);

        let mut mars: Mars<InstructionStruct> = MarsBuilder::new()
            .build_and_load(vec![
                (0, None, &prog)
            ])
            .unwrap();

        let init_pc    = mars.pc();

        assert_eq!(Ok(SimulationEvent::Stepped), mars.step());
        assert_eq!(prog[1].b(),                  mars.memory()[2].b());
        assert_eq!(prog[1].b_mode(),             mars.memory()[2].b_mode());
        assert_eq!(init_pc + 1,                  mars.pc());
    }

    #[test]
    fn test_mov_ab_mode()
    {
        let prog = mov_test_program(Modifier::AB);

        let mut mars: Mars<InstructionStruct> = MarsBuilder::new()
            .build_and_load(vec![
                (0, None, &prog)
            ])
            .unwrap();

        let init_pc    = mars.pc();

        assert_eq!(Ok(SimulationEvent::Stepped), mars.step());
        assert_eq!(prog[1].b(),                  mars.memory()[2].a());
        assert_eq!(prog[1].b_mode(),             mars.memory()[2].a_mode());
        assert_eq!(init_pc + 1,                  mars.pc());
    }

    #[test]
    fn test_mov_ba_mode()
    {
        let prog = mov_test_program(Modifier::BA);

        let mut mars: Mars<InstructionStruct> = MarsBuilder::new()
            .build_and_load(vec![
                (0, None, &prog)
            ])
            .unwrap();

        let init_pc    = mars.pc();

        assert_eq!(Ok(SimulationEvent::Stepped), mars.step());
        assert_eq!(prog[1].a(),                  mars.memory()[2].b());
        assert_eq!(prog[1].a_mode(),             mars.memory()[2].b_mode());
        assert_eq!(init_pc + 1,                  mars.pc());
    }

    #[test]
    fn test_mov_x_mode()
    {
        let prog = mov_test_program(Modifier::X);
        let mut mars: Mars<InstructionStruct> = MarsBuilder::new()
            .build_and_load(vec![
                (0, None, &prog)
            ])
            .unwrap();

        let init_pc    = mars.pc();

        assert_eq!(Ok(SimulationEvent::Stepped), mars.step());
        assert_eq!(prog[1].a(),                  mars.memory()[2].b());
        assert_eq!(prog[1].a_mode(),             mars.memory()[2].b_mode());
        assert_eq!(prog[1].b(),                  mars.memory()[2].a());
        assert_eq!(prog[1].b_mode(),             mars.memory()[2].a_mode());
        assert_eq!(init_pc + 1,                  mars.pc());
    }

    #[test]
    fn test_mov_f_mode()
    {
        let prog = mov_test_program(Modifier::F);

        let mut mars: Mars<InstructionStruct> = MarsBuilder::new()
            .build_and_load(vec![
                (0, None, &prog)
            ])
            .unwrap();

        let init_pc    = mars.pc();

        assert_eq!(Ok(SimulationEvent::Stepped), mars.step());
        assert_eq!(prog[1].a(),                  mars.memory()[2].a());
        assert_eq!(prog[1].a_mode(),             mars.memory()[2].a_mode());
        assert_eq!(prog[1].b(),                  mars.memory()[2].b());
        assert_eq!(prog[1].b_mode(),             mars.memory()[2].b_mode());
        assert_eq!(init_pc + 1,                  mars.pc());
    }

    #[test]
    fn test_seq_i_mode()
    {
        let prog = vec![
            InstructionStruct::new(
                OpCode::Seq,
                Modifier::I,
                0,
                AddressingMode::Direct,
                1,
                AddressingMode::Direct
                ),
            InstructionStruct::new(
                OpCode::Seq,
                Modifier::I,
                0,
                AddressingMode::Direct,
                1,
                AddressingMode::Direct
                ),
            InstructionStruct::new(
                OpCode::Seq,
                Modifier::I,
                0,
                AddressingMode::Direct,
                1,
                AddressingMode::Direct
                ),
            InstructionStruct::new(
                OpCode::Seq,
                Modifier::I,
                0,
                AddressingMode::Direct,
                0,
                AddressingMode::Direct
                ),
        ];

        let mut mars: Mars<InstructionStruct> = MarsBuilder::new()
            .max_processes(10)
            .build_and_load(vec![(0, None, &prog)])
            .unwrap();

        let init_pc = mars.pc();

        assert_eq!(Ok(SimulationEvent::Skipped), mars.step());
        assert_eq!(init_pc + 2, mars.pc());

        assert_eq!(Ok(SimulationEvent::Stepped), mars.step());
        assert_eq!(init_pc + 3, mars.pc());
    }

    #[test]
    fn test_spl_cant_create_more_than_max_processes()
    {
        // splitter program, infinitely creates imps
        let prog = vec![
            InstructionStruct::new(
                OpCode::Spl,
                Modifier::I,
                2,
                AddressingMode::Direct,
                1,
                AddressingMode::Direct,
                ),
            InstructionStruct::new(
                OpCode::Jmp,
                Modifier::I,
                -1,
                AddressingMode::Direct,
                1,
                AddressingMode::Direct,
                ),
            InstructionStruct::new(
                OpCode::Mov,
                Modifier::I,
                0,
                AddressingMode::Direct,
                1,
                AddressingMode::Direct,
            ),
        ];

        let mut mars: Mars<InstructionStruct> = MarsBuilder::new()
            .max_processes(10)
            .build_and_load(vec![(0, None, &prog)])
            .unwrap();

        assert_eq!(Ok(SimulationEvent::Split), mars.step());

        // run the simulation until it halts because cycles have been exauste
        while !mars.halted() {
            let _ = mars.step();
        }
        
        assert_eq!(10, mars.process_count());
    }
}