bladeink 1.2.3

This is a Rust port of inkle's ink, a scripting language for writing interactive narrative.
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
1484
1485
1486
use std::{cell::RefCell, collections::HashMap, rc::Rc};

use crate::{
    callstack::CallStack,
    choice::Choice,
    container::Container,
    control_command::{CommandType, ControlCommand},
    flow::Flow,
    glue::Glue,
    ink_list::InkList,
    json::{json_read, json_write},
    list_definitions_origin::ListDefinitionsOrigin,
    object::{Object, RTObject},
    path::Path,
    pointer::{self, Pointer},
    push_pop::PushPopType,
    state_patch::StatePatch,
    story::{Story, INK_VERSION_CURRENT},
    story_error::StoryError,
    tag::Tag,
    value::Value,
    value_type::{StringValue, ValueType},
    variables_state::VariablesState,
    void::Void,
};

use rand::RngExt;
use serde_json::{json, Map};

pub const INK_SAVE_STATE_VERSION: u32 = 10;
pub const MIN_COMPATIBLE_LOAD_VERSION: u32 = 8;

static DEFAULT_FLOW_NAME: &str = "DEFAULT_FLOW";

pub(crate) struct StoryState {
    pub current_flow: Flow,
    pub did_safe_exit: bool,
    output_stream_text_dirty: bool,
    output_stream_tags_dirty: bool,
    pub variables_state: VariablesState,
    alive_flow_names_dirty: bool,
    pub evaluation_stack: Vec<Rc<dyn RTObject>>,
    main_content_container: Rc<Container>,
    current_errors: Vec<String>,
    current_warnings: Vec<String>,
    current_text: Option<String>,
    patch: Option<StatePatch>,
    named_flows: Option<HashMap<String, Flow>>,
    pub diverted_pointer: Pointer,
    pub visit_counts: HashMap<String, i32>,
    pub turn_indices: HashMap<String, i32>,
    pub current_turn_index: i32,
    pub story_seed: i32,
    pub previous_random: i32,
    current_tags: Vec<String>,
    list_definitions: Rc<ListDefinitionsOrigin>,
}

impl StoryState {
    pub fn new(
        main_content_container: Rc<Container>,
        list_definitions: Rc<ListDefinitionsOrigin>,
    ) -> StoryState {
        let current_flow = Flow::new(DEFAULT_FLOW_NAME, main_content_container.clone());
        let callstack = current_flow.callstack.clone();

        let mut rng = rand::rng();
        let story_seed = rng.random_range(0..100);

        let state = StoryState {
            current_flow,
            did_safe_exit: false,
            output_stream_text_dirty: true,
            output_stream_tags_dirty: true,
            variables_state: VariablesState::new(callstack, list_definitions.clone()),
            alive_flow_names_dirty: true,
            evaluation_stack: Vec::new(),
            main_content_container,
            current_errors: Vec::with_capacity(0),
            current_warnings: Vec::with_capacity(0),
            current_text: None,
            patch: None,
            named_flows: None,
            diverted_pointer: pointer::NULL.clone(),
            visit_counts: HashMap::new(),
            turn_indices: HashMap::new(),
            current_turn_index: -1,
            story_seed,
            previous_random: 0,
            current_tags: Vec::with_capacity(0),
            list_definitions,
        };

        state.go_to_start();

        state
    }

    pub fn can_continue(&self) -> bool {
        !self.get_current_pointer().is_null() && !self.has_error()
    }

    pub fn has_error(&self) -> bool {
        !self.current_errors.is_empty()
    }

    /// String representation of the location where the story currently is.
    pub fn current_path_string(&self) -> Option<String> {
        let pointer = self.get_current_pointer();
        pointer.get_path().map(|path| path.to_string())
    }

    /// Get the previous state of currentPathString, which can be helpful
    /// for finding out where the story was before it ended (when the path
    /// string becomes null)
    ///
    /// Marked as dead code by now.
    #[allow(dead_code)]
    pub fn previous_path_string(&self) -> Option<String> {
        let pointer = self.get_previous_pointer();
        pointer.get_path().map(|path| path.to_string())
    }

    pub fn get_current_pointer(&self) -> Pointer {
        self.get_callstack()
            .borrow()
            .get_current_element()
            .current_pointer
            .clone()
    }

    pub fn get_callstack(&self) -> &Rc<RefCell<CallStack>> {
        &self.current_flow.callstack
    }

    pub fn set_did_safe_exit(&mut self, did_safe_exit: bool) {
        self.did_safe_exit = did_safe_exit;
    }

    pub fn reset_output(&mut self, objs: Option<Vec<Rc<dyn RTObject>>>) {
        self.get_output_stream_mut().clear();
        if let Some(objs) = objs {
            for o in objs {
                self.get_output_stream_mut().push(o.clone());
            }
        }
        self.output_stream_dirty();
    }

    pub fn get_generated_choices_mut(&mut self) -> &mut Vec<Rc<Choice>> {
        &mut self.current_flow.current_choices
    }

    pub fn get_generated_choices(&self) -> &Vec<Rc<Choice>> {
        &self.current_flow.current_choices
    }

    pub fn is_did_safe_exit(&self) -> bool {
        self.did_safe_exit
    }

    pub fn has_warning(&self) -> bool {
        !self.current_warnings.is_empty()
    }

    pub fn get_current_errors(&self) -> &[String] {
        &self.current_errors
    }

    pub fn get_current_warnings(&self) -> &[String] {
        &self.current_warnings
    }

    pub fn get_output_stream(&self) -> &Vec<Rc<dyn RTObject>> {
        &self.current_flow.output_stream
    }

    fn get_output_stream_mut(&mut self) -> &mut Vec<Rc<dyn RTObject>> {
        &mut self.current_flow.output_stream
    }

