import java.util.Scanner;
import java.io.*;

/*
 * Problem 4:  HS CS Programming Contest
 * Author:     William kreahling
 * Date:       March 2006
 *
 * Program:    Directory Lister, recusrsively lists directories in the 
 *             one specified at the prompt
 * NOTE:       This version uses the Scanner class
 */
public class DirectoryLister
{
   public static void main(String[] args) throws Exception
   {
      // Scanner and File variables
      Scanner scanIn = new Scanner(System.in);
      File fileIn;
      String fileName;

      // Create a valid file object
      do
      {
         System.out.print("Please enter a directory name >");
         fileName = scanIn.next();
         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 this directory
      File[] list = fileIn.listFiles();

      // print directory name
      System.out.println(fileIn.getName());
      // Print the files in the 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 - plain old printable filename
      else
      {
         System.out.println(indent + fileName.getName());
      }
   }
}
