require 'cdo'

cdo = Cdo.new
cdo.debug = true

inputfile = ARGV[0]
puts "inputfile: #{inputfile}"
outputfile = 'sortedInput.nc'

lowerBoundary = cdo.outputkey('value,nohead', input: '-fldmin '+inputfile)[0].to_f

mask = cdo.gtc(lowerBoundary-1.0,input: inputfile)

unstructuredInput = cdo.reducegrid(mask,input: inputfile, options: '-f nc')

sortedIndexList = cdo.outputkey('value,xind,nohead', input: unstructuredInput).map(&:split).map {|a|
  [a[0].to_f,a[1].to_i]  # convert values to float, index to integer
}.sort_by {|a|
  a[0]                   # sort by value
}.map {|a|
  a[1]                   # select index only
}
# or in a single line
# sortedIndexList = cdo.outputkey('value,xind,nohead', input: unstructuredInput).map(&:split).map {|a| [a[0].to_f,a[1].to_i]}.sort_by {|a| a[0]}.map {|a| a[1]}
pp sortedIndexList

cdo.selgridcell(sortedIndexList, input: unstructuredInput, output: outputfile)