    fn output_stream_dirty(&mut self) {
        self.output_stream_text_dirty = true;
        self.output_stream_tags_dirty = true;
    }

    pub fn in_string_evaluation(&self) -> bool {
        for e in self.get_output_stream().iter().rev() {
            if let Some(cmd) = e.as_any().downcast_ref::<ControlCommand>()
                && cmd.command_type == CommandType::BeginString {
                    return true;
                }
        }
        false
    }

    pub fn get_current_text(&mut self) -> String {
        if self.output_stream_text_dirty {
            let mut sb = String::new();
            let mut in_tag = false;

            for output_obj in self.get_output_stream() {
                let text_content = Value::get_value::<&StringValue>(output_obj.as_ref());

                if let (false, Some(text_content)) = (in_tag, text_content) {
                    sb.push_str(&text_content.string);
                } else if let Some(control_command) = output_obj
                    .as_ref()
                    .as_any()
                    .downcast_ref::<ControlCommand>()
                {
                    if control_command.command_type == CommandType::BeginTag {
                        in_tag = true;
                    } else if control_command.command_type == CommandType::EndTag {
                        in_tag = false;
                    }
                }
            }

            self.current_text = Some(StoryState::clean_output_whitespace(&sb));

            self.output_stream_text_dirty = false;
        }

        self.current_text.as_ref().unwrap().to_string()
    }

    pub fn get_current_tags(&mut self) -> Vec<String> {
        if self.output_stream_tags_dirty {
            self.current_tags.clear();

            let mut in_tag = false;
            let mut sb = String::new();

            for output_obj in self.get_output_stream().clone() {
                if let Some(control_command) = output_obj
                    .as_ref()
                    .as_any()
                    .downcast_ref::<ControlCommand>()
                {
                    match control_command.command_type {
                        CommandType::BeginTag => {
                            if in_tag && !sb.is_empty() {
                                let txt = Self::clean_output_whitespace(&sb);
                                self.current_tags.push(txt);
                                sb.clear();
                            }
                            in_tag = true;
                        }
                        CommandType::EndTag => {
                            if !sb.is_empty() {
                                let txt = Self::clean_output_whitespace(&sb);
                                self.current_tags.push(txt);
                                sb.clear();
                            }
                            in_tag = false;
                        }
                        _ => {}
                    }
                } else if in_tag {
                    if let Some(string_value) =
                        Value::get_value::<&StringValue>(output_obj.as_ref())
                    {
                        sb.push_str(&string_value.string);
                    }
                    if let Some(tag) = output_obj.as_ref().as_any().downcast_ref::<Tag>()
                        && !tag.get_text().is_empty() {
                            self.current_tags.push(tag.get_text().clone()); // tag.text has whitespace already cleaned
                        }
                }
            }

            if !sb.is_empty() {
                let txt = Self::clean_output_whitespace(&sb);
                self.current_tags.push(txt);
                sb.clear();
            }

            self.output_stream_tags_dirty = false;
        }

        self.current_tags.clone()
    }

    pub fn clean_output_whitespace(input_str: &str) -> String {
        let mut sb = String::with_capacity(input_str.len());
        let mut current_whitespace_start = -1;
        let mut start_of_line = 0;

        for (i, c) in input_str.chars().enumerate() {
            let is_inline_whitespace = c == ' ' || c == '\t';

            if is_inline_whitespace && current_whitespace_start == -1 {
                current_whitespace_start = i as i32;
            }

            if !is_inline_whitespace {
                if c != '\n'
                    && current_whitespace_start > 0
                    && current_whitespace_start != start_of_line
                {
                    sb.push(' ');
                }
                current_whitespace_start = -1;
            }

            if c == '\n' {
                start_of_line = i as i32 + 1;
            }

            if !is_inline_whitespace {
                sb.push(c);
            }
        }

        sb
    }

    pub fn output_stream_ends_in_newline(&self) -> bool {
        if !self.get_output_stream().is_empty() {
            for e in self.get_output_stream().iter().rev() {
                if e.as_any().is::<ControlCommand>() {
                    break;
                }

                if let Some(val) = e.as_any().downcast_ref::<Value>()
                    && let ValueType::String(text) = &val.value {
                        if text.is_newline {
                            return true;
                        } else if text.is_non_whitespace() {
                            break;
                        }
                    }
            }
        }

        false
    }

    pub fn set_current_pointer(&self, pointer: Pointer) {
        self.get_callstack()
            .as_ref()
            .borrow_mut()
            .get_current_element_mut()
            .current_pointer = pointer;
    }

    pub fn get_in_expression_evaluation(&self) -> bool {
        self.get_callstack()
            .borrow()
            .get_current_element()
            .in_expression_evaluation
    }

    pub fn set_in_expression_evaluation(&self, value: bool) {
        self.get_callstack()
            .borrow_mut()
            .get_current_element_mut()
            .in_expression_evaluation = value;
    }

    pub fn push_evaluation_stack(&mut self, obj: Rc<dyn RTObject>) {
        if let Some(list) = Value::get_value::<&InkList>(obj.as_ref()) {
            let origin_names = list.get_origin_names();

            list.origins.borrow_mut().clear();

            for name in &origin_names {
                let def = self.list_definitions.get_list_definition(name).unwrap();
                if !list.origins.borrow().iter().any(|e| std::ptr::eq(e, def)) {
                    list.origins.borrow_mut().push(def.clone());
                }
            }
        }

        self.evaluation_stack.push(obj);
    }

