=begin
(c) TIG 2012

  TIG-export_SKP_by_layer.rb
  
Usage: Type into the Ruby Console
  TIG.export_SKP_by_layer
Exports everything in the current Model into a set of SKP files 'by Layer', 
Faces with Edges on another layer take those Edges with them.
Potential duplicate layer/skp names are suffixed _1 etc...
Unused 'empty' layers are ignored.
The files are named 'C:/modelpath/modelname-layername.skp'
Only -_a-zA-Z0-9 are used in the file name, all other characters are made '_'

###cls;load'export_SKP_by_layer.rb!';TIG.export_SKP_by_layer

=end
require 'sketchup.rb'
module TIG
def self.export_SKP_by_layer()
  model=Sketchup.active_model
  entities=model.active_entities
  defns=model.definitions
  clayer=model.active_layer
  model.active_layer=nil
  dlayer=model.active_layer
  model.active_layer=clayer
  layers=model.layers
  modelp=model.path.tr("\\","/")
  if modelp.empty?
    puts "Model has not been saved! Exiting..."
    return nil
  end#if
  puts "\nExporting from...\n  "+modelp+"\nas\n\n"
  model.save(modelp)
  modelpath=File.dirname(modelp)
  modeltitle=model.title
  count=0
  usedlayers=[]
  layers.each{|layer|
    model.start_operation("Export SKP by Layer")
	lname=layer.name
	layers.purge_unused
	unless layers[lname]
	  puts lname+" == Empty"
	  model.abort_operation
	  next
	end
    entities.each{|e|
      if e.valid? and e.layer !=layer
        if e.class==Sketchup::Edge
          faceless=true
          e.faces.each{|f|
            if f.layer==layer
              faceless=false ### keep edge NOT on layer if its face is on layer
              break
            end#if
          }
          e.erase! if faceless
        else
          e.erase!
        end#if
      end#if
    }
    defns.each{|defn|
     defn.entities.each{|e|
      if e.valid? and not e.layer==nil and e.layer !=layer
        if e.class==Sketchup::Edge
          faceless=true
          e.faces.each{|f|
            if f.layer==layer
              faceless=false ### keep edge NOT on layer if its face is on layer
              break
            end#if
          }
          e.erase! if faceless
        else
          e.erase!
        end#if
      end#if
     }
    }
    layername=layer.name.gsub(/[^-_a-zA-Z0-9]/,'_')
	ln=layername+'0'
	while usedlayers.include?(layername)
	  layername=ln.next!
	end
	usedlayers << layername
	path=File.join(modelpath, modeltitle+"-"+layername+".skp").tr("\\","/")
    ### exporter
	model.save(path)
	Sketchup.open_file(modelp)
	puts path
	###
    count+=1
    model.abort_operation
  }#end layers
  puts "\n"+count.to_s+" Layers Exported as 'SKP' files."
  p usedlayers
end#def
end#module
###