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
// ## Core

// Cores are the smallest unit of a mech program exposed to a user. They hold references to all the
// subparts of Mech, including the database (defines the what) and the runtime (defines the how).
// The core accepts transactions and applies those to the database. Updated tables in the database
// trigger computation in the runtime, which can further update the database. Execution terminates
// when a steady state is reached, or an iteration limit is reached (whichever comes first). The
// core then waits for further transactions.

// Test

use crate::*;
#[cfg(feature = "stdlib")]
use crate::function::{
  math::*,
  math_update::*,
  compare::*,
  stats::*,
  table::*,
  set::*,
  logic::*,
  matrix::*,
};

use hashbrown::{HashMap, HashSet};
use std::rc::Rc;
use std::cell::RefCell;


pub type BlockRef = Rc<RefCell<Block>>;

pub struct Functions{
  pub functions: HashMap<u64,Box<dyn MechFunctionCompiler>>,
}

impl Functions {
  fn new () -> Functions {
    Functions {
      functions: HashMap::new(),
    }
  }
  pub fn get(&self, key: u64) -> std::option::Option<&Box<dyn MechFunctionCompiler>> {
    self.functions.get(&key)
  }
  pub fn insert(&mut self, key: u64, mut fxn: Box<dyn MechFunctionCompiler>) {
    self.functions.insert(key,fxn);
  }

  pub fn extend(&mut self, other: HashMap<u64,Box<dyn MechFunctionCompiler>>) {
    self.functions.extend(other); 
  }
  
}

impl fmt::Debug for Functions {
  #[inline]
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f,"Functions...")?;
    Ok(())
  }
}


pub struct Core {
  pub sections: Vec<HashMap<BlockId,BlockRef>>,
  pub blocks: HashMap<BlockId,BlockRef>,
  pub unsatisfied_blocks: HashMap<BlockId,BlockRef>,
  pub database: Rc<RefCell<Database>>,
  pub functions: Rc<RefCell<Functions>>,
  pub user_functions: Rc<RefCell<HashMap<u64,UserFunction>>>,
  pub required_functions: HashSet<u64>,
  pub errors: HashMap<MechErrorKind,Vec<BlockRef>>,
  pub full_errors: HashMap<MechError,Vec<BlockRef>>,
  pub input: HashSet<(TableId,RegisterIndex,RegisterIndex)>,
  pub output: HashSet<(TableId,RegisterIndex,RegisterIndex)>,
  pub defined_tables: HashSet<(TableId,RegisterIndex,RegisterIndex)>,
  pub schedule: Schedule,
  pub dictionary: StringDictionary,
}

impl Core {