    pub fn push_to_output_stream(&mut self, obj: Rc<dyn RTObject>) {
        let text = Value::get_value::<&StringValue>(obj.as_ref());

        if let Some(s) = text {
            let list_text = StoryState::try_splitting_head_tail_whitespace(&s.string);

            if let Some(list_text) = list_text {
                for text_obj in list_text {
                    self.push_to_output_stream_individual(Rc::new(text_obj));
                }
                self.output_stream_dirty();
                return;
            }
        }

        self.push_to_output_stream_individual(obj);
    }

    pub fn increment_visit_count_for_container(&mut self, container: &Rc<Container>) {
        let has_patch = self.patch.is_some();

        if has_patch {
            let curr_count = self.visit_count_for_container(container);
            let new_count = curr_count + 1;
            self.patch
                .as_mut()
                .unwrap()
                .set_visit_count(container, new_count);
        } else {
            let mut count = 0;
            let container_path_str = container.get_path().to_string();

            if let Some(&existing_count) = self.visit_counts.get(&container_path_str) {
                count = existing_count;
            }

            count += 1;
            self.visit_counts.insert(container_path_str, count);
        }
    }

    pub fn visit_count_for_container(&mut self, container: &Rc<Container>) -> i32 {
        if !container.visits_should_be_counted {
            // TODO

            // story.error(format!(
            //     "Read count for target ({:?} - on {:?}) unknown.",
            //     container.get_name(),
            //     container.get_debug_metadata()
            // ));
            return 0;
        }

        if let Some(patch) = &self.patch
            && let Some(visit_count) = patch.get_visit_count(container) {
                return visit_count;
            }

        let container_path_str = container.get_path().to_string();

        if let Some(&count) = self.visit_counts.get(&container_path_str) {
            return count;
        }

        0
    }

    pub fn record_turn_index_visit_to_container(&mut self, container: &Container) {
        if let Some(patch) = &mut self.patch {
            patch.set_turn_index(container, self.current_turn_index);
            return;
        }

        let container_path_str = Object::get_path(container).to_string();
        self.turn_indices
            .insert(container_path_str, self.current_turn_index);
    }

    fn try_splitting_head_tail_whitespace(text: &str) -> Option<Vec<Value>> {
        let mut head_first_newline_idx = -1;
        let mut head_last_newline_idx = -1;
        for (i, c) in text.chars().enumerate() {
            if c == '\n' {
                if head_first_newline_idx == -1 {
                    head_first_newline_idx = i as i32;
                }
                head_last_newline_idx = i as i32;
            } else if c == ' ' || c == '\t' {
                continue;
            } else {
                break;
            }
        }

        let mut tail_last_newline_idx = -1;
        let mut tail_first_newline_idx = -1;
        for (i, c) in text.chars().rev().enumerate() {
            let reversed_i = text.len() as i32 - i as i32 - 1;
            if c == '\n' {
                if tail_last_newline_idx == -1 {
                    tail_last_newline_idx = reversed_i;
                }
                tail_first_newline_idx = reversed_i;
            } else if c == ' ' || c == '\t' {
                continue;
            } else {
                break;
            }
        }

        if head_first_newline_idx == -1 && tail_last_newline_idx == -1 {
            return None;
        }

        let mut list_texts = Vec::new();
        let mut inner_str_start = 0;
        let mut inner_str_end = text.len();

        if head_first_newline_idx != -1 {
            if head_first_newline_idx > 0 {
                let leading_spaces = Value::new::<&str>(&text[0..head_first_newline_idx as usize]);
                list_texts.push(leading_spaces);
            }
            list_texts.push(Value::new::<&str>("\n"));
            inner_str_start = head_last_newline_idx + 1;
        }

        if tail_last_newline_idx != -1 {
            inner_str_end = tail_first_newline_idx as usize;
        }

        if inner_str_end > inner_str_start as usize {
            let inner_str_text = &text[inner_str_start as usize..inner_str_end];
            list_texts.push(Value::new::<&str>(inner_str_text));
        }

        if tail_last_newline_idx != -1 && tail_first_newline_idx > head_last_newline_idx {
            list_texts.push(Value::new::<&str>("\n"));
            if tail_last_newline_idx < text.len() as i32 - 1 {
                let num_spaces = (text.len() as i32 - tail_last_newline_idx) - 1;
                let trailing_spaces = Value::new::<&str>(
                    &text[(tail_last_newline_idx + 1) as usize
                        ..(num_spaces + tail_last_newline_idx + 1) as usize],
                );
                list_texts.push(trailing_spaces);
            }
        }

        Some(list_texts)
    }

