require 'sketchup' # First we pull in the standard API hooks.
require 'ShaDe//lib//utils.rb'
require 'ShaDe//lib//geometry.rb'
require 'ShaDe//lib//data-structures.rb'
require 'ShaDe//lib//main-structures.rb'
require 'ShaDe//lib//constraints.rb'
require 'ShaDe//lib//goals.rb'
require 'ShaDe//lib//interfaces//custom.rb'
require 'Shade//lib//montaner.rb'

#Author:: Manuela Ruiz  (mailto:mruiz@lcc.uma.es)
#This class represents the observer for a rule shape group. There is one observer of this kind for every present rule shape.
class RuleShapeObserver < Sketchup::EntitiesObserver
	
	#Initializing
	def initialize(shape)
		@shape = shape
	end
	
	#Method that triggers when something is modified inside a rule shape group, in order to update the internal representation of the affected rule shape
	def onElementModified(entities, entity)

	    #Shade.modified = true
	  
  		if !Shade.project.modifying
  			if !Shade.project.erasing
  				Shade.project.modifying = true
  				execution = Shade.project.execution
  				layer_name = Sketchup.active_model.active_layer.name
  				@shape.refresh_from_entities(entities, @shape.transformation(layer_name), layer_name)
  				execution.grammar.saved = false
  				Shade.project.modifying = false
  			end
  		end

	end
	
	

	#Method that triggers when a rule shape group is erased, in order to update the internal representation of the affected rule shape
	def onEraseEntities(entities)

    #Shade.modified = true
    
		if !Shade.project.modifying
			Shade.project.modifying = true
			layer_name = Sketchup.active_model.active_layer.name
			@shape.p[layer_name] = LinearLinkedList.new
			@shape.s[layer_name] = LinearLinkedList.new
			execution = Shade.project.execution
			execution.grammar.saved = false
			Shade.project.modifying = false
		end
	end

	#Method that triggers when some element is added into a rule shape group, in order to update the internal representation of the affected rule shape
	def onElementAdded(entities, entity)

	  
    #Shade.modified = true
      
		if !Shade.project.modifying
			
			Shade.project.modifying = true
			execution = Shade.project.execution
			layer_name = Sketchup.active_model.active_layer.name
			@shape.refresh_from_entities(entities, @shape.transformation(layer_name), layer_name)
			execution.grammar.saved = false
			Shade.project.modifying = false
		end
	end
	
	#Method that triggers when some element is removed from a rule shape group, in order to update the internal representation of the affected rule shape
	def onElementRemoved(entities, entity_id)

    #Shade.modified = true
    
		if !Shade.project.modifying
			Shade.project.modifying = true
			execution = Shade.project.execution
			layer_name = Sketchup.active_model.active_layer.name
			@shape.refresh_from_entities(entities, @shape.transformation(layer_name), layer_name)
			execution.grammar.saved = false
			Shade.project.modifying = false
		end
	  
    
	  
	end
end

#Author:: Manuela Ruiz  (mailto:mruiz@lcc.uma.es)
#This class represents the observer for all the rule shape groups. There is only one observer of this kind.
class RuleGroupsObserver < Sketchup::EntitiesObserver
	
	attr_accessor :observed_id_list
	
	#Initializing the observer
	def initialize()
		#List of entity ids that cannot be modified
		#These entities are the main groups of the rule shapes
		@observed_id_list = Array.new
		@undoing = false
		super
	end
	
	#Method that triggers when some rule shape group is modified (transformed) as a whole, in order to update the internal representation of the affected rule shape
	def onElementModified(entities, entity)
	 
		  
    #Shade.modified = true
	  
		if @observed_id_list.include? entity.entityID
			
			if !Shade.project.modifying
				Shade.project.modifying = true
				execution = Shade.project.execution
				shape = execution.grammar.search_shape_by_id(entity.entityID)

				if shape
					#refresh the transformation										
					layout_t = shape.layout_transformation
					layout_t_i = layout_t.inverse
					shape_t = layout_t_i * entity.transformation
					
					layer_name = Sketchup.active_model.active_layer.name
					shape.shape_transformation[layer_name] = shape_t
					
					shape.refresh_from_entities(entity.entities, Geom::Transformation.new, layer_name)
					
					execution.grammar.saved = false
				end
				Shade.project.modifying = false
			end
		end
		
	end
	
    def onElementRemoved(entities, entity_id)
      if (!Shade.project.modifying)
        Shade.modified = true
      end
    end

end

# This is an example of an observer that watches the selection for
 # changes.
 class RuleSelectionObserver < Sketchup::SelectionObserver
    def onSelectionBulkChange(selection)
      
      
#      while Shade.modified>0
#        Sketchup.undo
#        Shade.modified -= 1 
#      end
      
      
#      if Shade.modified
#        Shade.project.execution.grammar.rules.each{|rule|
#          rule.erase
#        }
#        #salvar current shape en un fichero con cada aplicacion de la regla 
#      end
      
      
      
     UI.messagebox("No modifique ni altere las figuras cargadas. Se volvera a cargar las originales si hace algun cambio")
#     entities = Sketchup.active_model.entities
#     
#      puts"selected"
#      puts"#{@@elements_added}"
#     
#     
#     @@elements_added.each{|el|
#      
#        entities.erase_entities el
#      
#     }
#         
#      @@elements_added = Array.new
     
     
      
#      @group.each_key {|layer_name|
#        @group[layer_name].locked = false
#      }
   
      rules = Shade.project.execution.grammar.rules
      rules.each{|rule| 
          rule.alpha.group.each_key{|layer_name|
            if !rule.alpha.group[layer_name].deleted?
              rule.alpha.group[layer_name].locked = true
              rule.alpha.group[layer_name].hidden = false
            end
          }
          rule.beta.group.each_key{|layer_name|
            if !rule.beta.group[layer_name].deleted?
              rule.beta.group[layer_name].locked = true
              rule.beta.group[layer_name].hidden = false
            end
          }

      }
      current_shape = Shade.project.execution.current_shape
      Shade.project.execution.current_shape.group.each_key{|layer_name|
        current_shape.group[layer_name].hidden = false
      }
      Sketchup.active_model.close_active
     
#      model = Sketchup.active_model
#      status = model.close_active
#      Shade.project.refresh
        
#      execution.grammar.rules.group.each{|layer_name| 
#        execution.grammar.rules.group[layer_name].locked = true
#      }
      
#     @@elements_deleted.each{|el|
#      el.each{|et|
#       Sketchup.active_model.entities.add_group et
#      }
#      
#     }
     
     
     
#     if Shade.modified
#       Sketchup.undo
#     end
     
     
   end
   
   
   def onSelectionCleared(selection)
     rules = Shade.project.execution.grammar.rules
        rules.each{|rule| 
         rule.alpha.group.each_key{|layer_name|
           if !rule.alpha.group[layer_name].deleted?
             rule.alpha.group[layer_name].locked = true
           end
         }
         rule.beta.group.each_key{|layer_name|
           if !rule.beta.group[layer_name].deleted?
             rule.beta.group[layer_name].locked = true
           end
           }
         }
           Sketchup.active_model.close_active
   end
   
 end


#Author:: Manuela Ruiz  (mailto:mruiz@lcc.uma.es)
# Observer attached to  Sketchup. Triggers when SU is closed
class CloseObserver < Sketchup::AppObserver	
	#Asks to save the project and removes the observers
	def onQuit
		ShadeUtils.ask_to_save_project()
	end
	
end

