#  Draco Econometrics
#  Copyright (C) 2006-2008 Approximatrix, LLC
#  http://www.approximatrix.com
#  
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

module Model

    class Data
        
        def to_matrix(*args)
            
            # puts args.to_s
            # puts args.class.to_s
            # puts args[0].class.to_s
          
            if(args.length == 0)
          	    to_matrix variables
            elsif(args.length > 1)
                passing = []
                args.each do |x|
                    passing << x if x.is_a? String
                    passing = passing + x if x.is_a? Array
                end
                to_matrix passing
            elsif(args.length == 1)
                array = args[0]
                builder = java.lang.String[array.length].new
                array.length.times do |i|
                    raise ArgumentError, "Input should be an array of variable names or indices to export" unless array[i].is_a? String or array[i].is_a? Fixnum

                    builder[i] = array[i] if array[i].is_a? String and @stmodel.getColumnNumber(array[i]) >= 0
                    
                    begin
                      builder[i] = @variables[array[i]].name if array[i].is_a? Fixnum
                    rescue
                      raise ArgumentError, "Index out of range: #{array[i]}"
                    end
                    
                end
                rows = @stmodel.getNonNullRows(builder)
                mat = @stmodel.getDataDouble(rows,builder)
                
                # Convert data to ruby arrays for matrix creation
                rows = []
                mat.length.times do |i|
                  row = []
                  mat[i].length.times do |j|
                    row << mat[i][j]
                  end 
                  rows << row
                end
                
                Matrix.rows rows
            end
        end
        
    end

end