    fn push_to_output_stream_individual(&mut self, obj: Rc<dyn RTObject>) {
        let glue = obj.clone().into_any().downcast::<Glue>();
        let text = Value::get_value::<&StringValue>(obj.as_ref());
        let mut include_in_output = true;

        // New glue, so chomp away any whitespace from the end of the stream
        if glue.is_ok() {
            self.trim_newlines_from_output_stream();
            include_in_output = true;
        }
        // New text: do we really want to append it, if it's whitespace?
        // Two different reasons for whitespace to be thrown away:
        // - Function start/end trimming
        // - User-defined glue: <>
        // We also need to know when to stop trimming when there's non-whitespace.
        else if let Some(text) = text {
            let mut function_trim_index = -1;

            {
                // block to release cs borrow
                let cs = self.get_callstack().borrow();
                let curr_el = cs.get_current_element();
                if curr_el.push_pop_type == PushPopType::Function {
                    function_trim_index = curr_el.function_start_in_output_stream;
                }
            }

            let mut glue_trim_index = -1;
            for (i, o) in self.get_output_stream().iter().rev().enumerate() {
                let i = self.get_output_stream().len() - i - 1;
                if let Some(c) = o.as_ref().as_any().downcast_ref::<ControlCommand>() {
                    if c.command_type == CommandType::BeginString {
                        if i as i32 >= function_trim_index {
                            function_trim_index = -1;
                        }

                        break;
                    }
                } else if o.as_ref().as_any().is::<Glue>() {
                    glue_trim_index = i as i32;
                    break;
                }
            }

            let trim_index;
            if glue_trim_index != -1 && function_trim_index != -1 {
                trim_index = function_trim_index.min(glue_trim_index);
            } else if glue_trim_index != -1 {
                trim_index = glue_trim_index;
            } else {
                trim_index = function_trim_index;
            }

            if trim_index != -1 {
                if text.is_newline {
                    include_in_output = false;
                } else if text.is_non_whitespace() {
                    if glue_trim_index > -1 {
                        self.remove_existing_glue();
                    }

                    if function_trim_index > -1 {
                        let mut cs = self.get_callstack().as_ref().borrow_mut();
                        let callstack_elements = cs.get_elements_mut();
                        for i in (0..callstack_elements.len()).rev() {
                            if let Some(el) = callstack_elements.get_mut(i) {
                                if el.push_pop_type == PushPopType::Function {
                                    el.function_start_in_output_stream = -1;
                                } else {
                                    break;
                                }
                            }
                        }
                    }
                }
            } else if text.is_newline
                && (self.output_stream_ends_in_newline() || !self.output_stream_contains_content())
            {
                include_in_output = false;
            }
        }

        if include_in_output {
            self.get_output_stream_mut().push(obj);
            self.output_stream_dirty();
        }
    }

    fn trim_newlines_from_output_stream(&mut self) {
        let mut remove_whitespace_from = -1;
        let output_stream = self.get_output_stream_mut();

        // Work back from the end, and try to find the point where
        // we need to start removing content.
        // - Simply work backwards to find the first newline in a String of
        // whitespace
        // e.g. This is the content \n \n\n
        // ^---------^ whitespace to remove
        // ^--- first while loop stops here
        let mut i = output_stream.len() as i32 - 1;
        while i >= 0 {
            if let Some(obj) = output_stream.get(i as usize) {
                if obj.as_ref().as_any().is::<ControlCommand>() {
                    break;
                } else if let Some(sv) = Value::get_value::<&StringValue>(obj.as_ref()) {
                    if sv.is_non_whitespace() {
                        break;
                    } else if sv.is_newline {
                        remove_whitespace_from = i;
                    }
                }
            }
            i -= 1;
        }

        // Remove the whitespace
        if remove_whitespace_from >= 0 {
            i = remove_whitespace_from;
            while i < output_stream.len() as i32 {
                if Value::get_value::<&StringValue>(output_stream[i as usize].as_ref()).is_some() {
                    output_stream.remove(i as usize);
                } else {
                    i += 1;
                }
            }
        }

        self.output_stream_dirty();
    }

    fn remove_existing_glue(&mut self) {
        let output_stream = self.get_output_stream_mut();

        let mut i = output_stream.len() as i32 - 1;
        while i >= 0 {
            if let Some(c) = output_stream.get(i as usize) {
                if c.as_ref().as_any().is::<Glue>() {
                    output_stream.remove(i as usize);
                } else if c.as_ref().as_any().is::<ControlCommand>() {
                    break;
                }
            }
            i -= 1;
        }

        self.output_stream_dirty();
    }

    fn output_stream_contains_content(&self) -> bool {
        for content in self.get_output_stream() {
            if let Some(v) = content.as_any().downcast_ref::<Value>()
                && let ValueType::String(_) = v.value {
                    return true;
                }
        }

        false
    }

    pub fn set_previous_pointer(&self, p: Pointer) {
        self.get_callstack()
            .as_ref()
            .borrow_mut()
            .get_current_thread_mut()
            .previous_pointer = p.clone();
    }

    pub fn get_previous_pointer(&self) -> Pointer {
        self.get_callstack()
            .as_ref()
            .borrow_mut()
            .get_current_thread_mut()
            .previous_pointer
            .clone()
    }

    pub fn try_exit_function_evaluation_from_game(&mut self) -> bool {
        if self
            .get_callstack()
            .borrow()
            .get_current_element()
            .push_pop_type
            == PushPopType::FunctionEvaluationFromGame
        {
            self.set_current_pointer(pointer::NULL.clone());
            self.did_safe_exit = true;
            return true;
        }

        false
    }

    pub fn pop_callstack(&mut self, t: Option<PushPopType>) -> Result<(), StoryError> {
        // Add the end of a function call, trim any whitespace from the end.
        if self
            .get_callstack()
            .borrow()
            .get_current_element()
            .push_pop_type
            == PushPopType::Function
        {
            self.trim_whitespace_from_function_end();
        }

        self.get_callstack().borrow_mut().pop(t)
    }

    fn go_to_start(&self) {
        self.get_callstack()
            .as_ref()
            .borrow_mut()
            .get_current_element_mut()
            .current_pointer = Pointer::start_of(self.main_content_container.clone())
    }

    pub fn get_current_choices(&self) -> Option<&Vec<Rc<Choice>>> {
        // If we can continue generating text content rather than choices,
        // then we reflect the choice list as being empty, since choices
        // should always come at the end.
        if self.can_continue() {
            return None;
        }

        Some(&self.current_flow.current_choices)
    }

