#include "SudokuTask.h"

#include <iostream>
using namespace std;

task* SudokuTask::execute() {
  int x=-1,y=-1;
  *subtasks=0;

  if (puzzle->nextfree(x,y)==true) {
    unsigned long childtasks[LENGTH]={0};
    int count=0;
    task_list list;

    for(int i=1;i<=LENGTH;i++) {
      if (puzzle->check(x,y,i)==true) {
        Sudoku* childpuzzle=new Sudoku(*puzzle);
        childpuzzle->at(x,y)=i;
        list.push_back(*new(allocate_child())SudokuTask(childpuzzle,childtasks+count));
        count++;
      }
    }
    if (count>0) {
      set_ref_count(count+1);
      spawn_and_wait_for_all(list);
      for(int i=0;i<LENGTH;i++)
        *subtasks+=childtasks[i];
      *subtasks+=count;
    }
  } else {
    cout << "Solution found." << endl;
    puzzle->print();
  }

  return NULL;
}
