c = 1 
while true 
  m = gets.to_i

  break if m == 0

  n = gets.to_i
  v, w, rv, rw = [].to_a, [].to_a, [].to_a , [].to_a
  n.times { |i| v[i], w[i] = gets.split(',').map(&:to_i) }

  mv, mw = 0, 0

  (1..n).each { |i| 
    vc = v.combination(i).to_a
    wc = w.combination(i).to_a        
    (0..vc.size - 1).each { |j| 
      tw = wc[j].inject(:+)
      if tw <= m
        tv = vc[j].inject(:+)
        if tv > mv
          mv, mw = tv, tw
        elsif tv == mv
          mv, mw = tv, [mw, tw].min
        end
       end 
    }   
  }
  puts "Case #{c}:"
  puts mv
  puts mw
  c += 1
end