    pub fn copy_and_start_patching(&self, for_background_save: bool) -> StoryState {
        let mut copy = StoryState::new(
            self.main_content_container.clone(),
            self.list_definitions.clone(),
        );

        copy.patch = Some(self.patch.clone().unwrap_or_else(StatePatch::new));

        // Hijack the new default flow to become a copy of our current one
        // If the patch is applied, then this new flow will replace the old one in
        // _namedFlows
        copy.current_flow.name = self.current_flow.name.clone();
        copy.current_flow.callstack = Rc::new(RefCell::new(
            self.current_flow.callstack.as_ref().borrow().clone(),
        ));
        copy.current_flow.output_stream = self.current_flow.output_stream.clone();
        copy.output_stream_dirty();

        // When background saving we need to make copies of choices since they each have
        // a snapshot of the thread at the time of generation since the game could progress
        // significantly and threads modified during the save process.
        // However, when doing internal saving and restoring of snapshots this isn't an issue,
        // and we can simply ref-copy the choices with their existing threads.
        if for_background_save {
            copy.current_flow.current_choices =
                Vec::with_capacity(self.current_flow.current_choices.len());

            for choice in self.current_flow.current_choices.iter() {
                let c = choice.as_ref().clone();
                copy.current_flow.current_choices.push(Rc::new(c));
            }
        } else {
            copy.current_flow.current_choices = self.current_flow.current_choices.clone();
        }

        // The copy of the state has its own copy of the named flows dictionary,
        // except with the current flow replaced with the copy above
        // (Assuming we're in multi-flow mode at all. If we're not then
        // the above copy is simply the default flow copy and we're done)
        if self.named_flows.is_some() {
            let mut nf = self.named_flows.clone();
            nf.as_mut().unwrap().insert(
                copy.current_flow.name.to_string(),
                copy.current_flow.clone(),
            );
            copy.alive_flow_names_dirty = true;

            copy.named_flows = nf;
        }

        if self.has_error() {
            copy.current_errors = self.current_errors.clone();
        }

        if self.has_warning() {
            copy.current_warnings = self.current_warnings.clone();
        }

        // ref copy - exactly the same variables state!
        // we're expecting not to read it only while in patch mode
        // (though the callstack will be modified)
        copy.variables_state = self.variables_state.clone();
        copy.variables_state
            .set_callstack(copy.get_callstack().clone());
        copy.variables_state.patch = copy.patch.clone();

        copy.evaluation_stack = self.evaluation_stack.clone();

        if !self.diverted_pointer.is_null() {
            copy.diverted_pointer = self.diverted_pointer.clone();
        }

        copy.set_previous_pointer(self.get_previous_pointer().clone());

        // visit counts and turn indicies will be read only, not modified
        // while in patch mode
        copy.visit_counts = self.visit_counts.clone();
        copy.turn_indices = self.turn_indices.clone();

        copy.current_turn_index = self.current_turn_index;
        copy.story_seed = self.story_seed;
        copy.previous_random = self.previous_random;

        copy.set_did_safe_exit(self.did_safe_exit);

        copy
    }

    pub fn restore_after_patch(&mut self) {
        // VariablesState was being borrowed by the patched
        // state, so restore it with our own callstack.
        // _patch will be null normally, but if you're in the
        // middle of a save, it may contain a _patch for save purpsoes.
        self.variables_state.callstack = self.get_callstack().clone();
        self.variables_state.patch = self.patch.clone(); // usually null
    }

    pub fn apply_any_patch(&mut self) {
        if self.patch.is_none() {
            return;
        }

        self.variables_state.apply_patch();

        if self.patch.is_some() {
            for (path, count) in self.patch.as_ref().unwrap().visit_counts.clone().iter() {
                self.apply_count_changes(path, *count, true);
            }

            for (path, index) in self.patch.as_ref().unwrap().turn_indices.clone().iter() {
                self.apply_count_changes(path, *index, false);
            }
        }

        self.patch = None;
    }

    fn apply_count_changes(&mut self, container: &str, new_count: i32, is_visit: bool) {
        let counts = if is_visit {
            &mut self.visit_counts
        } else {
            &mut self.turn_indices
        };

        counts.insert(container.to_string(), new_count);
    }

    pub fn pop_from_output_stream(&mut self, count: usize) {
        let len = self.get_output_stream().len();

        if count <= len {
            let start = len - count;
            self.get_output_stream_mut().drain(start..len);
        }

        self.output_stream_dirty();
    }

    pub fn pop_evaluation_stack(&mut self) -> Rc<dyn RTObject> {
        self.evaluation_stack.pop().unwrap()
    }

    pub fn pop_evaluation_stack_multiple(
        &mut self,
        number_of_objects: usize,
    ) -> Vec<Rc<dyn RTObject>> {
        let start = self.evaluation_stack.len() - number_of_objects;
        let obj: Vec<Rc<dyn RTObject>> = self.evaluation_stack.drain(start..).collect();

        obj
    }

    pub fn set_diverted_pointer(&mut self, p: Pointer) {
        self.diverted_pointer = p;
    }

    pub fn set_chosen_path(
        &mut self,
        path: &Path,
        incrementing_turn_index: bool,
    ) -> Result<(), StoryError> {
        // Changing direction, assume we need to clear current set of choices
        self.current_flow.current_choices.clear();

        let mut new_pointer = Story::pointer_at_path(&self.main_content_container, path)?;
        if !new_pointer.is_null() && new_pointer.index == -1 {
            new_pointer.index = 0;
        }

        self.set_current_pointer(new_pointer);

        if incrementing_turn_index {
            self.current_turn_index += 1;
        }

        Ok(())
    }

    pub(crate) fn force_end(&mut self) {
        self.get_callstack().borrow_mut().reset();

        self.current_flow.current_choices.clear();

        self.set_current_pointer(pointer::NULL.clone());
        self.set_previous_pointer(pointer::NULL.clone());

        self.set_did_safe_exit(true);
    }

