loop do
  w = gets.to_i
  n ||= 0
  break if w==0
  data = gets.to_i.times.map{ gets.split(",").map(&:to_i) }.sort_by{|i,_| -i}
  av,aw = 0,0
  data.each do |vi,wi|
    if aw+wi <= w
      av, aw = av+vi, aw+wi
    end
  end
  puts "Case #{n}"
  puts [av, aw]
  n += 1
end