gt:         	String index = Integer.toString(i++);
context: /*
   * #%L
   * Fork of Apache Jakarta POI.
   * %%
   * Copyright (C) 2008 - 2012 Open Microscopy Environment:
   *   - Board of Regents of the University of Wisconsin-Madison
   *   - Glencoe Software, Inc.
   *   - University of Dundee
   * %%
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   * 
   *      http://www.apache.org/licenses/LICENSE-2.0
   * 
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   * #L%
   */
  /* ====================================================================
     Licensed to the Apache Software Foundation (ASF) under one or more
     contributor license agreements.  See the NOTICE file distributed with
     this work for additional information regarding copyright ownership.
     The ASF licenses this file to You under the Apache License, Version 2.0
     (the "License"); you may not use this file except in compliance with
     the License.  You may obtain a copy of the License at
  
         http://www.apache.org/licenses/LICENSE-2.0
  
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
  ==================================================================== */
  
  
  /*
   * HSSFWorkbook.java
   *
   * Created on September 30, 2001, 3:37 PM
   */
  package loci.poi.hssf.usermodel;
  
  import loci.common.*;
  
  import loci.poi.POIDocument;
  import loci.poi.ddf.EscherBSERecord;
  import loci.poi.ddf.EscherBitmapBlip;
  import loci.poi.ddf.EscherRecord;
  import loci.poi.ddf.EscherBlipRecord;
  import loci.poi.hssf.eventmodel.EventRecordFactory;
  import loci.poi.hssf.model.Sheet;
  import loci.poi.hssf.model.Workbook;
  import loci.poi.hssf.record.*;
  import loci.poi.hssf.record.formula.Area3DPtg;
  import loci.poi.hssf.record.formula.MemFuncPtg;
  import loci.poi.hssf.record.formula.UnionPtg;
  import loci.poi.hssf.util.CellReference;
  import loci.poi.poifs.filesystem.*;
  import loci.poi.util.*;
  
  import java.io.ByteArrayInputStream;
  import java.io.FileNotFoundException;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.OutputStream;
  import java.io.PrintWriter;
  import java.util.ArrayList;
  import java.util.Iterator;
  import java.util.List;
  import java.util.Stack;
  
  /**
   * High level representation of a workbook.  This is the first object most users
   * will construct whether they are reading or writing a workbook.  It is also the
   * top level object for creating new sheets/etc.
   *
   * @see loci.poi.hssf.model.Workbook
   * @see loci.poi.hssf.usermodel.HSSFSheet
   * @author  Andrew C. Oliver (acoliver at apache dot org)
   * @author  Glen Stampoultzis (glens at apache.org)
   * @author  Shawn Laubach (slaubach at apache dot org)
   * @version 2.0-pre
   */
  
  public class HSSFWorkbook extends POIDocument
  {
      private static final int DEBUG = POILogger.DEBUG;
  
      /**
       * used for compile-time performance/memory optimization.  This determines the
       * initial capacity for the sheet collection.  Its currently set to 3.
       * Changing it in this release will decrease performance
       * since you're never allowed to have more or less than three sheets!
       */
  
      public final static int INITIAL_CAPACITY = 3;
  
      /**
       * this is the reference to the low level Workbook object
       */
  
      private Workbook workbook;
  
      /**
       * this holds the HSSFSheet objects attached to this workbook
       */
  
      protected ArrayList sheets;
  
      /**
       * this holds the HSSFName objects attached to this workbook
       */
  
      private ArrayList names;
  
      /**
       * holds whether or not to preserve other nodes in the POIFS.  Used
       * for macros and embedded objects.
       */
      private boolean   preserveNodes;
  
      /**
       * Used to keep track of the data formatter so that all
       * createDataFormatter calls return the same one for a given
       * book.  This ensures that updates from one places is visible
       * someplace else.
       */
      private HSSFDataFormat formatter;
  
  
      /** Extended windows meta file */
      public static final int PICTURE_TYPE_EMF = 2;
      /** Windows Meta File */
      public static final int PICTURE_TYPE_WMF = 3;
      /** Mac PICT format */
      public static final int PICTURE_TYPE_PICT = 4;
      /** JPEG format */
      public static final int PICTURE_TYPE_JPEG = 5;
      /** PNG format */
      public static final int PICTURE_TYPE_PNG = 6;
      /** Device independant bitmap */
      public static final int PICTURE_TYPE_DIB = 7;
  
  
      private static POILogger log = POILogFactory.getLogger(HSSFWorkbook.class);
  
  
  
      /**
       * Creates new HSSFWorkbook from scratch (start here!)
       *
       */
      public HSSFWorkbook()
      {
          this(Workbook.createWorkbook());
      }
  
      protected HSSFWorkbook( Workbook book )
      {
          workbook = book;
          sheets = new ArrayList( INITIAL_CAPACITY );
          names = new ArrayList( INITIAL_CAPACITY );
      }
  
      public HSSFWorkbook(POIFSFileSystem fs) throws IOException {
        this(fs,true);
      }
  
      /**
       * given a POI POIFSFileSystem object, read in its Workbook and populate the high and
       * low level models.  If you're reading in a workbook...start here.
       *
       * @param fs the POI filesystem that contains the Workbook stream.
       * @param preserveNodes whether to preseve other nodes, such as
       *        macros.  This takes more memory, so only say yes if you
       *        need to. If set, will store all of the POIFSFileSystem
       *        in memory
       * @see loci.poi.poifs.filesystem.POIFSFileSystem
       * @exception IOException if the stream cannot be read
       */
  
      public HSSFWorkbook(POIFSFileSystem fs, boolean preserveNodes)
              throws IOException
      {
          this.preserveNodes = preserveNodes;
  
          // Read in the HPSF properties
          this.filesystem = fs;
          readProperties();
          
          // If we're not preserving nodes, don't track the
          //  POIFS any more
          if(! preserveNodes) {
             this.filesystem = null;
          }
  
          sheets = new ArrayList(INITIAL_CAPACITY);
          names  = new ArrayList(INITIAL_CAPACITY);
          
          // Normally, the Workbook will be in a POIFS Stream
          //  called "Workbook". However, some wierd XLS generators
          //  put theirs in one called "WORKBOOK"
          String workbookName = "Workbook";
          try {
          	fs.getRoot().getEntry(workbookName);
          	// Is the default name
          } catch(FileNotFoundException fe) {
          	// Try the upper case form
          	try {
          		workbookName = "WORKBOOK";
          		fs.getRoot().getEntry(workbookName);
          	} catch(FileNotFoundException wfe) {
          		// Doesn't contain it in either form
          		throw new IllegalArgumentException("The supplied POIFSFileSystem contained neither a 'Workbook' entry, nor a 'WORKBOOK' entry. Is it really an excel file?");
          	}
          }
  
          
          // Grab the data from the workbook stream, however
          //  it happens to be spelt.
          InputStream stream = fs.createDocumentInputStream(workbookName);
  
          EventRecordFactory factory = new EventRecordFactory();
  
          List records = RecordFactory.createRecords(stream);
  
          workbook = Workbook.createWorkbook(records);
          setPropertiesFromWorkbook(workbook);
          int recOffset = workbook.getNumRecords();
          int sheetNum = 0;
  
          // convert all LabelRecord records to LabelSSTRecord
          convertLabelRecords(records, recOffset);        
          while (recOffset < records.size())
          {
              Sheet sheet = Sheet.createSheet(records, sheetNum++, recOffset );
  
              recOffset = sheet.getEofLoc()+1;
              if (recOffset == 1)
              {
                  break;
              }
  
              HSSFSheet hsheet = new HSSFSheet(this, sheet);
  
              sheets.add(hsheet);
  
              // workbook.setSheetName(sheets.size() -1, "Sheet"+sheets.size());
          }
  
          for (int i = 0 ; i < workbook.getNumNames() ; ++i){
              HSSFName name = new HSSFName(workbook, workbook.getNameRecord(i));
              names.add(name);
          }
      }
  
       public HSSFWorkbook(RandomAccessInputStream s) throws IOException {
           this(s,true);
       }
  
      /**
       * Companion to HSSFWorkbook(POIFSFileSystem), this constructs the POI filesystem around your
       * inputstream.
       *
       * @param s  the POI filesystem that contains the Workbook stream.
       * @param preserveNodes whether to preseve other nodes, such as
       *        macros.  This takes more memory, so only say yes if you
       *        need to.
       * @see loci.poi.poifs.filesystem.POIFSFileSystem
       * @see #HSSFWorkbook(POIFSFileSystem)
       * @exception IOException if the stream cannot be read
       */
  
      public HSSFWorkbook(RandomAccessInputStream s, boolean preserveNodes)
              throws IOException
      {
          this(new POIFSFileSystem(s, 512), preserveNodes);
      }
  
      /**
       * used internally to set the workbook properties.
       */
  
      private void setPropertiesFromWorkbook(Workbook book)
      {
          this.workbook = book;
  
          // none currently
      }
      
      /**
        * This is basically a kludge to deal with the now obsolete Label records.  If
        * you have to read in a sheet that contains Label records, be aware that the rest
        * of the API doesn't deal with them, the low level structure only provides read-only
        * semi-immutable structures (the sets are there for interface conformance with NO
        * impelmentation).  In short, you need to call this function passing it a reference
        * to the Workbook object.  All labels will be converted to LabelSST records and their
        * contained strings will be written to the Shared String tabel (SSTRecord) within
        * the Workbook.
        *
        * @param wb sheet's matching low level Workbook structure containing the SSTRecord.
        * @see loci.poi.hssf.record.LabelRecord
        * @see loci.poi.hssf.record.LabelSSTRecord
        * @see loci.poi.hssf.record.SSTRecord
        */
   
       private void convertLabelRecords(List records, int offset)
       {
           if (log.check( POILogger.DEBUG ))
               log.log(POILogger.DEBUG, "convertLabelRecords called");
           for (int k = offset; k < records.size(); k++)
           {
               Record rec = ( Record ) records.get(k);
  
               if (rec.getSid() == LabelRecord.sid)
               {
                   LabelRecord oldrec = ( LabelRecord ) rec;
  
                   records.remove(k);
                   LabelSSTRecord newrec   = new LabelSSTRecord();
                   int            stringid =
                       workbook.addSSTString(new UnicodeString(oldrec.getValue()));
  
                   newrec.setRow(oldrec.getRow());
                   newrec.setColumn(oldrec.getColumn());
                   newrec.setXFIndex(oldrec.getXFIndex());
                   newrec.setSSTIndex(stringid);
                         records.add(k, newrec);
               }
           }
           if (log.check( POILogger.DEBUG ))
               log.log(POILogger.DEBUG, "convertLabelRecords exit");
       }
      
  
      /**
       * sets the order of appearance for a given sheet.
       *
       * @param sheetname the name of the sheet to reorder
       * @param pos the position that we want to insert the sheet into (0 based)
       */
  
      public void setSheetOrder(String sheetname, int pos ) {
          sheets.add(pos,sheets.remove(getSheetIndex(sheetname)));
          workbook.setSheetOrder(sheetname, pos);
      }
      
      /**
       * sets the tab whose data is actually seen when the sheet is opened.
       * This may be different from the "selected sheet" since excel seems to
       * allow you to show the data of one sheet when another is seen "selected"
       * in the tabs (at the bottom).
       * @see loci.poi.hssf.usermodel.HSSFSheet#setSelected(boolean)
       * @param index
       */
      public void setSelectedTab(short index) {
          workbook.getWindowOne().setSelectedTab(index);
      }
      
      /**
       * gets the tab whose data is actually seen when the sheet is opened.
       * This may be different from the "selected sheet" since excel seems to
       * allow you to show the data of one sheet when another is seen "selected"
       * in the tabs (at the bottom).
       * @see loci.poi.hssf.usermodel.HSSFSheet#setSelected(boolean)
       */
      public short getSelectedTab() {
          return workbook.getWindowOne().getSelectedTab();
      }
      
      /**
       * sets the first tab that is displayed in the list of tabs
       * in excel.
       * @param index
       */
      public void setDisplayedTab(short index) {
          workbook.getWindowOne().setDisplayedTab(index);
      }
      
      /**
       * sets the first tab that is displayed in the list of tabs
       * in excel.
       */
      public short getDisplayedTab() {
          return workbook.getWindowOne().getDisplayedTab();
      }
  
      /**
       * @deprecated POI will now properly handle unicode strings without
       * forceing an encoding
       */
      public final static byte ENCODING_COMPRESSED_UNICODE = 0;
      /**
       * @deprecated POI will now properly handle unicode strings without
       * forceing an encoding
       */
      public final static byte ENCODING_UTF_16             = 1;
  
  
      /**
       * set the sheet name. 
       * Will throw IllegalArgumentException if the name is greater than 31 chars
       * or contains /\?*[]
       * @param sheet number (0 based)
       */
      public void setSheetName(int sheet, String name)
      {
          if (workbook.doesContainsSheetName( name, sheet ))
              throw new IllegalArgumentException( "The workbook already contains a sheet with this name" );
  
          if (sheet > (sheets.size() - 1))
          {
              throw new RuntimeException("Sheet out of bounds");
          }
          
          workbook.setSheetName( sheet, name);
      }
  
      
      /**
       * set the sheet name forcing the encoding. Forcing the encoding IS A BAD IDEA!!!
       * @deprecated 3-Jan-2006 POI now automatically detects unicode and sets the encoding
       * appropriately. Simply use setSheetName(int sheet, String encoding) 
       * @throws IllegalArgumentException if the name is greater than 31 chars
       * or contains /\?*[]
       * @param sheet number (0 based)
       */    
      public void setSheetName( int sheet, String name, short encoding )
      {
          if (workbook.doesContainsSheetName( name, sheet ))
              throw new IllegalArgumentException( "The workbook already contains a sheet with this name" );
  
          if (sheet > (sheets.size() - 1))
          {
              throw new RuntimeException("Sheet out of bounds");
          }
  
          switch ( encoding ) {
          case ENCODING_COMPRESSED_UNICODE:
          case ENCODING_UTF_16:
              break;
  
          default:
              // TODO java.io.UnsupportedEncodingException
              throw new RuntimeException( "Unsupported encoding" );
          }
  
          workbook.setSheetName( sheet, name, encoding );
      }
  
      /**
       * get the sheet name
       * @param sheet Number
       * @return Sheet name
       */
  
      public String getSheetName(int sheet)
      {
          if (sheet > (sheets.size() - 1))
          {
              throw new RuntimeException("Sheet out of bounds");
          }
          return workbook.getSheetName(sheet);
      }
  
      /*
       * get the sheet's index
       * @param name  sheet name
       * @return sheet index or -1 if it was not found.
       */
  
      /** Returns the index of the sheet by his name
       * @param name the sheet name
       * @return index of the sheet (0 based)
       */
      public int getSheetIndex(String name)
      {
          int retval = workbook.getSheetIndex(name);
  
          return retval;
      }
  
      /** Returns the index of the given sheet
       * @param sheet the sheet to look up
       * @return index of the sheet (0 based)
       */
      public int getSheetIndex(HSSFSheet sheet)
      {
      	for(int i=0; i<sheets.size(); i++) {
      		if(sheets.get(i) == sheet) {
      			return i;
      		}
      	}
      	return -1;
      }
  
      /**
       * create an HSSFSheet for this HSSFWorkbook, adds it to the sheets and returns
       * the high level representation.  Use this to create new sheets.
       *
       * @return HSSFSheet representing the new sheet.
       */
  
      public HSSFSheet createSheet()
      {
  
  //        if (getNumberOfSheets() == 3)
  //            throw new RuntimeException("You cannot have more than three sheets in HSSF 1.0");
          HSSFSheet sheet = new HSSFSheet(this);
  
          sheets.add(sheet);
          workbook.setSheetName(sheets.size() - 1,
                  "Sheet" + (sheets.size() - 1));
          WindowTwoRecord windowTwo = (WindowTwoRecord) sheet.getSheet().findFirstRecordBySid(WindowTwoRecord.sid);
          windowTwo.setSelected(sheets.size() == 1);
          windowTwo.setPaged(sheets.size() == 1);
          return sheet;
      }
  
      /**
       * create an HSSFSheet from an existing sheet in the HSSFWorkbook.
       *
       * @return HSSFSheet representing the cloned sheet.
       */
  
      public HSSFSheet cloneSheet(int sheetNum) {
        HSSFSheet srcSheet = (HSSFSheet)sheets.get(sheetNum);
        String srcName = workbook.getSheetName(sheetNum);
        if (srcSheet != null) {
          HSSFSheet clonedSheet = srcSheet.cloneSheet(this);
          WindowTwoRecord windowTwo = (WindowTwoRecord) clonedSheet.getSheet().findFirstRecordBySid(WindowTwoRecord.sid);
          windowTwo.setSelected(sheets.size() == 1);
          windowTwo.setPaged(sheets.size() == 1);
  
          sheets.add(clonedSheet);
          int i=1;
          while (true) {
          	//Try and find the next sheet name that is unique
          	String name = srcName;
  