/**
  * Write a formula to the specified row and column (zero indexed).
  * The textual representation of the formula is passed to the parser in
  * Parser.php which returns a packed binary string.
  *
  * Returns  0 : normal termination
  *         -1 : formula errors (bad formula)
  *         -2 : row or column out of range
  *
  * @access public
  * @param integer $row     Zero indexed row
  * @param integer $col     Zero indexed column
  * @param string  $formula The formula text string
  * @param mixed   $format  The optional XF format
  * @return integer
  */
 public function writeFormula($row, $col, $formula, $format = null)
 {
     $record = 0x6;
     // Record identifier
     // Excel normally stores the last calculated value of the formula in $num.
     // Clearly we are not in a position to calculate this a priori. Instead
     // we set $num to zero and set the option flags in $grbit to ensure
     // automatic calculation of the formula when the file is opened.
     //
     $xf = $this->_XF($format);
     // The cell format
     $num = 0x0;
     // Current value of formula
     $grbit = 0x3;
     // Option flags
     $unknown = 0x0;
     // Must be zero
     // Check that row and col are valid and store max and min values
     if ($this->_checkRowCol($row, $col) == false) {
         return -2;
     }
     // Strip the '=' or '@' sign at the beginning of the formula string
     if (preg_match("/^=/", $formula)) {
         $formula = preg_replace("/(^=)/", "", $formula);
     } elseif (preg_match("/^@/", $formula)) {
         $formula = preg_replace("/(^@)/", "", $formula);
     } else {
         // Error handling
         $this->writeString($row, $col, 'Unrecognised character for formula');
         return -1;
     }
     // Parse the formula using the parser in Parser.php
     $error = $this->_parser->parse($formula);
     if ($this->isError($error)) {
         $this->writeString($row, $col, $error->getMessage());
         return -1;
     }
     $formula = $this->_parser->toReversePolish();
     if ($this->isError($formula)) {
         $this->writeString($row, $col, $formula->getMessage());
         return -1;
     }
     $formlen = strlen($formula);
     // Length of the binary string
     $length = 0x16 + $formlen;
     // Length of the record data
     $header = pack("vv", $record, $length);
     $data = pack("vvvdvVv", $row, $col, $xf, $num, $grbit, $unknown, $formlen);
     $this->_append($header . $data . $formula);
     return 0;
 }