import java.io.*;

/*
 * Problem 4:  HS CS Programming Contest
 * Author:     William kreahling
 * Date:       March 2006
 *
 * Program:    DirLister, recusrsively lists directories in the 
 *             one specified at the prompt
 * NOTE:       This version uses BufferedReader
 */

public class DirLister
{
   public static void main(String[] args) throws Exception
   {
      // BufferedReader and File variables
      BufferedReader bufIn = new BufferedReader(
                             new InputStreamReader(System.in)); 
      File fileIn;
      String fileName;

      // Create a valid File object
      do
      {
         System.out.print("Please enter a directory name >");
         fileName = bufIn.readLine();
         fileIn = new File(fileName);

         if (!fileIn.exists() || !fileIn.isDirectory()) 
            System.out.println("Invalid directory name, please try again");

      }while (!fileIn.exists() || !fileIn.isDirectory()); 


      // Get files in the current directory
      File[] list = fileIn.listFiles();

      // print directory name
      System.out.println(fileIn.getName());
      // print the files in this directory
      for (int i = 0; i < list.length; i++)
         listDir("", list[i]);
   }

 /*
    * listDir - prints out the files in the current directory with the
    *           proper indentation. If the file is in actuality a 
    *           subdirectory, calls itself recursively to handle it
    *
    * Parameters: indent - current amount of indentation
    *             filename - current file to list or check
    */
   public static void listDir(String indent, File fileName) throws Exception
   {
      indent = indent + "  "; // increase indentation
      /*
       * If this file is a directory, print it out, and then get
       * all the files in this directory and call func recursively
       */
      if (fileName.isDirectory())
      {
         System.out.println(indent + fileName.getName());
         File[] list = fileName.listFiles();

         for (int i = 0; i < list.length; i++)
            listDir(indent, list[i]); 
      }
      // base case - a plain old file to print
      else
      {
         System.out.println(indent + fileName.getName());
      }
   }
}