  pub fn new() -> Core {
    
    
    let mut functions = Functions::new();
    // -----------------
    // Standard Machines
    // -----------------
    let dictionary = Rc::new(RefCell::new(HashMap::new()));
    #[cfg(feature = "stdlib")]
    {
      let mut dict = dictionary.borrow_mut();
      // Math
      functions.insert(*MATH_ADD, Box::new(MathAdd{})); dict.insert(*MATH_ADD,MechString::from_str("math/add"));
      functions.insert(*MATH_SUBTRACT, Box::new(MathSub{})); dict.insert(*MATH_SUBTRACT,MechString::from_str("math/subtract"));
      functions.insert(*MATH_MULTIPLY, Box::new(MathMul{})); dict.insert(*MATH_MULTIPLY,MechString::from_str("math/multiply"));
      functions.insert(*MATH_DIVIDE, Box::new(MathDiv{})); dict.insert(*MATH_DIVIDE,MechString::from_str("math/divide"));
      functions.insert(*MATH_EXPONENT, Box::new(MathExp{})); dict.insert(*MATH_EXPONENT,MechString::from_str("math/exp"));
      functions.insert(*MATH_NEGATE, Box::new(MathNegate{})); dict.insert(*MATH_NEGATE,MechString::from_str("math/negate"));
      functions.insert(*MATH_ADD__UPDATE, Box::new(MathAddUpdate{})); dict.insert(*MATH_ADD__UPDATE,MechString::from_str("math/add-update"));
      functions.insert(*MATH_SUBTRACT__UPDATE, Box::new(MathSubtractUpdate{})); dict.insert(*MATH_SUBTRACT__UPDATE,MechString::from_str("math/subtract-update"));  
      functions.insert(*MATH_MULTIPLY__UPDATE, Box::new(MathMultiplyUpdate{})); dict.insert(*MATH_MULTIPLY__UPDATE,MechString::from_str("math/multiply-update"));
      functions.insert(*MATH_DIVIDE__UPDATE, Box::new(MathDivideUpdate{})); dict.insert(*MATH_DIVIDE__UPDATE,MechString::from_str("math/divide-update"));

      // Matrix
      functions.insert(*MATRIX_MULTIPLY, Box::new(MatrixMul{}));
      functions.insert(*MATRIX_TRANSPOSE, Box::new(MatrixTranspose{}));

      // Logic
      functions.insert(*LOGIC_NOT, Box::new(LogicNot{}));
      functions.insert(*LOGIC_AND, Box::new(LogicAnd{}));
      functions.insert(*LOGIC_OR, Box::new(LoigicOr{}));
      functions.insert(*LOGIC_XOR, Box::new(LogicXor{}));

      // Compare
      functions.insert(*COMPARE_GREATER__THAN, Box::new(CompareGreater{}));
      functions.insert(*COMPARE_LESS__THAN, Box::new(CompareLess{}));
      functions.insert(*COMPARE_GREATER__THAN__EQUAL, Box::new(CompareGreaterEqual{}));
      functions.insert(*COMPARE_LESS__THAN__EQUAL, Box::new(CompareLessEqual{}));
      functions.insert(*COMPARE_EQUAL, Box::new(CompareEqual{}));
      functions.insert(*COMPARE_NOT__EQUAL, Box::new(CompareNotEqual{}));

      // Table
      functions.insert(*TABLE_APPEND, Box::new(TableAppend{}));
      functions.insert(*TABLE_RANGE, Box::new(TableRange{}));
      functions.insert(*TABLE_SPLIT, Box::new(TableSplit{}));
      functions.insert(*TABLE_FLATTEN, Box::new(TableFlatten{}));
      functions.insert(*TABLE_DEFINE, Box::new(TableDefine{}));
      functions.insert(*TABLE_SET, Box::new(TableSet{}));
      functions.insert(*TABLE_HORIZONTAL__CONCATENATE, Box::new(TableHorizontalConcatenate{}));
      functions.insert(*TABLE_VERTICAL__CONCATENATE, Box::new(TableVerticalConcatenate{}));
      functions.insert(*TABLE_SIZE, Box::new(TableSize{}));
      
      // Stats
      functions.insert(*STATS_SUM, Box::new(StatsSum{}));

      // Set
      functions.insert(*SET_ANY, Box::new(SetAny{}));
      functions.insert(*SET_ALL, Box::new(SetAll{}));
      functions.insert(*SET_CARTESIAN, Box::new(SetCartesian{}));
    }

    Core {
      sections: Vec::new(),
      blocks: HashMap::new(),
      unsatisfied_blocks: HashMap::new(),
      database: Rc::new(RefCell::new(Database::new())),
      functions: Rc::new(RefCell::new(functions)),
      user_functions: Rc::new(RefCell::new(HashMap::new())),
      required_functions: HashSet::new(),
      errors: HashMap::new(),
      full_errors: HashMap::new(),
      schedule: Schedule::new(),
      input: HashSet::new(),
      output: HashSet::new(),
      defined_tables: HashSet::new(),
      dictionary: dictionary,
    }
  }

  pub fn get_name(&self, name_id: u64) -> Option<String> {
    match self.dictionary.borrow().get(&name_id) {
      Some(mech_string) => Some(mech_string.to_string()),
      None => None,
    }
  }

  pub fn load_function(&mut self, name: &str, mut fxn: Box<dyn MechFunctionCompiler>) -> Result<(),MechError> {
    let mut functions_brrw = self.functions.borrow_mut();
    functions_brrw.insert(hash_str(name),fxn);
    Ok(())
  }

  pub fn needed_registers(&self) -> HashSet<(TableId,RegisterIndex,RegisterIndex)> {
    self.input.difference(&self.defined_tables).cloned().collect()
  }