#Author:: Manuela Ruiz  (mailto:mruiz@lcc.uma.es)
#Observer attached to Sketchup.active_model, triggers when the user makes an UNDO
class UndoObserver < Sketchup::ModelObserver
	
	#Reexecutes the grammar and shows a message, saying that it is not allowed to undo
	def onTransactionUndo(model)
		Sketchup.active_model.start_operation("Undo Done")
		#Shade.project.need_refresh = true
		UI.messagebox("We are sorry, you cannot use the undo command.")
		Sketchup.active_model.commit_operation
	end
end
#Author:: Manuela Ruiz  (mailto:mruiz@lcc.uma.es)
#Tool for painting a label
class AddLabelTool

	#shape:: the shape to which the label is going to be added
	#value:: the value of the label
	#
	#Initializing the tool
	def initialize(shape, value)
		@id_cursor = nil
		@shape = shape
		@value = value
	end
	
	#Activates the cursor
	def activate
		file_name = Sketchup.find_support_file "add_label.png", "Plugins/ShaDe/#{Constants::ABS_ICONS_DIR}"
		@id_cursor = UI.create_cursor file_name, 18, 18
	end
	
	#Method that triggers when the cursor is chosen
	def onSetCursor
		UI.set_cursor  @id_cursor
	end
	
	#Method that triggers when the left button of the mouse is pressed
	def onLButtonDown(flags, x, y, view)

		inputpoint = view.inputpoint x,y
		point = inputpoint.position
		
		#Obtain point relative to shape
		t = @shape.layout_transformation.inverse
		pt_label = t * point
		layer_name = Sketchup.active_model.active_layer.name
		@shape.add_label(pt_label, @value, layer_name)
		
		@shape.changed = true
		
		Shade.project.refresh
		Shade.project.execution.reset
	end
end

#Saves the project, the current shape and the execution history
def save_temp_files()
	project = Shade.project
	
	#STEP 1: Save project
	project_path = "#{File.dirname(__FILE__)}/#{Constants::TEMP_DIR}/project.txt"
	project_path.gsub!("/", "\\")
	project.save(project_path, true)

	#STEP 2: Save current shape 
	current_shape_path = "#{File.dirname(__FILE__)}/#{Constants::TEMP_DIR}/current_shape.txt"
	current_shape_path.gsub!("/", "\\")
	project.execution.current_shape.save(current_shape_path)

	#STEP 2: Save execution history
	history_directory = "#{File.dirname(__FILE__)}/#{Constants::TEMP_DIR}"
	history_directory.gsub!("/", "\\")
	project.execution.save_execution_history(history_directory)
end

#Loads the temp files
def load_temp_files()
	execution = Shade.project.execution

	#STEP 1: Load execution history
	history_directory = "#{File.dirname(__FILE__)}/#{Constants::TEMP_DIR}"
	history_directory.gsub!("/", "\\")
	execution.load_execution_history(history_directory)
	
	#STEP 1: Load current shape
	current_shape_path = "#{File.dirname(__FILE__)}/#{Constants::TEMP_DIR}/current_shape.txt"
	current_shape_path.gsub!("/", "\\")
	execution.current_shape.load(current_shape_path)
	execution.current_shape.refresh
	execution.current_shape.create_pi
end

#Deletes all the files inside temp folder
def delete_temp_files()
	dir = Dir.new("#{File.dirname(__FILE__)}/#{Constants::TEMP_DIR}")
	dir.each { |file_name|
		if file_name == '.' or file_name == '..' then next
		else File.delete("#{File.dirname(__FILE__)}/#{Constants::TEMP_DIR}/#{file_name}")
		end
	}
end