    // At the end of a function call, trim any whitespace from the end.
    // We always trim the start and end of the text that a function produces.
    // The start whitespace is discard as it is generated, and the end
    // whitespace is trimmed in one go here when we pop the function.
    fn trim_whitespace_from_function_end(&mut self) {
        assert_eq!(
            self.get_callstack()
                .borrow()
                .get_current_element()
                .push_pop_type,
            PushPopType::Function
        );

        let function_start_point = match self
            .get_callstack()
            .borrow()
            .get_current_element()
            .function_start_in_output_stream
        {
            -1 => 0,
            start_point => start_point,
        };

        // Trim whitespace from END of function call
        let mut i = self.get_output_stream().len() as isize - 1;
        while i >= function_start_point as isize {
            if let Some(obj) = self.get_output_stream().get(i as usize) {
                if obj.as_any().is::<ControlCommand>() {
                    break;
                }

                if let Some(txt) = Value::get_value::<&StringValue>(obj.as_ref()) {
                    if txt.is_newline || txt.is_inline_whitespace {
                        self.get_output_stream_mut().remove(i as usize);
                        self.output_stream_dirty();
                    } else {
                        break;
                    }
                }
            }
            i -= 1;
        }
    }

    pub fn peek_evaluation_stack(&self) -> Option<&Rc<dyn RTObject>> {
        self.evaluation_stack.last()
    }

    pub fn start_function_evaluation_from_game(
        &mut self,
        func_container: Rc<Container>,
        arguments: Option<&Vec<ValueType>>,
    ) -> Result<(), StoryError> {
        self.get_callstack().borrow_mut().push(
            PushPopType::FunctionEvaluationFromGame,
            self.evaluation_stack.len(),
            0,
        );
        self.get_callstack()
            .borrow_mut()
            .get_current_element_mut()
            .current_pointer = Pointer::start_of(func_container);

        self.pass_arguments_to_evaluation_stack(arguments)?;

        Ok(())
    }

    pub fn pass_arguments_to_evaluation_stack(
        &mut self,
        arguments: Option<&Vec<ValueType>>,
    ) -> Result<(), StoryError> {
        // Pass arguments onto the evaluation stack
        if let Some(arguments) = arguments {
            for arg in arguments {
                let value = match arg {
                    ValueType::Bool(v) => Value::new::<bool>(*v),
                    ValueType::Int(v) => Value::new::<i32>(*v),
                    ValueType::Float(v) => Value::new::<f32>(*v),
                    ValueType::List(v) => Value::new::<InkList>(v.clone()),
                    ValueType::String(v) => Value::new::<&str>(&v.string),
                    _ => {
                        return Err(StoryError::InvalidStoryState("ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must be \
                        int, float, string, bool or InkList.".to_owned()));
                    }
                };

                self.push_evaluation_stack(Rc::new(value));
            }
        }

        Ok(())
    }

    pub fn complete_function_evaluation_from_game(
        &mut self,
    ) -> Result<Option<ValueType>, StoryError> {
        if self
            .get_callstack()
            .borrow()
            .get_current_element()
            .push_pop_type
            != PushPopType::FunctionEvaluationFromGame
        {
            return Err(StoryError::InvalidStoryState(format!(
                "Expected external function evaluation to be complete. Stack trace: {}",
                self.get_callstack().borrow().get_callstack_trace()
            )));
        }

        let original_evaluation_stack_height = self
            .get_callstack()
            .borrow()
            .get_current_element()
            .evaluation_stack_height_when_pushed;

        // Do we have a returned value?
        // Potentially pop multiple values off the stack, in case we need
        // to clean up after ourselves (e.g. caller of EvaluateFunction may
        // have passed too many arguments, and we currently have no way to check
        // for that)
        let mut returned_obj = None;
        while self.evaluation_stack.len() > original_evaluation_stack_height {
            let popped_obj = self.pop_evaluation_stack();
            if returned_obj.is_none() {
                returned_obj = Some(popped_obj);
            }
        }

        // Finally, pop the external function evaluation
        self.get_callstack()
            .borrow_mut()
            .pop(Some(PushPopType::FunctionEvaluationFromGame))?;

        // What did we get back?
        if let Some(returned_obj) = returned_obj {
            if returned_obj.as_ref().as_any().is::<Void>() {
                return Ok(None);
            }

            // Some kind of value, if not void
            if let Some(return_val) = returned_obj.as_ref().as_any().downcast_ref::<Value>() {
                // DivertTargets get returned as the string of components
                // (rather than a Path, which isn't public)
                if let ValueType::DivertTarget(p) = &return_val.value {
                    return Ok(Some(ValueType::new::<&str>(&p.to_string())));
                }

                // Other types can just have their exact object type:
                // int, float, string. VariablePointers get returned as strings.
                return Ok(Some(return_val.value.clone()));
            }
        }

        Ok(None)
    }

    pub(crate) fn turns_since_for_container(
        &self,
        container: &Container,
    ) -> Result<i32, StoryError> {
        if !container.turn_index_should_be_counted {
            return Err(StoryError::InvalidStoryState(format!(
                "TURNS_SINCE() for target ({}) unknown.",
                container.name.as_ref().unwrap()
            )));
        }

        if self.patch.is_some()
            && self
                .patch
                .as_ref()
                .unwrap()
                .get_turn_index(container)
                .is_some()
        {
            let index = *self
                .patch
                .as_ref()
                .unwrap()
                .get_turn_index(container)
                .unwrap();
            return Ok(self.current_turn_index - index);
        }

        let container_path_str = Object::get_path(container).to_string();

        if self.turn_indices.contains_key(&container_path_str) {
            let index = *self.turn_indices.get(&container_path_str).unwrap();
            Ok(self.current_turn_index - index)
        } else {
            Ok(-1)
        }
    }