  pub fn process_transaction(&mut self, txn: &Transaction) -> Result<(Vec<BlockRef>,HashSet<(TableId,RegisterIndex,RegisterIndex)>),MechError> {
    let mut changed_registers = HashSet::new();
    let mut block_refs = Vec::new();
    for change in txn {
      match change {
        Change::Set((table_id, adds)) => {
          match self.database.borrow().get_table_by_id(table_id) {
            Some(table) => {
              let table_brrw = table.borrow();
              for (row,col,val) in adds {
                match table_brrw.set(row, col, val.clone()) {
                  Ok(()) => {
                    // TODO This is inserting a {:,:} register instead of the one passed in, and that needs to be fixed.
                    changed_registers.insert((TableId::Global(*table_id),RegisterIndex::All,RegisterIndex::All));
                  },
                  Err(x) => { return Err(MechError{msg: "".to_string(), id: 1000, kind: MechErrorKind::GenericError(format!("{:?}", x))});},
                }
              }
            }
            None => {return Err(MechError{msg: "".to_string(), id: 1001, kind: MechErrorKind::MissingTable(TableId::Global(*table_id))});},
          }
        }
        Change::NewTable{table_id, rows, columns} => {
          let table = Table::new(*table_id,rows.clone(),*columns);
          self.database.borrow_mut().insert_table(table)?;
        }
        Change::ColumnAlias{table_id, column_ix, column_alias} => {
          match self.database.borrow_mut().get_table_by_id(table_id) {
            Some(table) => {
              let mut table_brrw = table.borrow_mut();   
              let rows = table_brrw.rows;
              if *column_ix + 1 > table_brrw.cols {
                table_brrw.resize(rows, column_ix + 1);
              }    
              table_brrw.set_col_alias(*column_ix,*column_alias);     
            }
            x => {return Err(MechError{msg: "".to_string(), id: 1002, kind: MechErrorKind::GenericError(format!("{:?}", x))});},
          }
        }
        Change::ColumnKind{table_id, column_ix, column_kind} => {
          match self.database.borrow_mut().get_table_by_id(table_id) {
            Some(table) => {
              let mut table_brrw = table.borrow_mut();   
              let rows = table_brrw.rows;
              if *column_ix + 1 > table_brrw.cols {
                table_brrw.resize(rows, column_ix + 1);
              }    
              table_brrw.set_col_kind(*column_ix,column_kind.clone());     
            }
            x => {return Err(MechError{msg: "".to_string(), id: 1003, kind: MechErrorKind::GenericError(format!("{:?}", x))});},
          }
        }
      }
    }

    for (changed_table_id,_,_) in &changed_registers {
      let mut cured_block_refs = self.remove_error(*changed_table_id)?;
      block_refs.append(&mut cured_block_refs);
    }
    for register in &changed_registers {
      self.step(register);
    }
    Ok((block_refs,changed_registers))
  }

  pub fn remove_error(&mut self, table_id: TableId) -> Result<Vec<BlockRef>,MechError> {
    let mut block_refs = vec![];
    match &self.errors.remove(&MechErrorKind::MissingTable(table_id)) {
      Some(ref ublocks) => {
        let mut mb = ublocks.clone();
        block_refs.append(&mut mb);
      }
      None => (),
    }
    match self.errors.remove(&MechErrorKind::PendingTable(table_id)) {
      Some(ref ublocks) => {
        let mut mb = ublocks.clone();
        block_refs.append(&mut mb);
      }
      None => (),
    }
    self.load_block_refs(block_refs.clone());
    self.schedule_blocks();
    let mut graph_output = vec![];
    match self.schedule.trigger_to_output.get(&(table_id,RegisterIndex::All,RegisterIndex::All)) {
      Some(output) => {
        for (table_id,_,_) in output {
          graph_output.push(table_id.clone());
        }
      }
      None => (),
    }
    for table_id in graph_output {
      self.remove_error(table_id);
    }
    Ok(block_refs)
  }

  pub fn insert_table(&mut self, table: Table) -> Result<Rc<RefCell<Table>>,MechError> {
    self.database.borrow_mut().insert_table(table)
  }

  pub fn overwrite_tables(&mut self, tables: &Vec<Table>) -> Result<(),MechError> {
    let mut database_brrw = self.database.borrow_mut();
    for table in tables {
      let table2 = database_brrw.get_table_by_id(&table.id).unwrap();
    }
    Ok(())
  }

