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
  iarr <- newListArray ((0, 0),(nt, mw)) (repeat 0) :: IO (IOUArray (Int, Int) Int)
  narr <- foldM (updTbl iot) iarr [(i,j) | i <- [0..nt-1], j <- [0..mw]]
  mv <- readArray narr (nt, mw)
  mwmv <- mwomv narr (nt, mw)
  return (mv, mwmv)
      
updTbl :: [[Int]] -> IOUArray (Int, Int) Int -> (Int, Int) -> IO (IOUArray (Int, Int) Int)
updTbl iot dp (i,j) = do
  v1 <- readArray dp (i, j)
  if j >= w then do
    v2 <- readArray dp (i, j - w)
    writeArray dp (i + 1, j) (max v1 (v + v2))
    return dp
  else do
    writeArray dp (i + 1, j) v1
    return dp
  where
    v = voi iot i
    w = woi iot i

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