import Control.Applicative ((<$>), (<*>))
import Control.Monad
import Data.List
import Text.Printf
import Data.List.Split (splitOn)
import Data.Array

main :: IO ()
main = solve 1

solve :: Int -> IO ()
solve n = do
  mw <- inp toInt
  if mw == 0 then return () else do
    nt <- inp toInt
    iot <- inpn nt $ map toInt . splitOn ","
    printf "Case %d:\n" n
    let (sv, sw) = thief mw nt iot
    print sv
    print sw
    solve (n+1)

thief :: Int -> Int -> [[Int]] -> (Int, Int)
thief mw nt iot = (narr ! (nt,mw), mwomv narr (nt, mw))
  where
    narr = foldl (updTbl iot) (listArray ((0, 0),(nt, mw)) (repeat 0)) [(i,j) | i <- [0..nt-1], j <- [0..mw]]
      
updTbl :: [[Int]] -> Array (Int, Int) Int -> (Int, Int) -> Array (Int, Int) Int
updTbl iot dp (i,j) = dp //[((i+1,j), nv)]
  where
    v = voi iot i
    w = woi iot i
    nv = if j >= w then max (dp ! (i, j)) (v + dp ! (i, j - w)) else dp ! (i, j)

mwomv :: Array (Int, Int) Int -> (Int, Int) -> Int
mwomv ar (i,j) = if ar ! (i,j) == ar ! (i,j-1) then mwomv ar (i,j-1) else j
                                                                     
voi :: [[Int]] -> Int -> Int
voi iot i = iot !! i !! 0

woi :: [[Int]] -> Int -> Int
woi iot i = iot !! i !! 1

toInt :: String -> Int
toInt s = read s

inp :: (String -> a) -> IO a
inp f = f <$> getLine

inpn :: Int -> (String -> a) -> IO [a]
inpn n f = map f <$> replicateM n getLine