  pub fn get_table(&self, table_name: &str) -> Result<Rc<RefCell<Table>>,MechError> {
    match self.database.borrow().get_table(table_name) {
      Some(table) => Ok(table.clone()),
      None => {return Err(MechError{msg: "".to_string(), id: 1004, kind: MechErrorKind::MissingTable(TableId::Global(hash_str(table_name)))});},
    }
  }

  pub fn get_table_by_id(&self, table_id: u64) -> Result<Rc<RefCell<Table>>,MechError> {
    match self.database.borrow().get_table_by_id(&table_id) {
      Some(table) => Ok(table.clone()),
      None => {return Err(MechError{msg: "".to_string(), id: 1005, kind: MechErrorKind::MissingTable(TableId::Global(table_id))});},
    }
  }

  pub fn table_names(&self) -> Vec<String> {
    self.database.borrow().tables.iter().filter_map(|(_,t)| {
      t.borrow().name()
    }).collect::<Vec<String>>()
  }

  pub fn recompile_dynamic_tables(&mut self, register: (TableId, RegisterIndex, RegisterIndex)) -> Result<(),MechError> {
    match self.schedule.schedules.get(&register) {
      Some(schedules) => {
        for schedule in schedules {
          schedule.recompile_blocks()?;
        }
      }
      None => (),
    }
    
    Ok(())
  }

  pub fn load_sections(&mut self, sections: Vec<Vec<SectionElement>>) -> Vec<((Vec<BlockId>,Vec<u64>,Vec<MechError>))> {
    let mut result = vec![];
    for elements in sections.iter() {
      let mut block_ids_agg = vec![];
      let mut fxn_ids = vec![];
      let mut errors_agg = vec![];
      for section_element in elements.iter() {
        match section_element {
          SectionElement::Block(block) => {
            let (mut block_ids, mut errors) = self.load_blocks(&vec![block.clone()]);
            block_ids_agg.append(&mut block_ids);
            errors_agg.append(&mut errors);
          }
          SectionElement::UserFunction(fxn) => {
            self.load_user_function(fxn);
          }
        }
      }
      result.push((block_ids_agg,fxn_ids,errors_agg));
    }
    result
  }

  pub fn load_user_function(&mut self, user_function: &UserFunction) -> Result<(),MechError> {

    let mut usr_fxns_brrw = self.user_functions.borrow_mut();

    usr_fxns_brrw.insert(user_function.name,user_function.clone());

    Ok(())
  }

  pub fn load_block_refs(&mut self, mut blocks: Vec<BlockRef>) -> (Vec<BlockId>,Vec<MechError>) {
    let mut block_ids = vec![];
    let mut block_errors = vec![];
    for block in blocks {
      let (mut new_block_ids, mut new_block_errors, mut new_block_output) = self.load_block(block.clone());
      block_ids.append(&mut new_block_ids);
      block_errors.append(&mut new_block_errors);
      for register in new_block_output.iter() {
        self.step(register);
      }
      self.schedule_blocks();
      //self.recompile_dynamic_tables();
    }
    (block_ids,block_errors)
  }

  pub fn load_blocks(&mut self, mut blocks: &Vec<Block>) -> (Vec<BlockId>,Vec<MechError>) {
    let mut block_ids = vec![];
    let mut block_errors = vec![];
    for block in blocks {
      let (mut new_block_ids, mut new_block_errors, mut new_block_output) = self.load_block(Rc::new(RefCell::new(block.clone())));
      block_ids.append(&mut new_block_ids);
      block_errors.append(&mut new_block_errors);
      for register in new_block_output.iter() {
        self.step(register);
      }
      self.schedule_blocks();
      //self.recompile_dynamic_tables();
    }
    (block_ids,block_errors)
  }

