#!/usr/bin/perl

use strict;
use Term::ANSIColor;

system ('clear');
###############################################################################################################
print   color("red"),   "###############################################################",color("reset"),"\n",
        color("white"), "Presenting:                                                    ",color("reset"),"\n",
        color("white"), "       Exersize 10.7                                          ",color("reset"),"\n",
        color("red"),   "###############################################################",color("reset"),"\n";
print   "Part 1:",color("magenta"),"\tRead in all words from dictionary file.           ",color("reset"),"\n",
                  color("magenta"),"\tSeparate the words into files based on the first two letters of each word",color("reset"),"\n",
	          color("magenta"),"\tSeparate the files into directories based on the first lettter of each word.",color("reset"),"\n";

###############################################################################################################
# Create dictionary
print color("green"),"Preparing the dictionary file, please wait\n";
open (DICTIONARY_DATA,"aspell dump master |") || die "Could not get dictionary data:\t$!\n";   # Pipe on Right captures output of aspell
open (WRITE_DICTIONARY, ">dictionary.txt") || die "Could write to dictionary.txt:\t$!\n";      # Open file dictionary.txt for write
while (<DICTIONARY_DATA>){
    print WRITE_DICTIONARY $_;
}
close (DICTIONARY_DATA);
close (WRITE_DICTIONARY);
###############################################################################################################
# open the dictionary for reading
open (DICTIONARY,"<dictionary.txt") || die "Couldn't open dectionary.txt:\t$!\n"; 
while (<DICTIONARY>){
   chomp ( my $stuff="$_");
   #  
   # This if statement saves me from dealing with 1 letter words,
   # because they do not match the 2 letter pattern.
   #
   if ( $stuff =~ m/^((\w)\w).*/i){ 
       # There is a benefit to not using .txt extentions.
       # my $file = lc($1).".txt";
       #
       my $file = lc($1);
       my $directory = lc($2);
       if ( ! -d "$directory" ){
         mkdir ( "$directory" ) or die "Could not create $directory:\t$!\n";
       }
       open ( FILE, ">>$directory/$file") or die "Could not write $file:\t$!\n";
       print FILE "$stuff\n"; 
       close (FILE);
   }
}
print color("yellow");print "\ndone\n", color("reset");
#print color("green"); system ('ls '); print color("reset");
#############################################################################################################################
print   "Part 2:",color("magenta"),"\tInput a word." ,color("reset"),"\n",
                  color("magenta"),"\tCheck to see if the word is in one of the files created in Part 1." ,color("reset"),"\n",
	          color("magenta"),"\t\tIf found, ask if word should be deleted, and delete it."          ,color("reset"),"\n",
		  color("magenta"),"\t\tIf it is the last word in the file, delete the file."             ,color("reset"),"\n",
		  color("magenta"),"\t\tIf not found, ask if the word should be added, add it."             ,color("reset"),"\n";
		  

my $morewords=1;  #my couter to tell when to stop asking for words
while ($morewords){
  print color("green"),"Please enter a word of at least 2 characters:\t",color("reset");
  chomp ( my $word=<STDIN> );

  # Check for 2 letter words, and store directory and file to be searched.
  unless ( $word =~ m/^((\w)\w)\w*$/i){
     print color("red"),"You must enter a word with at least 2 letters and no spaces",color("reset"),"\n";
     next;
  }
  my $file = lc($1);
  my $directory = lc($2);         
  ##################################################
  # Search for word in file, Set "word_found"
  my $word_found = &Search_for_word( $word, $file, $directory);
  if ( $word_found ){
    # Ask if we should remove it.
    &Remove_Word($word, $file, $directory);	 
  } else {
    # Ask if we should add it. 
    &Add_Word( $word, $file, $directory);
  }		 		  
}
##########################################################
sub Search_for_word {
  my $word= shift;
  my $file= shift;
  my $directory = shift;
  print "Searching for $word\tin\t$directory/$file\n";

  # Check to see if directory exists
  if ( -d "$directory" ){   
    # Check to see if file exists
    if ( -f "$directory/$file" ){
      open (FILE, "<$directory/$file") || die "Could not read $directory $file:\t$!\n";
      while (<FILE>){
        if ( m/^$word$/ ){
          print "\tFound $word in $directory/$file\n";
          close (FILE);
	  return "1";
        }
      } 
    } else {
      print "$directory/$file does not exist:\t$!\n";
    }
  } else {
      print "$directory does not exist:\t$!\n";
      next;
  }       
  close (FILE);
  return  0; 
}  
##########################################################
sub Add_Word {
  my $word= shift;
  my $file= shift;
  my $directory = shift;

  print "The word $word was not found, should I add it (Y/N):\t";
  my $add_word=<STDIN>;
  if ( $add_word=~ m/^y$/i ){
    print color("blue"),"\tAre you sure you want to add $word to $directory/$file (Y/N):\t ",color("reset");
    my $sure_add_word=<STDIN>;
    if ( $sure_add_word =~ m/^y$/i ){
      print color("yellow"),"\t\tYour vocabulary is growing!... OK, Adding word.",color("reset"),"\n";
    } else { return; }
  } else { return; }
  
  open (ADD, ">>$directory/$file") or die "Could not open $directory/$file:\t$!\n"; 
  print ADD "$word\n";
  close (ADD);
  return;
}
##########################################################
sub Remove_Word {  
  my $word= shift;
  my $file= shift;
  my $directory = shift;

  print "Should I remove the word (Y/N):\t";
  my $ok_remove_word=<STDIN>;
  if (  $ok_remove_word=~ m/^y$/i ){
    print color("blue"),"\tAre you sure you want to remove $word from $directory/$file (Y/N):\t ",color("reset");
    my $sure_remove_word=<STDIN>;
    if (  $sure_remove_word =~ m/^y$/i ){
      print color("yellow"),"\t\tYour vocabulary is already pretty small!... OK, I'll do it.",color("reset"),"\n";
    } else { return; }
  } else { return; }
  
  # Perl Cookbook Recipe 7.8 Modify a File in Place with a Temp File
  #  Read from original file, write change to temp file, and then rename temp to original
  #
  my $old="$directory/$file";
  my $new="$directory/$file.new";
  open (OLD, "< $old") or die "can't read $old:\t$!\n";
  open (NEW, "> $new")or die "can't write $new:\t$!\n";
  while (<OLD>){
    # print all lines of the file except the one with our word
    if ( ! m/^$word$/ ){
      print NEW "$_";
    }
  }
  close (OLD);
  close (NEW);
  rename ($new, $old) or die "can't rename $new to $old:\t$!\n";
  #
  # Remove file if empty
  #
  if ( -z "$directory/$file" ){
    print color("red"),"File is empty and will be removed",color("reset"),"\n";
    unlink ( "$directory/$file" ) or die "Could not remove $directory/$file:\t$!" ;
  }	  
}          
##########################################################
