function klear() {
  for (var i=0;i<1600;i++) g_squares[i]=0;
}
function draw() {
  for (var i=0;i<1600;i++) {
    var el=document.getElementById(i);
    var colour='white';
    if (g_squares[i]==1) colour='red';
    el.style.backgroundColor=colour;
  }
}
function seed() {
  klear();
  for (var i=0;i<1600;i++) {
    if (random(2)==1) g_squares[i]=1;
  }
}
function neighbours(r,c) {
  var n=0;
  for (var row=r-1; row<r+2; row++) {
    for (var col=c-1; col<c+2; col++) {
      var id=rc2id(row,col);
      n+=g_squares[id];
    }
  }
  id=rc2id(r,c);
  n-=g_squares[id];
  return n;
}
function rc2id(r,c) {
  return r*40+c;
}
function gen() {
  var temp=[];
  for (var id=0;id<1600;id++) temp[id]=0;
  for (var row=1;row<39;row++) {
    for (var col=1;col<39;col++) {
      var n=neighbours(row,col);
      var id=rc2id(row,col);
      var v=g_squares[id];
      if (v==0) { // dead
        if (n==3) v=1;
      } else { // alive
        if (n<2) v=0;
        if (n>3) v=0;
      }
      temp[id]=v;
    }
  }
  for (var id=0;id<1600;id++) {
    g_squares[id]=temp[id];
  }
}
function one_step() {
  gen();
  draw();
}
function run() {
  g_running=true;
  cont();
}
function cont() {
  if (g_running) {
    one_step();
    setTimeout(cont,150);
  }
}
function stop() {
  g_running=false;
}
function glider() {
  var arr=[[1,2],[2,3],[3,1],[3,2],[3,3]];
  set(arr);
}
function set(arr) {
  for (var i=0;i<arr.length;i++) {
    var rc=arr[i];
    var row=rc[0];
    var col=rc[1];
    var id=rc2id(row,col);
    g_squares[id]=1;
    var el=document.getElementById(id);
    el.style.backgroundColor='red';
  }
}
function glider_gun() {
  var arr=[[1,26],[2,24],[2,26],[3,14],[3,15],[3,22],[3,23],[3,36],[3,37],[4,13],[4,17],[4,22],[4,23],[4,36],[4,37],[5,2],[5,3],[5,12],[5,18],[5,22],[5,23],[6,2],[6,3],[6,12],[6,16],[6,18],[6,19],[6,24],[6,26],[7,12],[7,18],[7,26],[8,13],[8,17],[9,14],[9,15]];
    set(arr);
}