  pub fn load_block(&mut self, mut block_ref: BlockRef) -> (Vec<BlockId>,Vec<MechError>,HashSet<(TableId,RegisterIndex,RegisterIndex)>) {
    let block_ref_c = block_ref.clone();
    let mut new_block_ids = vec![];
    let mut new_block_errors = vec![];
    let mut new_block_output = HashSet::new();
    {
      let mut block_brrw = block_ref.borrow_mut();
      let temp_db = block_brrw.global_database.clone();
      block_brrw.global_database = self.database.clone();
      block_brrw.functions = Some(self.functions.clone());
      block_brrw.user_functions = Some(self.user_functions.clone());
      // Merge databases
      {
        let mut temp_db_brrw = temp_db.borrow();
        match self.database.try_borrow_mut() {
          Ok(ref mut database_brrw) => {
            database_brrw.union(&mut temp_db_brrw);
          }
          Err(_) => ()
        }
      }
      // Merge dictionaries
      for (k,v) in block_brrw.strings.borrow().iter() {
        self.dictionary.borrow_mut().insert(*k,v.clone());
      }
      // Merge dictionaries
      for fxn_id in block_brrw.required_functions.iter() {
        self.required_functions.insert(*fxn_id);
      }
      // try to satisfy the block
      match block_brrw.ready() {
        Ok(()) => {
          
          let id = block_brrw.gen_id();

          // Merge input and output
          self.input = self.input.union(&mut block_brrw.input).cloned().collect();
          self.output = self.output.union(&mut block_brrw.output).cloned().collect();
          self.defined_tables = self.defined_tables.union(&mut block_brrw.defined_tables).cloned().collect();
          {
            let mut database_brrw = self.database.borrow_mut();
            database_brrw.dynamic_tables = database_brrw.dynamic_tables.union(&mut block_brrw.dynamic_tables).cloned().collect();
          }
          self.schedule.add_block(block_ref.clone());
          self.blocks.insert(id,block_ref_c.clone());

          // Try to satisfy other blocks
          let mut block_output = block_brrw.output.clone();
          new_block_output = new_block_output.union(&mut block_output).cloned().collect();
          let mut resolved_tables: Vec<MechErrorKind> = block_output.iter().map(|(table_id,_,_)| MechErrorKind::MissingTable(*table_id)).collect();
          let mut resolved_pending_tables: Vec<MechErrorKind> = block_output.iter().map(|(table_id,_,_)| MechErrorKind::PendingTable(*table_id)).collect();
          resolved_tables.append(&mut resolved_pending_tables);
          new_block_ids.push(id);
          let (mut newly_resolved_block_ids, mut new_errors, mut new_output) = self.resolve_errors(&resolved_tables);
          new_block_output = new_block_output.union(&mut new_output).cloned().collect();
          new_block_ids.append(&mut newly_resolved_block_ids);
          new_block_errors.append(&mut new_errors);
        }
        Err(x) => {
          // Merge input and output
          self.input = self.input.union(&mut block_brrw.input).cloned().collect();
          self.output = self.output.union(&mut block_brrw.output).cloned().collect();        
          let (mech_error,_) = block_brrw.unsatisfied_transformation.as_ref().unwrap();
          let blocks_with_errors = self.full_errors.entry(mech_error.clone()).or_insert(Vec::new());
          blocks_with_errors.push(block_ref_c.clone());
          let blocks_with_errors = self.errors.entry(mech_error.kind.clone()).or_insert(Vec::new());
          blocks_with_errors.push(block_ref_c.clone());
          self.unsatisfied_blocks.insert(0,block_ref_c.clone());
          let error = MechError{msg: "".to_string(), id: 1006, kind: MechErrorKind::GenericError(format!("{:?}", x))};
          new_block_errors.push(error);
        },
      };
    }
    self.unsatisfied_blocks.drain_filter(|k,v| { 
      let state = {
        match v.try_borrow() {
          Ok(brrw) => brrw.state.clone(),
          Err(_) => BlockState::Pending,
        }
      };
      state == BlockState::Ready
    });

    (new_block_ids,new_block_errors,new_block_output)
  }
  
