/* Problem 1--Toric Boggle
   This is a good example of using recursion to solve a problem.  Trying
   to compute the twisty-turny direction changes without recursion could
   be quite nasty! */

import java.io.*;
import java.util.*;

public class prob1 {

 public static Scanner in=null;
 public static PrintWriter out=null;
 public static char Grid[][] = new char[10][];
 public static int rct=0, cct=0, ct=0, cs=0;
  // ct is number of appearances of the word

 public static void main (String[] args) throws Exception {

  in = new Scanner (new File ("prob1.in"));
  out = new PrintWriter ("prob1.out");
  while (in.hasNextLine()) {
   rct=0;
   String line=null;
   while (!(line=in.nextLine()).equals("")) //read in the grid
    Grid[rct++] = line.toCharArray();
   cct = Grid[0].length;
   ct = 0;
   String search=in.nextLine(); // read in the word
   in.nextLine();
   for (int i=0; i < rct; i++) // check each square to see if the word
    for (int j=0; j < cct; j++) // begins there.
     Process (search,i,j);
   out.println ("Case "+(++cs)+": "+search+" appears "+ct+" time(s).");
   out.println ();
  }
  in.close();
  out.close();
 }

/* Process looks for the word beginning at the specified square. */

 public static void Process (String search, int i, int j) {

  if (Grid[i][j] != search.charAt (0)) return;
       // first character doesn't match.
  if (search.length()==1) {ct++; return;} // word of length one.
  char t = Grid[i][j]; // Put an * in the grid so we don't count this
  Grid[i][j]='*';      // letter again.
  int left = (j+cct-1)%cct, right = (j+1)%cct, // directions to move in
      up = (i+rct-1)%rct, down = (i+1)%rct;    // the grid.
  Process (search.substring(1),up,left);
  Process (search.substring(1),down,left); //Try all 8 directions.
  Process (search.substring(1),i,left);
  Process (search.substring(1),up,right);
  Process (search.substring(1),down,right);
  Process (search.substring(1),i,right);
  Process (search.substring(1),up,j);
  Process (search.substring(1),down,j);
  Grid[i][j] = t;  // Restore the character we *'ed.
 }
}