#Method that creates the toolbar for performing execution tasks 
def create_general_toolbar()
 
	toolbar = UI.toolbar "Práctica Proyectos Arquitectónicos 6"
	

	info_cmd = UI::Command.new("info"){

		html_path = Sketchup.find_support_file "info.html" ,Constants::HTML_DIR
		name_dialog = start_tutorial_dialog("info.html")
		name_dialog.set_file(html_path)
		name_dialog.show()
		
	}
	info_cmd.tooltip = "Información de ayuda"
	info_cmd.small_icon = File.join(Constants::ICONS_DIR, "info.PNG")
	info_cmd.large_icon = File.join(Constants::ICONS_DIR, "info.PNG")
	toolbar.add_item info_cmd
	
	tutorial_simple_cmd = UI::Command.new("tutorial_simple"){
		html_path = Sketchup.find_support_file "Gramatica.html" ,Constants::HTML_DIR
		name_dialog = create_gramatica_dialog("Gramatica.html")
		name_dialog.set_file(html_path)
		name_dialog.show()
	}
	tutorial_simple_cmd.tooltip = "Tutorial para las gramáticas de los cuadrados y de la vivienda simple"
	tutorial_simple_cmd.small_icon = File.join(Constants::ICONS_DIR, "tutorial_simple.PNG")
	tutorial_simple_cmd.large_icon = File.join(Constants::ICONS_DIR, "tutorial_simple.PNG")
	toolbar.add_item tutorial_simple_cmd

	tutorial_montaner_cmd = UI::Command.new("tutorial_montaner"){
		html_path = Sketchup.find_support_file "Tutorial.html" ,Constants::HTML_DIR
		name_dialog = create_tutorial_dialog("Tutorial.html")
		name_dialog.set_file(html_path)
		name_dialog.show()
	}
	tutorial_montaner_cmd.tooltip = "Tutorial para generar viviendas segun normativa de Montaner"
	tutorial_montaner_cmd.small_icon = File.join(Constants::ICONS_DIR, "tutorial_montaner.PNG")
	tutorial_montaner_cmd.large_icon = File.join(Constants::ICONS_DIR, "tutorial_montaner.PNG")
	toolbar.add_item tutorial_montaner_cmd
	
	toolbar.add_separator
	
	#Squares grammar
	squares_grammar_cmd = UI::Command.new("squares_grammar"){
	
		if Shade.contour_face
			Shade.contour_face.erase!  
			Shade.montaner_shape = nil
			Shade.contour_face = nil
			Shade.montaner_status = nil
			Shade.montaner_actions = nil
			Shade.montaner_history =Hash.new(nil)
		end

		project = Shade.project
		execution = Shade.project.execution
		Sketchup.active_model.close_active

		directory = "#{File.dirname(__FILE__)}/#{Constants::MONTANER_DIR}/"
		directory.gsub!("/", "\\")

		square_grammar_path = "#{directory}square.gr2"

		execution.grammar.load(square_grammar_path)

		execution.reset
		Shade.project.execution.delete_constraint(Constants::NO_SCALES_CONSTRAINT_NAME)
		Shade.project.execution.add_constraint(DistinctShapeConstraint.new)
		Shade.project.refresh(true)

		Shade.grammar_loaded = "SQUARE"
		Shade.modified = false

		
	}
	squares_grammar_cmd.tooltip = "Gramática de los cuadrados"
	squares_grammar_cmd.small_icon = File.join(Constants::ICONS_DIR, "squares_grammar.PNG")
	squares_grammar_cmd.large_icon = File.join(Constants::ICONS_DIR, "squares_grammar.PNG")
	toolbar.add_item squares_grammar_cmd


	simple_house_grammar_cmd = UI::Command.new("simple_house_grammar"){
		if Shade.contour_face
			Shade.contour_face.erase!  
			Shade.montaner_shape = nil
			Shade.contour_face = nil
			Shade.montaner_status = nil
			Shade.montaner_actions = nil
			Shade.montaner_history =Hash.new(nil)
		end
		ShadeUtils.load_acadia_grammar()
	}
	simple_house_grammar_cmd.tooltip = "Gramática para generar una vivienda simple"
	simple_house_grammar_cmd.small_icon = File.join(Constants::ICONS_DIR, "simple_house_grammar.PNG")
	simple_house_grammar_cmd.large_icon = File.join(Constants::ICONS_DIR, "simple_house_grammar.PNG")
	toolbar.add_item simple_house_grammar_cmd
	
	# Execute command
	exe_cmd = UI::Command.new("apply_rule"){
		if !Shade.contour_face
			project = Shade.project
			execution = Shade.project.execution
			Sketchup.active_model.close_active

			if Shade.modified
			  ShadeUtils.load_grammar(Shade.grammar_loaded)
			end
			
			if execution.grammar.rules.size > 1
			
				prompts = ["Chosen rule id"]
				default = [1]
				rule_list = ShadeUtils.create_rule_list()
				list = [rule_list]
				input = UI.inputbox prompts, default, list, "Apply Rule"
				if input
					chosen_rule_idx = input[0]
					chosen_rule_id = execution.grammar.rules[chosen_rule_idx.to_i - 1].rule_id
					
					#STEP 1: Save temp files
					save_temp_files()
					
					#STEP 2: Call external command with argument: chosen_rule_id
					command_directory = "#{File.dirname(__FILE__)}/#{Constants::COMMANDS_DIR}/execute-command.rb"
					command_directory.gsub!("/", "\\")
					output = system("ruby \"#{command_directory}\" #{chosen_rule_id}")
					
					#STEP 3: Catch return from external command
					if !($? == 0)
						#UI.messagebox("The loaded constraints/goals use some functions of SketchUp API. The execution will be performed inside the SketchUp environment, and it may take more time.")
						#puts output
						success = execution.apply_rule(chosen_rule_id)
						if !success
							UI.messagebox("The rule cannot be applied")
						end
					else
						log_directory = "#{File.dirname(__FILE__)}/#{Constants::TEMP_DIR}/result.log"
						log_directory.gsub!("/", "\\")
						File.open(log_directory, 'r') do |f|
							line = f.gets.strip
							if (line == "true")
								load_temp_files()
							elsif (line == "false")
								UI.messagebox("The rule cannot be applied")
							end
						end	
					end
					
					#STEP 4: delete files of temporal directory
					delete_temp_files()
				end
			else					
					#STEP 1: Save temp files
					save_temp_files()
					
					#STEP 2: Call external command with argument: chosen_rule_id
					command_directory = "#{File.dirname(__FILE__)}/#{Constants::COMMANDS_DIR}/execute-command.rb"
					command_directory.gsub!("/", "\\")
					output = system("ruby \"#{command_directory}\" 1")
					
					#STEP 3: Catch return from external command
					if !($? == 0)
						#UI.messagebox("The loaded constraints/goals use some functions of SketchUp API. The execution will be performed inside the SketchUp environment, and it may take more time.")
						#puts output
						success = execution.apply_rule(chosen_rule_id)
						if !success
							UI.messagebox("The rule cannot be applied")
						end
					else
						log_directory = "#{File.dirname(__FILE__)}/#{Constants::TEMP_DIR}/result.log"
						log_directory.gsub!("/", "\\")
						File.open(log_directory, 'r') do |f|
							line = f.gets.strip
							if (line == "true")
								load_temp_files()
							elsif (line == "false")
								UI.messagebox("The rule cannot be applied")
							end
						end	
					end
					
					#STEP 4: delete files of temporal directory
					delete_temp_files()
			end
		else
			UI.messagebox("Mientras estés creando un plano no puedes ejecutar reglas")
		end
	}
	exe_cmd.tooltip = "Aplicar una regla"
	exe_cmd.small_icon = File.join(Constants::ICONS_DIR, "execute.PNG")
	exe_cmd.large_icon = File.join(Constants::ICONS_DIR, "execute.PNG")
	toolbar.add_item exe_cmd
	

	undo_step_cmd = UI::Command.new("undo_step"){
		if !Shade.contour_face
			project = Shade.project
			execution = Shade.project.execution
			Sketchup.active_model.close_active
			
			execution.undo
		else
			UI.messagebox("Mientras estés creando un plano no puedes ejecutar reglas")
		end
	}
	undo_step_cmd.tooltip = "Deshacer la aplicación de la última regla"
	undo_step_cmd.small_icon = File.join(Constants::ICONS_DIR, "undo.PNG")
	undo_step_cmd.large_icon = File.join(Constants::ICONS_DIR, "undo.PNG")
	toolbar.add_item undo_step_cmd
	
	# Reset command
	reset_cmd = UI::Command.new("reset"){
		if !Shade.contour_face
			project = Shade.project
			execution = Shade.project.execution
			Sketchup.active_model.close_active
			
			execution.reset
		else
			UI.messagebox("Mientras estés creando un plano no puedes ejecutar reglas")
		end
	}
	reset_cmd.tooltip = "Resetear diseño al axioma"
	reset_cmd.small_icon = File.join(Constants::ICONS_DIR, "reset.PNG")
	reset_cmd.large_icon = File.join(Constants::ICONS_DIR, "reset.PNG")
	toolbar.add_item reset_cmd
	
	toolbar.add_separator
	
		
	
	# Montaner command
   
    montaner_cmd = UI::Command.new("montaner"){
    
    
    prompts = ["NÂº de planos: "]
    default = [1]
    list = [""]
    input = UI.inputbox prompts, default, list, "Generador Montaner"
      
    if input
	    
	    if Shade.contour_face
			Shade.contour_face.erase!  
			Shade.montaner_shape = nil
			Shade.contour_face = nil
			Shade.montaner_status = nil
			Shade.montaner_actions = nil
			Shade.montaner_history =Hash.new(nil)
		end
      Shade.project.execution.delete_constraint(Constants::OVERLAP_CONSTRAINT_NAME)
      Shade.project.execution.delete_constraint(Constants::DISTINCT_SHAPE_CONSTRAINT_NAME)
      Shade.project.execution.delete_constraint(Constants::NO_SCALES_CONSTRAINT_NAME)
      
      

     
      #Delete files of flats directory
      dir = Dir.new("#{File.dirname(__FILE__)}/#{Constants::MONTANER_SAVE_DIR}/")
      dir.each { |file_name|
        if file_name == '.' or file_name == '..' then next
        else File.delete("#{File.dirname(__FILE__)}/#{Constants::MONTANER_SAVE_DIR}/#{file_name}")
        end
      }
      
      
      flats = input[0]
      Sketchup.active_model.close_active
      
      save_path = "#{File.dirname(__FILE__)}/#{Constants::MONTANER_SAVE_DIR}/"
      save_path.gsub!("/", "\\")
      
      montaner_directory = "#{File.dirname(__FILE__)}/#{Constants::MONTANER_DIR}/"
      montaner_directory.gsub!("/", "\\")
      
      m(flats, save_path, montaner_directory)
      
      Shade.flats_generated = true
    end  
    }
    montaner_cmd.tooltip = "Generador automático de viviendas según normativa de Montaner"
    montaner_cmd.small_icon = File.join(Constants::ICONS_DIR, "montaner.PNG")
    montaner_cmd.large_icon = File.join(Constants::ICONS_DIR, "montaner.PNG")
    toolbar.add_item montaner_cmd
	
	
    
    
  # Select generate flat command
  flat_cmd = UI::Command.new("select_flat"){
  
    if Shade.flats_generated
	    
	    if Shade.contour_face
			Shade.contour_face.erase!  
			Shade.montaner_shape = nil
			Shade.contour_face = nil
			Shade.montaner_status = nil
			Shade.montaner_actions = nil
			Shade.montaner_history =Hash.new(nil)
		end
		
	    project = Shade.project
	    execution = Shade.project.execution
	    Sketchup.active_model.close_active
	    
	    prompts = ["Selecciona una vivienda: "]
	    default = [0]
	    rule_list = ShadeUtils.create_flat_list()
	    list = [rule_list]
	    input = UI.inputbox prompts, default, list, "Selector de viviendas"
	    if input
	      

	      
	      chosen_flat_idx = input[0] 
	      puts"#{File.dirname(__FILE__)}/#{Constants::MONTANER_SAVE_DIR}/plan#{chosen_flat_idx}.txt"
	      
	      chosen_axiom_path = "#{File.dirname(__FILE__)}/#{Constants::MONTANER_SAVE_DIR}/plan#{chosen_flat_idx}.txt"
	      chosen_axiom_path.gsub!("//", "\\")
	      chosen_axiom_path.gsub!("/", "\\")
	      
	      Shade.design_current_path=(chosen_axiom_path)
	      
	     new_axiom = LabelledShape.new(Array.new, Array.new)
	     new_axiom.load(chosen_axiom_path)
	     Shade.project.execution.file_axiom = true
	     Shade.project.execution.grammar.axiom = new_axiom
	     Shade.project.execution.reset
	     end
	else
		UI.messagebox("No existen planos generados automáticamente")
	end
      
  }
  flat_cmd.tooltip = "Abrir una vivienda generada automáticamente"
  flat_cmd.small_icon = File.join(Constants::ICONS_DIR, "open_montaner_house.PNG")
  flat_cmd.large_icon = File.join(Constants::ICONS_DIR, "open_montaner_house.PNG")
  toolbar.add_item flat_cmd
    
    
    
  