  pub fn resolve_errors(&mut self, resolved_errors: &Vec<MechErrorKind>) -> (Vec<u64>,Vec<MechError>,HashSet<(TableId,RegisterIndex,RegisterIndex)>) {
    let mut new_block_ids =  vec![];
    let mut new_block_errors =  vec![];
    let mut new_block_output = HashSet::new();
    for error in resolved_errors.iter() {
      match self.errors.remove(error) {
        Some(mut ublocks) => {
          for ublock in ublocks {
            let (mut nbids,mut nberrs, mut nboutput) = self.load_block(ublock);
            {
              new_block_ids.append(&mut nbids);
              self.unsatisfied_blocks = self.unsatisfied_blocks.drain_filter(|k,v| {
                let state = {
                  match v.try_borrow() {
                    Ok(brrw) => brrw.state.clone(),
                    Err(_) => BlockState::Pending,
                  }
                };
                state != BlockState::Ready
              }).collect();
              // For each of the new blocks, check to see if any of the tables
              // it provides are pending.
              let mut new_block_pending_ids = vec![];
              for id in &new_block_ids {
                let mut output = {
                  let block_ref = self.blocks.get(id).unwrap();
                  let block_ref_brrw = block_ref.borrow();
                  block_ref_brrw.output.clone()
                };
                new_block_output = new_block_output.union(&mut output).cloned().collect();
                for (table_id,_,_) in &output {
                  let (mut resolved, mut errs, mut output) = self.resolve_errors(&vec![MechErrorKind::PendingTable(*table_id)]);
                  new_block_pending_ids.append(&mut resolved);
                  new_block_errors.append(&mut errs);
                  new_block_output = new_block_output.union(&mut output).cloned().collect();
                }
              }
              new_block_ids.append(&mut new_block_pending_ids);
            }
            new_block_errors.append(&mut nberrs)
          }
        }
        None => (),
      }
    }
    (new_block_ids,new_block_errors,new_block_output)
  }

  pub fn get_output_by_block_id(&self, block_id: BlockId) -> Result<HashSet<(TableId,RegisterIndex,RegisterIndex)>,MechError> {
    match self.blocks.get(&block_id) {
      Some(block_ref) => {
        let output = block_ref.borrow().output.clone();
        Ok(output)
      }
      None => Err(MechError{msg: "".to_string(), id: 1008, kind: MechErrorKind::MissingBlock(block_id)}),
    }
  }

  pub fn schedule_blocks(&mut self) -> Result<(),MechError> {
    self.schedule.schedule_blocks()
  }

  pub fn step(&mut self, register: &(TableId,RegisterIndex,RegisterIndex)) -> Result<(),MechError> {
    self.schedule.run_schedule(register)
  }
}

impl fmt::Debug for Core {
  #[inline]
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    let dictionary = self.dictionary.clone();
    let mut box_drawing = BoxPrinter::new();
    box_drawing.add_title("🤖","CORE");
    if self.errors.len() > 0 {
      box_drawing.add_title("🐛","errors");
      for (error,blocks) in self.errors.iter() {
        box_drawing.add_line(format!("  - {:?}", error));
      }
    }
    box_drawing.add_title("📭","input");
    for (table,row,col) in &self.input {
      let table = match dictionary.borrow().get(table.unwrap()) {
        Some(x) => x.to_string(),
        None => format!("{:?}", table),
      };
      box_drawing.add_line(format!("  - ({:?}, {:?}, {:?})", table,row,col));
    }
    box_drawing.add_title("📬","output");
    for (table,row,col) in &self.output {
      let table = match dictionary.borrow().get(table.unwrap()) {
        Some(x) => x.to_string(),
        None => format!("{:?}", table),
      };
      box_drawing.add_line(format!("  - ({:?}, {:?}, {:?})", table,row,col));
    }
    box_drawing.add_title("🧊","blocks");
    box_drawing.add_line(format!("{:#?}", &self.blocks.iter().map(|(k,v)|humanize(&k)).collect::<Vec<String>>()));
    if self.unsatisfied_blocks.len() > 0 {
      box_drawing.add_title("😔","unsatisfied blocks");
      box_drawing.add_line(format!("{:#?}", &self.unsatisfied_blocks));    
    }
    box_drawing.add_title("💻","functions");
    box_drawing.add_line("Compiled Functions".to_string());
    box_drawing.add_line(format!("{:#?}", &self.functions.borrow().functions.iter().map(|(k,v)|
    {
      match dictionary.borrow().get(k) {
        Some(x) => x.to_string(),
        None => humanize(&k),
      }
    }).collect::<Vec<String>>()));
    box_drawing.add_line("User Functions".to_string());
    box_drawing.add_line(format!("{:#?}", &self.user_functions.borrow().iter().map(|(k,v)|
    {
      match dictionary.borrow().get(k) {
        Some(x) => x.to_string(),
        None => humanize(&k),
      }
    }).collect::<Vec<String>>()));
    box_drawing.add_title("🗓️","schedule");
    box_drawing.add_line(format!("{:#?}", &self.schedule));
    box_drawing.add_title("💾","database");
    box_drawing.add_line(format!("{:#?}", &self.database.borrow()));
    write!(f,"{:?}",box_drawing)?;
    Ok(())
  }
}