module RPG
  class TilesetVX
    attr_accessor :name
    attr_accessor :bitmapNames
    attr_accessor :passages
    def initialize(name,bitmapNames,passages)
      @name=name
      @bitmapNames=bitmapNames
      @passages=passages
    end
  end
end

def loadTileset(name)
  begin
    return Cache.load_bitmap("Graphics/Tilesets/",name)
  rescue RGSSError, Errno::ENOENT
    return Cache.system(name)
  end
end

class Spriteset_Map
  def create_tilemap
    if !$data_map_tilesets
     begin
       $data_map_tilesets=load_data("Data/MapTilesets.rvdata")
     rescue
       $data_map_tilesets=nil
     end
    end
    if !$data_tilesets
     begin
       $data_tilesets=load_data("Data/Tilesets.rvdata")
     rescue
       $data_tilesets=nil
     end
    end
    @tilemap = Tilemap.new(@viewport1)
    tileset=nil
    if $data_map_tilesets && $data_tilesets
      mapset=$data_map_tilesets[$game_map.map_id]
      tileset=$data_tilesets[mapset] if mapset && mapset>0
    end
    if tileset
      @tilemap.bitmaps[0] = loadTileset(tileset.bitmapNames[0])
      @tilemap.bitmaps[1] = loadTileset(tileset.bitmapNames[1])
      @tilemap.bitmaps[2] = loadTileset(tileset.bitmapNames[2])
      @tilemap.bitmaps[3] = loadTileset(tileset.bitmapNames[3])
      @tilemap.bitmaps[4] = loadTileset(tileset.bitmapNames[4])
      @tilemap.bitmaps[5] = loadTileset(tileset.bitmapNames[5])
      @tilemap.bitmaps[6] = loadTileset(tileset.bitmapNames[6])
      @tilemap.bitmaps[7] = loadTileset(tileset.bitmapNames[7])
      @tilemap.bitmaps[8] = loadTileset(tileset.bitmapNames[8])     
      @tilemap.passages = tileset.passages
    else
      @tilemap.bitmaps[0] = Cache.system("TileA1")
      @tilemap.bitmaps[1] = Cache.system("TileA2")
      @tilemap.bitmaps[2] = Cache.system("TileA3")
      @tilemap.bitmaps[3] = Cache.system("TileA4")
      @tilemap.bitmaps[4] = Cache.system("TileA5")
      @tilemap.bitmaps[5] = Cache.system("TileB")
      @tilemap.bitmaps[6] = Cache.system("TileC")
      @tilemap.bitmaps[7] = Cache.system("TileD")
      @tilemap.bitmaps[8] = Cache.system("TileE")
      @tilemap.passages = $game_map.passages
    end
    @tilemap.map_data = $game_map.data
  end
end