# Select generate flat command
all_flats_cmd = UI::Command.new("all_flats"){

 if Shade.flats_generated
	    
	    if Shade.contour_face
			Shade.contour_face.erase!  
			Shade.montaner_shape = nil
			Shade.contour_face = nil
			Shade.montaner_status = nil
			Shade.montaner_actions = nil
			Shade.montaner_history =Hash.new(nil)
		end
  project = Shade.project
  execution = Shade.project.execution
  Sketchup.active_model.close_active
    
    
    #puts"#{File.dirname(__FILE__)}/#{Constants::MONTANER_SAVE_DIR}/plan#{chosen_flat_idx}.txt"
    
    chosen_axiom_path = "#{File.dirname(__FILE__)}/#{Constants::MONTANER_SAVE_DIR}"
    chosen_axiom_path.gsub!("//", "\\")
    chosen_axiom_path.gsub!("/", "\\")
    
   
    new_axiom = Shade.project.execution.current_shape.clone
    new_axiom.several_loads(chosen_axiom_path)
    Shade.project.execution.file_axiom = true
    Shade.project.execution.grammar.axiom = new_axiom
    Shade.project.execution.reset
    
    else
		UI.messagebox("No existen planos generados automáticamente")
	end
        
}
all_flats_cmd.tooltip = "Visualizar todas las viviendas"
all_flats_cmd.small_icon = File.join(Constants::ICONS_DIR, "open_all_montaner_houses.PNG")
all_flats_cmd.large_icon = File.join(Constants::ICONS_DIR, "open_all_montaner_houses.PNG")
toolbar.add_item all_flats_cmd
	
	toolbar.add_separator
	
	# Contour command
	contour_cmd = UI::Command.new("contour"){
	
		Shade.project.execution.delete_constraint(Constants::OVERLAP_CONSTRAINT_NAME)
		Shade.project.execution.delete_constraint(Constants::NO_SCALES_CONSTRAINT_NAME)
		Shade.project.execution.delete_constraint(Constants::DISTINCT_SHAPE_CONSTRAINT_NAME)
		
		project = Shade.project
		execution = Shade.project.execution
		Sketchup.active_model.close_active
		
		if Shade.contour_face
			Shade.contour_face.erase!  
			Shade.montaner_history = Hash.new(nil)
		end
		
		contour_number = rand(200)
		
		contour_path = "#{File.dirname(__FILE__)}/../resources/contours/plan#{contour_number}.txt"
		contour_path.gsub!("//", "\\")
		contour_path.gsub!("/", "\\")
		
		execution.current_shape.load(contour_path)
		
		corners = execution.current_shape.p["Layer0"].get_node(Label.new("White")).list
		
		#We order the corners counter clock wise
		sorted_corners = Array.new
		aux_corners = corners.clone
		p = corners.first.key
		side = 1.m
		while (p)
			top_neighbor = OrderedPoint.new(Point.new(p.x, p.y + side, 0))
			right_neighbor = OrderedPoint.new(Point.new(p.x + side, p.y, 0))
			bottom_neighbor = OrderedPoint.new(Point.new(p.x, p.y - side, 0))
			left_neighbor = OrderedPoint.new(Point.new(p.x - side, p.y, 0))
      
			if aux_corners.get_node top_neighbor
				p = top_neighbor.clone
				sorted_corners.push top_neighbor.point
				aux_corners.delete_node top_neighbor
        
			elsif aux_corners.get_node right_neighbor
				p = right_neighbor.clone
				sorted_corners.push right_neighbor.point
				aux_corners.delete_node right_neighbor
        
			elsif aux_corners.get_node bottom_neighbor
				p = bottom_neighbor.clone
				sorted_corners.push bottom_neighbor.point
				aux_corners.delete_node bottom_neighbor
        
			elsif aux_corners.get_node left_neighbor
				p = left_neighbor.clone
				sorted_corners.push left_neighbor.point
				aux_corners.delete_node left_neighbor
        
			else
				p = nil
			end
		end
		
		#Make face group with the contour
		group_contour_face = Sketchup.active_model.entities.add_group
		group_contour_face.entities.add_face sorted_corners
		group_contour_face.transform! Constants::AXIOM_T
		group_contour_face.material = "white"
		
		Shade.montaner_shape = execution.current_shape.clone
		Shade.contour_face = group_contour_face
		Shade.montaner_status = "contour"
		
		montaner_history = Shade.montaner_history
		montaner_history["contour"] = execution.current_shape.clone
		Shade.montaner_history = montaner_history
		
		execution.show_labels = true
		execution.hide_black = true
		project.refresh()
	}
	contour_cmd.tooltip = "Generar contorno"
	contour_cmd.small_icon = File.join(Constants::ICONS_DIR, "contour.PNG")
	contour_cmd.large_icon = File.join(Constants::ICONS_DIR, "contour.PNG")
	toolbar.add_item contour_cmd
	
	# Distributor command
	distributor_cmd = UI::Command.new("distributor"){
		
		project = Shade.project
		execution = Shade.project.execution
		Sketchup.active_model.close_active
		
		if Shade.montaner_status == "contour" 
			
			Shade.montaner_status = "distributor"

			distributor_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\distributor.gr2"
			distributor_grammar_path.gsub!("//", "\\")
			distributor_grammar_path.gsub!("/", "\\")
			execution.grammar.load(distributor_grammar_path)
			#Load the axiom
			execution.grammar.axiom = Shade.montaner_shape
			execution.reset

	
			Shade.montaner_actions = NonEspecializedSpacesProblem.new(1.m).get_actions(State.new(Shade.montaner_shape), false)
			chosen_action = Shade.montaner_actions[rand(Shade.montaner_actions.size)]
			execution.apply_rule(chosen_action[0], chosen_action[1])
			Shade.montaner_shape = execution.current_shape.clone
			
			montaner_history = Shade.montaner_history
			montaner_history["distributor"] = execution.current_shape.clone
			montaner_history["kitchen"] = nil
			montaner_history["bathroom"] = nil
			montaner_history["non-specialized"] = nil
			montaner_history["entrance"] = nil
			montaner_history["limits"] = nil 
			Shade.montaner_history = montaner_history
			
			execution.grammar.axiom = execution.current_shape.clone
			
		elsif Shade.montaner_status == "distributor"
						
			Shade.montaner_shape = Shade.montaner_history["contour"]
			execution.grammar.axiom = Shade.montaner_shape
			execution.reset
			
			chosen_action = Shade.montaner_actions[rand(Shade.montaner_actions.size)]
			execution.apply_rule(chosen_action[0], chosen_action[1])
			Shade.montaner_shape = execution.current_shape.clone
			
			montaner_history = Shade.montaner_history
			montaner_history["distributor"] = execution.current_shape.clone
			montaner_history["kitchen"] = nil
			montaner_history["bathroom"] = nil
			montaner_history["non-specialized"] = nil
			montaner_history["entrance"] = nil
			montaner_history["limits"] = nil 
			Shade.montaner_history = montaner_history
			
			execution.grammar.axiom = execution.current_shape.clone
			
		elsif Shade.montaner_history["contour"]
			
			Shade.montaner_status = "distributor"
			
			Shade.montaner_shape = Shade.montaner_history["contour"]
			
			distributor_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\distributor.gr2"
			distributor_grammar_path.gsub!("//", "\\")
			distributor_grammar_path.gsub!("/", "\\")
			execution.grammar.load(distributor_grammar_path)
			#Load the axiom
			execution.grammar.axiom = Shade.montaner_shape
			execution.reset
			
			Shade.montaner_actions = NonEspecializedSpacesProblem.new(1.m).get_actions(State.new(Shade.montaner_shape), false)
			chosen_action = Shade.montaner_actions[rand(Shade.montaner_actions.size)]
			execution.apply_rule(chosen_action[0], chosen_action[1])
			Shade.montaner_shape = execution.current_shape.clone
			
			montaner_history = Shade.montaner_history
			montaner_history["distributor"] = execution.current_shape.clone
			montaner_history["kitchen"] = nil
			montaner_history["bathroom"] = nil
			montaner_history["non-specialized"] = nil
			montaner_history["entrance"] = nil
			montaner_history["limits"] = nil 
			Shade.montaner_history = montaner_history
			
			execution.grammar.axiom = execution.current_shape.clone
		else
			UI.messagebox("El distribuidor sólo puede ser ubicado tras generar un contorno")
		end

		
		execution.show_labels = true
		execution.hide_black = true
		project.refresh()
	}
	distributor_cmd.tooltip = "Ubicar distribuidor"
	distributor_cmd.small_icon = File.join(Constants::ICONS_DIR, "distributor.PNG")
	distributor_cmd.large_icon = File.join(Constants::ICONS_DIR, "distributor.PNG")
	toolbar.add_item distributor_cmd
	
	# Kitchen command
	kitchen_cmd = UI::Command.new("kitchen"){
		
		project = Shade.project
		execution = Shade.project.execution
		Sketchup.active_model.close_active
		
		if Shade.montaner_status == "distributor" or Shade.montaner_status == "kitchen"
			
			if Shade.montaner_status == "distributor"
				Shade.montaner_status = "kitchen"
			else
				Shade.montaner_shape = Shade.montaner_history["distributor"]
			end

			seed_kitchen_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\seed-kitchen.gr2"
			seed_kitchen_grammar_path.gsub!("//", "\\")
			seed_kitchen_grammar_path.gsub!("/", "\\")
			execution.grammar.load(seed_kitchen_grammar_path)
			#Load the axiom
			execution.grammar.axiom = Shade.montaner_shape
			execution.reset

			#Load seed kitchen policy
			seed_kitchen_policy_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\seed-kitchen-policy.pol"
			seed_kitchen_policy_path.gsub!("//", "\\")
			seed_kitchen_policy_path.gsub!("/", "\\")
			linear_coefs = Array.new
			i = 0
			File.open(seed_kitchen_policy_path, 'r') do |f|
				problem_module_name = f.gets.strip
				problem_module = SeedKitchenProblem.new(Shade.contour_face, 1.m)
				while line = f.gets
					linear_coefs[i] = line.to_f
					i += 1
				end
				Shade.problem_module = problem_module
				Shade.policy = linear_coefs
			end
			#Execute the steps for this grammar, using the policy
			execution.execute_with_general_policy(1, Shade.policy, Shade.problem_module)  
			#Save the axiom
			seed_kitchen_axiom = execution.current_shape.clone
			
			#Load kitchen grammar
			kitchen_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\kitchen.gr2"
			kitchen_grammar_path.gsub!("//", "\\")
			kitchen_grammar_path.gsub!("/", "\\")
			execution.grammar.load(kitchen_grammar_path)
			#Load the axiom
			execution.grammar.axiom = seed_kitchen_axiom
			execution.reset
			#Load kitchen policy
			kitchen_policy_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\kitchen-policy.pol"
			kitchen_policy_path.gsub!("//", "\\")
			kitchen_policy_path.gsub!("/", "\\")
			linear_coefs = Array.new
			i = 0
			File.open(kitchen_policy_path, 'r') do |f|
				problem_module_name = f.gets.strip
				problem_module = KitchenProblem.new(Shade.contour_face, 1.m, 46)  
				while line = f.gets
					linear_coefs[i] = line.to_f
					i += 1
				end
				Shade.problem_module = problem_module
				Shade.policy = linear_coefs
			end
			#Execute the steps for this grammar, using the policy
			execution.execute_with_general_policy(5, Shade.policy, Shade.problem_module)  
			#Save the axiom
			kitchen_axiom = execution.current_shape.clone
			
			#Load furniture grammar
			kitchen_furniture_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\kitchen-furniture.gr2"
			execution.grammar.load(kitchen_furniture_grammar_path)
			#Load the axiom
			execution.grammar.axiom = kitchen_axiom
			execution.reset
			#Execute the steps for this grammar, using the policy
			execution.apply_rule(1)
			execution.apply_rule(2)
			#Save the axiom
			Shade.montaner_shape = execution.current_shape.clone		

			montaner_history = Shade.montaner_history
			montaner_history["kitchen"] = execution.current_shape.clone
			montaner_history["bathroom"] = nil
			montaner_history["non-specialized"] = nil
			montaner_history["entrance"] = nil
			montaner_history["limits"] = nil 
			Shade.montaner_history = montaner_history
			
			execution.grammar.axiom = execution.current_shape.clone
			
		elsif Shade.montaner_history["distributor"]
			
			Shade.montaner_status = "kitchen"
			Shade.montaner_shape = Shade.montaner_history["distributor"]
			
			seed_kitchen_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\seed-kitchen.gr2"
			seed_kitchen_grammar_path.gsub!("//", "\\")
			seed_kitchen_grammar_path.gsub!("/", "\\")
			execution.grammar.load(seed_kitchen_grammar_path)
			#Load the axiom
			execution.grammar.axiom = Shade.montaner_shape
			execution.reset

			#Load seed kitchen policy
			seed_kitchen_policy_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\seed-kitchen-policy.pol"
			seed_kitchen_policy_path.gsub!("//", "\\")
			seed_kitchen_policy_path.gsub!("/", "\\")
			linear_coefs = Array.new
			i = 0
			File.open(seed_kitchen_policy_path, 'r') do |f|
				problem_module_name = f.gets.strip
				problem_module = SeedKitchenProblem.new(Shade.contour_face, 1.m)
				while line = f.gets
					linear_coefs[i] = line.to_f
					i += 1
				end
				Shade.problem_module = problem_module
				Shade.policy = linear_coefs
			end
			#Execute the steps for this grammar, using the policy
			execution.execute_with_general_policy(1, Shade.policy, Shade.problem_module)  
			#Save the axiom
			seed_kitchen_axiom = execution.current_shape.clone
			
			#Load kitchen grammar
			kitchen_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\kitchen.gr2"
			kitchen_grammar_path.gsub!("//", "\\")
			kitchen_grammar_path.gsub!("/", "\\")
			execution.grammar.load(kitchen_grammar_path)
			#Load the axiom
			execution.grammar.axiom = seed_kitchen_axiom
			execution.reset
			#Load kitchen policy
			kitchen_policy_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\kitchen-policy.pol"
			kitchen_policy_path.gsub!("//", "\\")
			kitchen_policy_path.gsub!("/", "\\")
			linear_coefs = Array.new
			i = 0
			File.open(kitchen_policy_path, 'r') do |f|
				problem_module_name = f.gets.strip
				problem_module = KitchenProblem.new(Shade.contour_face, 1.m, 46)  
				while line = f.gets
					linear_coefs[i] = line.to_f
					i += 1
				end
				Shade.problem_module = problem_module
				Shade.policy = linear_coefs
			end
			#Execute the steps for this grammar, using the policy
			execution.execute_with_general_policy(5, Shade.policy, Shade.problem_module)  
			#Save the axiom
			kitchen_axiom = execution.current_shape.clone
			
			#Load furniture grammar
			kitchen_furniture_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\kitchen-furniture.gr2"
			execution.grammar.load(kitchen_furniture_grammar_path)
			#Load the axiom
			execution.grammar.axiom = kitchen_axiom
			execution.reset
			#Execute the steps for this grammar, using the policy
			execution.apply_rule(1)
			execution.apply_rule(2)
			#Save the axiom
			Shade.montaner_shape = execution.current_shape.clone
			
			montaner_history = Shade.montaner_history
			montaner_history["kitchen"] = execution.current_shape.clone
			montaner_history["bathroom"] = nil
			montaner_history["non-specialized"] = nil
			montaner_history["entrance"] = nil
			montaner_history["limits"] = nil 
			Shade.montaner_history = montaner_history
			
			execution.grammar.axiom = execution.current_shape.clone
		else
			UI.messagebox("La cocina sólo puede ser ubicada tras ubicar el distribuidor")
		end

		
		execution.show_labels = true
		execution.hide_black = true
		project.refresh()
	}
	kitchen_cmd.tooltip = "Ubicar cocina"
	kitchen_cmd.small_icon = File.join(Constants::ICONS_DIR, "kitchen.PNG")
	kitchen_cmd.large_icon = File.join(Constants::ICONS_DIR, "kitchen.PNG")
	toolbar.add_item kitchen_cmd
	
	# Bathroom command
	bathroom_cmd = UI::Command.new("bathroom"){
		
		project = Shade.project
		execution = Shade.project.execution
		Sketchup.active_model.close_active
		
		if Shade.montaner_status == "kitchen" or Shade.montaner_status == "bathroom"
			
			if Shade.montaner_status == "kitchen"
				Shade.montaner_status = "bathroom"
			else
				Shade.montaner_shape = Shade.montaner_history["kitchen"]
			end

			seed_bath_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\seed-bath.gr2"
			seed_bath_grammar_path.gsub!("//", "\\")
			seed_bath_grammar_path.gsub!("/", "\\")
			execution.grammar.load(seed_bath_grammar_path)
			#Load the axiom
			execution.grammar.axiom = Shade.montaner_shape
			execution.reset

			#Load seed kitchen policy
			seed_bath_policy_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\seed-bath-policy.pol"
			seed_bath_policy_path.gsub!("//", "\\")
			seed_bath_policy_path.gsub!("/", "\\")
			linear_coefs = Array.new
			i = 0
			File.open(seed_bath_policy_path, 'r') do |f|
				problem_module_name = f.gets.strip
				problem_module = SeedBathProblem.new(Shade.contour_face, 1.m)
				while line = f.gets
					linear_coefs[i] = line.to_f
					i += 1
				end
				Shade.problem_module = problem_module
				Shade.policy = linear_coefs
			end
			#Execute the steps for this grammar, using the policy
			execution.execute_with_general_policy(1, Shade.policy, Shade.problem_module)  
			#Save the axiom
			seed_bath_axiom = execution.current_shape.clone
			
			#Load kitchen grammar
			bath_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\bath.gr2"
			bath_grammar_path.gsub!("//", "\\")
			bath_grammar_path.gsub!("/", "\\")
			execution.grammar.load(bath_grammar_path)
			#Load the axiom
			execution.grammar.axiom = seed_bath_axiom
			execution.reset
			#Load kitchen policy
			bath_policy_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\bath-policy.pol"
			bath_policy_path.gsub!("//", "\\")
			bath_policy_path.gsub!("/", "\\")
			linear_coefs = Array.new
			i = 0
			File.open(bath_policy_path, 'r') do |f|
				problem_module_name = f.gets.strip
				problem_module = BathProblem.new(Shade.contour_face, 1.m)  
				while line = f.gets
					linear_coefs[i] = line.to_f
					i += 1
				end
				Shade.problem_module = problem_module
				Shade.policy = linear_coefs
			end
			#Execute the steps for this grammar, using the policy
			execution.execute_with_general_policy(1, Shade.policy, Shade.problem_module)  
			bath_axiom = execution.current_shape.clone
			
			#Load walls grammar (bath)
			bath_walls_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\bath-walls.gr2"
			execution.grammar.load(bath_walls_grammar_path)
			#Load the axiom
			execution.grammar.axiom = bath_axiom
			execution.reset
			execution.execute_until_end
			walls_bath_axiom = execution.current_shape.clone
			
			#Load bath furniture grammar
			bath_furniture_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\bath-furniture.gr2"
			execution.grammar.load(bath_furniture_grammar_path)
			#Load the axiom
			execution.grammar.axiom = walls_bath_axiom
			execution.reset
			#Execute the steps for this grammar, using the policy
			execution.apply_rule(2)
			execution.apply_rule(1)
			#Save the axiom
			furniture_bath_axiom = execution.current_shape.clone

			#PHASE 12. Load erase bath walls grammar
			erase_bath_walls_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\erase-bath-walls.gr2"
			execution.grammar.load(erase_bath_walls_grammar_path)
			#Load the axiom
			execution.grammar.axiom = furniture_bath_axiom
			execution.reset
			#Execute the steps for this grammar, using the policy
			execution.execute_until_end
			
			#Save the axiom
			Shade.montaner_shape = execution.current_shape.clone	

			montaner_history = Shade.montaner_history
			montaner_history["bathroom"] = execution.current_shape.clone
			montaner_history["non-specialized"] = nil
			montaner_history["entrance"] = nil
			montaner_history["limits"] = nil 
			Shade.montaner_history = montaner_history
			
			execution.grammar.axiom = execution.current_shape.clone
			
		elsif Shade.montaner_history["kitchen"]
			
			Shade.montaner_status = "bathroom"
			Shade.montaner_shape = Shade.montaner_history["kitchen"]
			
			seed_bath_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\seed-bath.gr2"
			seed_bath_grammar_path.gsub!("//", "\\")
			seed_bath_grammar_path.gsub!("/", "\\")
			execution.grammar.load(seed_bath_grammar_path)
			#Load the axiom
			execution.grammar.axiom = Shade.montaner_shape
			execution.reset

			#Load seed kitchen policy
			seed_bath_policy_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\seed-bath-policy.pol"
			seed_bath_policy_path.gsub!("//", "\\")
			seed_bath_policy_path.gsub!("/", "\\")
			linear_coefs = Array.new
			i = 0
			File.open(seed_bath_policy_path, 'r') do |f|
				problem_module_name = f.gets.strip
				problem_module = SeedBathProblem.new(Shade.contour_face, 1.m)
				while line = f.gets
					linear_coefs[i] = line.to_f
					i += 1
				end
				Shade.problem_module = problem_module
				Shade.policy = linear_coefs
			end
			#Execute the steps for this grammar, using the policy
			execution.execute_with_general_policy(1, Shade.policy, Shade.problem_module)  
			#Save the axiom
			seed_bath_axiom = execution.current_shape.clone
			
			#Load kitchen grammar
			bath_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\bath.gr2"
			bath_grammar_path.gsub!("//", "\\")
			bath_grammar_path.gsub!("/", "\\")
			execution.grammar.load(bath_grammar_path)
			#Load the axiom
			execution.grammar.axiom = seed_bath_axiom
			execution.reset
			#Load kitchen policy
			bath_policy_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\bath-policy.pol"
			bath_policy_path.gsub!("//", "\\")
			bath_policy_path.gsub!("/", "\\")
			linear_coefs = Array.new
			i = 0
			File.open(bath_policy_path, 'r') do |f|
				problem_module_name = f.gets.strip
				problem_module = BathProblem.new(Shade.contour_face, 1.m)  
				while line = f.gets
					linear_coefs[i] = line.to_f
					i += 1
				end
				Shade.problem_module = problem_module
				Shade.policy = linear_coefs
			end
			#Execute the steps for this grammar, using the policy
			execution.execute_with_general_policy(1, Shade.policy, Shade.problem_module)  
			bath_axiom = execution.current_shape.clone
			
			#Load walls grammar (bath)
			bath_walls_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\bath-walls.gr2"
			execution.grammar.load(bath_walls_grammar_path)
			#Load the axiom
			execution.grammar.axiom = bath_axiom
			execution.reset
			execution.execute_until_end
			walls_bath_axiom = execution.current_shape.clone
			
			#Load bath furniture grammar
			bath_furniture_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\bath-furniture.gr2"
			execution.grammar.load(bath_furniture_grammar_path)
			#Load the axiom
			execution.grammar.axiom = walls_bath_axiom
			execution.reset
			#Execute the steps for this grammar, using the policy
			execution.apply_rule(2)
			execution.apply_rule(1)
			#Save the axiom
			furniture_bath_axiom = execution.current_shape.clone

			#PHASE 12. Load erase bath walls grammar
			erase_bath_walls_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\erase-bath-walls.gr2"
			execution.grammar.load(erase_bath_walls_grammar_path)
			#Load the axiom
			execution.grammar.axiom = furniture_bath_axiom
			execution.reset
			#Execute the steps for this grammar, using the policy
			execution.execute_until_end
			
			#Save the axiom
			Shade.montaner_shape = execution.current_shape.clone	

			montaner_history = Shade.montaner_history
			montaner_history["bathroom"] = execution.current_shape.clone
			montaner_history["non-specialized"] = nil
			montaner_history["entrance"] = nil
			montaner_history["limits"] = nil 
			Shade.montaner_history = montaner_history
			
			execution.grammar.axiom = execution.current_shape.clone
		else
			UI.messagebox("El bano sólo puede ser ubicado tras ubicar la cocina")
		end

		
		execution.show_labels = true
		execution.hide_black = true
		project.refresh()
	}
	bathroom_cmd.tooltip = "Ubicar cuarto de bano"
	bathroom_cmd.small_icon = File.join(Constants::ICONS_DIR, "bathroom.PNG")
	bathroom_cmd.large_icon = File.join(Constants::ICONS_DIR, "bathroom.PNG")
	toolbar.add_item bathroom_cmd
	
	# Non-specialized command
	n_s_cmd = UI::Command.new("non-specialized"){
		
		project = Shade.project
		execution = Shade.project.execution
		Sketchup.active_model.close_active
		
		if Shade.montaner_status == "bathroom" or Shade.montaner_status == "ne"
			
			if Shade.montaner_status == "bathroom"
				Shade.montaner_status = "ne"
			else
				Shade.montaner_shape = Shade.montaner_history["bathroom"]
			end

			non_specialized_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\non-especialized.gr2"
			non_specialized_grammar_path.gsub!("//", "\\")
			non_specialized_grammar_path.gsub!("/", "\\")
			execution.grammar.load(non_specialized_grammar_path)
			#Load the axiom
			execution.grammar.axiom = Shade.montaner_shape
			execution.reset

			non_specialized_policy_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\non-especialized-policy.pol"
			non_specialized_policy_path.gsub!("//", "\\")
			non_specialized_policy_path.gsub!("/", "\\")
			linear_coefs = Array.new
			i = 0
			File.open(non_specialized_policy_path, 'r') do |f|
				problem_module_name = f.gets.strip
				problem_module = NonEspecializedSpacesProblem.new(1.m)
				while line = f.gets
					linear_coefs[i] = line.to_f
					i += 1
				end
				Shade.problem_module = problem_module
				Shade.policy = linear_coefs
			end
			#Execute the steps for this grammar, using the policy
			execution.execute_with_general_policy(2, Shade.policy, Shade.problem_module)  	
			
			#Save the axiom
			Shade.montaner_shape = execution.current_shape.clone		

			montaner_history = Shade.montaner_history
			montaner_history["non-specialized"] = execution.current_shape.clone
			montaner_history["entrance"] = nil
			montaner_history["limits"] = nil 
			Shade.montaner_history = montaner_history
			
			execution.grammar.axiom = execution.current_shape.clone
			
		elsif Shade.montaner_history["bathroom"]
			
			Shade.montaner_status = "ne"
			Shade.montaner_shape = Shade.montaner_history["bathroom"]
			
			non_specialized_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\non-especialized.gr2"
			non_specialized_grammar_path.gsub!("//", "\\")
			non_specialized_grammar_path.gsub!("/", "\\")
			execution.grammar.load(non_specialized_grammar_path)
			#Load the axiom
			execution.grammar.axiom = Shade.montaner_shape
			execution.reset

			non_specialized_policy_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\non-especialized-policy.pol"
			non_specialized_policy_path.gsub!("//", "\\")
			non_specialized_policy_path.gsub!("/", "\\")
			linear_coefs = Array.new
			i = 0
			File.open(non_specialized_policy_path, 'r') do |f|
				problem_module_name = f.gets.strip
				problem_module = NonEspecializedSpacesProblem.new(1.m)
				while line = f.gets
					linear_coefs[i] = line.to_f
					i += 1
				end
				Shade.problem_module = problem_module
				Shade.policy = linear_coefs
			end
			#Execute the steps for this grammar, using the policy
			execution.execute_with_general_policy(2, Shade.policy, Shade.problem_module)  	
			
			#Save the axiom
			Shade.montaner_shape = execution.current_shape.clone		

			montaner_history = Shade.montaner_history
			montaner_history["non-specialized"] = execution.current_shape.clone
			montaner_history["entrance"] = nil
			montaner_history["limits"] = nil 
			Shade.montaner_history = montaner_history
			
			execution.grammar.axiom = execution.current_shape.clone
		else
			UI.messagebox("Los ámbitos no especializados sólo pueden ser ubicados tras el bano")
		end

		
		execution.show_labels = true
		execution.hide_black = true
		project.refresh()
	}
	n_s_cmd.tooltip = "Ubicar ámbitos no especializados"
	n_s_cmd.small_icon = File.join(Constants::ICONS_DIR, "n-e.PNG")
	n_s_cmd.large_icon = File.join(Constants::ICONS_DIR, "n-e.PNG")
	toolbar.add_item n_s_cmd
	
	# Entrance command
	entrance_cmd = UI::Command.new("entrance"){
		
		project = Shade.project
		execution = Shade.project.execution
		Sketchup.active_model.close_active
		
		if Shade.montaner_status == "ne" or Shade.montaner_status == "entrance"
			
			if Shade.montaner_status == "ne"
				Shade.montaner_status = "entrance"
			else
				Shade.montaner_shape = Shade.montaner_history["non-specialized"]
			end

			entrance_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\entrance.gr2"
			entrance_grammar_path.gsub!("//", "\\")
			entrance_grammar_path.gsub!("/", "\\")
			execution.grammar.load(entrance_grammar_path)
			#Load the axiom
			execution.grammar.axiom = Shade.montaner_shape
			execution.reset

			#Load seed kitchen policy
			entrance_policy_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\entrance-policy.pol"
			entrance_policy_path.gsub!("//", "\\")
			entrance_policy_path.gsub!("/", "\\")
			linear_coefs = Array.new
			i = 0
			File.open(entrance_policy_path, 'r') do |f|
				problem_module_name = f.gets.strip
				problem_module = EntranceProblem.new(1.m)
				while line = f.gets
					linear_coefs[i] = line.to_f
					i += 1
				end
				Shade.problem_module = problem_module
				Shade.policy = linear_coefs
			end
			#Execute the steps for this grammar, using the policy
			execution.execute_with_general_policy(1, Shade.policy, Shade.problem_module)  
			entrance_axiom = execution.current_shape.clone	

			 #PHASE 13. Load flat door grammar
			flat_door_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\flat-door.gr2"
			execution.grammar.load(flat_door_grammar_path)
			#Load the axiom
			execution.grammar.axiom = entrance_axiom
			execution.reset
			#Execute the steps for this grammar, using the policy
			execution.execute_until_end
			
			#Save the axiom
			Shade.montaner_shape = execution.current_shape.clone	

			montaner_history = Shade.montaner_history
			montaner_history["entrance"] = execution.current_shape.clone
			montaner_history["limits"] = nil 
			Shade.montaner_history = montaner_history
			
			execution.grammar.axiom = execution.current_shape.clone
			
		elsif Shade.montaner_history["non-specialized"]
			
			Shade.montaner_status = "entrance"
			Shade.montaner_shape = Shade.montaner_history["non-specialized"]
			
			entrance_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\entrance.gr2"
			entrance_grammar_path.gsub!("//", "\\")
			entrance_grammar_path.gsub!("/", "\\")
			execution.grammar.load(entrance_grammar_path)
			#Load the axiom
			execution.grammar.axiom = Shade.montaner_shape
			execution.reset

			#Load seed kitchen policy
			entrance_policy_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\entrance-policy.pol"
			entrance_policy_path.gsub!("//", "\\")
			entrance_policy_path.gsub!("/", "\\")
			linear_coefs = Array.new
			i = 0
			File.open(entrance_policy_path, 'r') do |f|
				problem_module_name = f.gets.strip
				problem_module = EntranceProblem.new(1.m)
				while line = f.gets
					linear_coefs[i] = line.to_f
					i += 1
				end
				Shade.problem_module = problem_module
				Shade.policy = linear_coefs
			end
			#Execute the steps for this grammar, using the policy
			execution.execute_with_general_policy(1, Shade.policy, Shade.problem_module)  
			entrance_axiom = execution.current_shape.clone	

			 #PHASE 13. Load flat door grammar
			flat_door_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\flat-door.gr2"
			execution.grammar.load(flat_door_grammar_path)
			#Load the axiom
			execution.grammar.axiom = entrance_axiom
			execution.reset
			#Execute the steps for this grammar, using the policy
			execution.execute_until_end
			
			#Save the axiom
			Shade.montaner_shape = execution.current_shape.clone	

			montaner_history = Shade.montaner_history
			montaner_history["entrance"] = execution.current_shape.clone
			montaner_history["limits"] = nil 
			Shade.montaner_history = montaner_history
			
			execution.grammar.axiom = execution.current_shape.clone
		else
			UI.messagebox("La entrada sólo puede ser ubicada tras los ámbitos no especializados")
		end

		
		execution.show_labels = true
		execution.hide_black = true
		project.refresh()
	}
	entrance_cmd.tooltip = "Ubicar entrada"
	entrance_cmd.small_icon = File.join(Constants::ICONS_DIR, "entrance.PNG")
	entrance_cmd.large_icon = File.join(Constants::ICONS_DIR, "entrance.PNG")
	toolbar.add_item entrance_cmd
	
	# Limits command
	limits_cmd = UI::Command.new("limits"){
		
		project = Shade.project
		execution = Shade.project.execution
		Sketchup.active_model.close_active
		
		if Shade.montaner_status == "entrance" or Shade.montaner_status == "limits"
			
			if Shade.montaner_status == "entrance"
				Shade.montaner_status = "limits"
			else
				Shade.montaner_shape = Shade.montaner_history["entrance"]
			end

			limits_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\room-walls.gr2"
			limits_grammar_path.gsub!("//", "\\")
			limits_grammar_path.gsub!("/", "\\")
			execution.grammar.load(limits_grammar_path)
			#Load the axiom
			execution.grammar.axiom = Shade.montaner_shape
			execution.reset
			
			execution.add_constraint(NoScalesConstraint.new)
			project.refresh(true)

			execution.apply_rule_random()
			execution.apply_rule_random()
			
			execution.delete_constraint(Constants::NO_SCALES_CONSTRAINT_NAME)
			
			#Save the axiom
			Shade.montaner_shape = execution.current_shape.clone		

			montaner_history = Shade.montaner_history
			montaner_history["limits"] = execution.current_shape.clone
			Shade.montaner_history = montaner_history
			
			execution.grammar.axiom = execution.current_shape.clone
			
		elsif Shade.montaner_history["entrance"]
			
			Shade.montaner_status = "limits"
			Shade.montaner_shape = Shade.montaner_history["entrance"]
			
			limits_grammar_path = "#{File.dirname(__FILE__)}\\#{Constants::MONTANER_DIR}\\room-walls.gr2"
			limits_grammar_path.gsub!("//", "\\")
			limits_grammar_path.gsub!("/", "\\")
			execution.grammar.load(limits_grammar_path)
			#Load the axiom
			execution.grammar.axiom = Shade.montaner_shape
			execution.reset
			
			execution.add_constraint(NoScalesConstraint.new)
			project.refresh(true)

			execution.apply_rule_random()
			execution.apply_rule_random()
			
			execution.delete_constraint(Constants::NO_SCALES_CONSTRAINT_NAME)
			
			#Save the axiom
			Shade.montaner_shape = execution.current_shape.clone		

			montaner_history = Shade.montaner_history
			montaner_history["limits"] = execution.current_shape.clone
			Shade.montaner_history = montaner_history
			
			execution.grammar.axiom = execution.current_shape.clone
		else
			UI.messagebox("Los límites de los ámbitos no especializados sólo pueden ubicarse tras la entrada")
		end

		
		execution.show_labels = true
		execution.hide_black = true
		project.refresh()
	}
	limits_cmd.tooltip = "Ubicar límites para los ámbitos no especializados"
	limits_cmd.small_icon = File.join(Constants::ICONS_DIR, "delimit.PNG")
	limits_cmd.large_icon = File.join(Constants::ICONS_DIR, "delimit.PNG")
	toolbar.add_item limits_cmd
	

	
	toolbar.show
	
	
end