    pub(crate) fn switch_flow_internal(&mut self, flow_name: &str) {
        if flow_name.eq(&self.current_flow.name) {
            return;
        }

        if self.named_flows.is_none() {
            self.named_flows = Some(HashMap::new());
        }

        let named_flows = self.named_flows.as_mut().unwrap();

        // store the current flow and retrieve and remove the next flow
        let flow = named_flows.remove(flow_name);

        let mut next_flow = match flow {
            Some(f) => f,
            None => {
                self.alive_flow_names_dirty = true;
                Flow::new(flow_name, self.main_content_container.clone())
            }
        };

        std::mem::swap(&mut self.current_flow, &mut next_flow);
        named_flows.insert(next_flow.name.clone(), next_flow);

        self.variables_state
            .set_callstack(self.current_flow.callstack.clone());

        // Cause text to be regenerated from output stream if necessary
        self.output_stream_dirty();
    }

    pub fn visit_count_at_path_string(&self, path_string: &str) -> Result<i32, StoryError> {
        let mut visit_count_out;

        if self.patch.is_some() {
            let container = self
                .main_content_container
                .content_at_path(&Path::new_with_components_string(Some(path_string)), 0, -1)
                .container();
            if container.is_none() {
                return Err(StoryError::InvalidStoryState(format!(
                    "Content at path not found: {}",
                    path_string
                )));
            }

            visit_count_out = self
                .patch
                .as_ref()
                .unwrap()
                .get_visit_count(container.as_ref().unwrap());
            if let Some(visit_count_out) = visit_count_out {
                return Ok(visit_count_out);
            }
        }

        visit_count_out = self.visit_counts.get(path_string).copied();
        if let Some(visit_count_out) = visit_count_out {
            return Ok(visit_count_out);
        }

        Ok(0)
    }

    pub fn to_json(&self) -> Result<String, StoryError> {
        Ok(self.write_json()?.to_string())
    }

    pub fn load_json(&mut self, save_string: &str) -> Result<(), StoryError> {
        match serde_json::from_str(save_string) {
            Ok(value) => self.load_json_obj(value),
            Err(_) => Err(StoryError::BadJson("State not in JSON format.".to_owned())),
        }
    }

    fn write_json(&self) -> Result<serde_json::Value, StoryError> {
        let mut obj: Map<String, serde_json::Value> = Map::new();

        // Flows
        let mut flows: Map<String, serde_json::Value> = Map::new();

        // current flow
        flows.insert(
            self.current_flow.name.clone(),
            self.current_flow.write_json()?,
        );

        // named flows
        if let Some(named_flows) = &self.named_flows {
            for (k, v) in named_flows {
                flows.insert(k.clone(), v.write_json()?);
            }
        }

        obj.insert("flows".to_owned(), serde_json::Value::Object(flows));

        obj.insert("currentFlowName".to_owned(), json!(self.current_flow.name));
        obj.insert(
            "variablesState".to_owned(),
            self.variables_state.write_json()?,
        );
        obj.insert(
            "evalStack".to_owned(),
            json_write::write_list_rt_objs(&self.evaluation_stack)?,
        );

        if !self.diverted_pointer.is_null() {
            obj.insert(
                "currentDivertTarget".to_owned(),
                json!(self
                    .diverted_pointer
                    .get_path()
                    .unwrap()
                    .get_components_string()),
            );
        }

        obj.insert(
            "visitCounts".to_owned(),
            json_write::write_int_dictionary(&self.visit_counts),
        );
        obj.insert(
            "turnIndices".to_owned(),
            json_write::write_int_dictionary(&self.turn_indices),
        );

        obj.insert("turnIdx".to_owned(), json!(self.current_turn_index));
        obj.insert("storySeed".to_owned(), json!(self.story_seed));
        obj.insert("previousRandom".to_owned(), json!(self.previous_random));

        obj.insert("inkSaveVersion".to_owned(), json!(INK_SAVE_STATE_VERSION));

        // Not using this right now, but could do in future.
        obj.insert("inkFormatVersion".to_owned(), json!(INK_VERSION_CURRENT));

        Ok(serde_json::Value::Object(obj))
    }

