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

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
    (sv, sw) <- thief mw nt iot
    print sv
    print sw
    solve (n+1)

thief :: Int -> Int -> [[Int]] -> IO (Int, Int)
thief mw nt iot = do
  arr <- newListArray ((0, 0),(nt, mw)) (repeat 0) :: IO (IOUArray (Int, Int) Int)
  forM_ [0..nt-1] $ \i -> do
    forM_ [0..mw] $ \j -> do
      let v = voi iot i
      let w = woi iot i
      v1 <- readArray arr (i,j)
      if j >= w then do
        v2 <- readArray arr (i, j - w)
        writeArray arr (i + 1, j) (max v1 (v + v2))
      else writeArray arr (i + 1, j) v1
  mv <- readArray arr (nt, mw)
  mwmv <- mwomv arr (nt, mw)
  return (mv, mwmv)
      
mwomv :: IOUArray (Int, Int) Int -> (Int, Int) -> IO Int
mwomv ar (i,j) = do
  v1 <- readArray ar (i, j)
  v2 <- readArray ar (i, j - 1)
  if v1 == v2 then mwomv ar (i,j-1) else return 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