var undoList = new Chunk();
var undoing = 0;
var undoStart = 0;
var undoCount = 0;

function Chunk() {
  this.location = 0;
  this.value = "";
  this.prev = 0;
  this.next = 0;
  this.revert = function() {
    if (this.location == 0) {
      alert("Nothing more to undo");
      return;
    }
    undoCount--;
    undoing = 1;
    getCellContents(this.location);
    putCellContents(this.location, this.value);
    undoing = 0;
    undoList = this.prev;
    undoList.next = 0;
  }
}

// set undoing=1 so addChunk ignore any addChunk requests
function turnOffUndo() {
  undoing = 1;
}

function turnOnUndo() {
  undoing = 0;
}

function addChunk(cell, str) {
  if (undoing) return;
  var c = new Chunk();
  c.location = cell;
  c.value = str;
  c.prev = undoList;
  undoList.next = c;
  undoList = c;
  undoCount++;
  if (undoCount > 40) {
    undoCount--;
    undoStart = undoStart.next;
    undoStart.location = 0;
    undoStart.prev = 0;
  }
}

function resetUndoList() {
  undoList = new Chunk();
  undoStart = undoList;
  undoCount = 0;
}

function undo() {
  undoList.revert();
}