    fn load_json_obj(&mut self, j_object: serde_json::Value) -> Result<(), StoryError> {
        let j_save_version = match j_object.get("inkSaveVersion") {
            Some(version) => version,
            None => {
                return Err(StoryError::BadJson(
                    "ink save format incorrect, can't load.".to_owned(),
                ))
            }
        };

        if let Some(version) = j_save_version.as_i64()
            && version < MIN_COMPATIBLE_LOAD_VERSION as i64 {
                return Err(StoryError::BadJson(format!(
                    "Ink save format isn't compatible with the current version (saw '{}', but minimum is {}), so can't load.",
                    version,
                    MIN_COMPATIBLE_LOAD_VERSION
                )));
            }

        // Flows: Always exists in latest format (even if there's just one default)
        // but this dictionary doesn't exist in prev format
        if let Some(flows_obj) = j_object.get("flows") {
            let flows_obj_dict = flows_obj
                .as_object()
                .ok_or_else(|| StoryError::BadJson("Invalid flows object".to_string()))?;

            // Single default flow
            if flows_obj_dict.len() == 1 {
                self.named_flows = None;
            }
            // Multi-flow, need to create flows dict
            else if self.named_flows.is_none() {
                self.named_flows = Some(HashMap::new());
            }
            // Multi-flow, already have a flows dict
            else {
                self.named_flows.as_mut().unwrap().clear();
            }

            // Load up each flow (there may only be one)
            for (named_flow_name, named_flow_obj) in flows_obj_dict.iter() {
                let name = named_flow_name.clone();
                let flow_obj = named_flow_obj
                    .as_object()
                    .ok_or_else(|| StoryError::BadJson("Invalid flow object".to_string()))?;

                // Load up this flow using JSON data
                let flow = Flow::from_json(&name, self.main_content_container.clone(), flow_obj)?;

                if flows_obj_dict.len() == 1 {
                    self.current_flow =
                        Flow::from_json(&name, self.main_content_container.clone(), flow_obj)?;
                } else {
                    self.named_flows
                        .as_mut()
                        .ok_or_else(|| {
                            StoryError::BadJson("Named flows should be initialized".to_string())
                        })?
                        .insert(name, flow);
                }
            }

            if let Some(named_flows) = &mut self.named_flows
                && named_flows.len() > 1
                    && let Some(current_flow_name) = j_object.get("currentFlowName")
                        && let Some(curr_flow_name) = current_flow_name.as_str()
                            && let Some(curr_flow) = named_flows.get(curr_flow_name) {
                                self.current_flow = curr_flow.clone();
                                named_flows.remove(curr_flow_name);
                            }
        }
        // Old format: individually load up callstack, output stream, choices in
        // current/default flow
        else {
            self.named_flows = None;
            self.current_flow.name = "default".to_owned(); // Replace with the default flow name
            self.current_flow.callstack.borrow_mut().load_json(
                &self.main_content_container,
                j_object
                    .get("callstackThreads")
                    .and_then(|o| o.as_object())
                    .ok_or(StoryError::BadJson("loading callstack threads".to_owned()))?,
            )?;

            if let Some(output_stream_obj) = j_object.get("outputStream") {
                self.current_flow.output_stream = json_read::jarray_to_runtime_obj_list(
                    output_stream_obj.as_array().unwrap(),
                    false,
                )?;
            }

            if let Some(current_choices_obj) = j_object.get("currentChoices") {
                self.current_flow.current_choices = json_read::jarray_to_runtime_obj_list(
                    current_choices_obj.as_array().unwrap(),
                    false,
                )?
                .iter()
                .map(|o| o.clone().into_any().downcast::<Choice>().unwrap())
                .collect();
            }

            let j_choice_threads_obj = j_object.get("choiceThreads");
            self.current_flow.load_flow_choice_threads(
                j_choice_threads_obj,
                self.main_content_container.clone(),
            )?;
        }

        self.output_stream_dirty();
        self.alive_flow_names_dirty = true;

        if let Some(variables_state_obj) = j_object.get("variablesState") {
            self.variables_state
                .load_json(variables_state_obj.as_object().ok_or_else(|| {
                    StoryError::BadJson("Invalid variables state object".to_string())
                })?)?;
            self.variables_state
                .set_callstack(self.current_flow.callstack.clone());
        }

        if let Some(eval_stack_obj) = j_object.get("evalStack") {
            self.evaluation_stack =
                json_read::jarray_to_runtime_obj_list(eval_stack_obj.as_array().unwrap(), false)?;
        }

        if let Some(current_divert_target_path) = j_object.get("currentDivertTarget") {
            let divert_path = Path::new_with_components_string(current_divert_target_path.as_str());
            self.diverted_pointer =
                Story::pointer_at_path(&self.main_content_container, &divert_path)?.clone();
        }

        if let Some(visit_counts_obj) = j_object.get("visitCounts") {
            self.visit_counts =
                json_read::jobject_to_int_hashmap(visit_counts_obj.as_object().ok_or_else(
                    || StoryError::BadJson("Invalid visit counts object".to_string()),
                )?)?;
        }

        if let Some(turn_indices_obj) = j_object.get("turnIndices") {
            self.turn_indices =
                json_read::jobject_to_int_hashmap(turn_indices_obj.as_object().ok_or_else(
                    || StoryError::BadJson("Invalid turn indices object".to_string()),
                )?)?;
        }

        if let Some(current_turn_index) = j_object.get("turnIdx") {
            self.current_turn_index = current_turn_index
                .as_i64()
                .ok_or_else(|| StoryError::BadJson("Invalid current turn index".to_string()))?
                as i32;
        }

        if let Some(story_seed) = j_object.get("storySeed") {
            self.story_seed = story_seed
                .as_i64()
                .ok_or_else(|| StoryError::BadJson("Invalid story seed".to_string()))?
                as i32;
        }

        // Not optional, but bug in inkjs means it's actually missing in inkjs saves
        if let Some(previous_random_obj) = j_object.get("previousRandom") {
            self.previous_random = previous_random_obj
                .as_i64()
                .ok_or_else(|| StoryError::BadJson("Invalid previous random value".to_string()))?
                as i32;
        } else {
            self.previous_random = 0;
        }

        Ok(())
    }

    pub(crate) fn remove_flow_internal(&mut self, flow_name: &str) -> Result<(), StoryError> {
        if flow_name.eq(DEFAULT_FLOW_NAME) {
            return Err(StoryError::BadArgument(
                "Cannot destroy default flow".to_owned(),
            ));
        }

        // If we're currently in the flow that's being removed, switch back to default
        if self.current_flow.name.eq(flow_name) {
            self.switch_to_default_flow_internal();
        }

        self.named_flows.as_mut().unwrap().remove(flow_name);
        self.alive_flow_names_dirty = true;

        Ok(())
    }

    pub(crate) fn switch_to_default_flow_internal(&mut self) {
        if self.named_flows.is_some() {
            self.switch_flow_internal(DEFAULT_FLOW_NAME);
        }
    }

    pub(crate) fn add_error(&mut self, message: String, is_warning: bool) {
        if !is_warning {
            self.current_errors.push(message);
        } else {
            self.current_warnings.push(message);
        }
    }

    pub(crate) fn reset_errors(&mut self) {
        self.current_errors.clear();
    }
}