#!/bin/bash

# If not arguments are specified, exit
if [ $# -eq 0 ]
then
   echo 'No arguments specified'
   exit 0
fi

if [ $1 != "-all" ]     # is the first argument -all ?
then
   for keyword in $@
   do
      # look for:
      #     files contain matches (-l)
      #     ignore case (-i)
      #     look for whole words (-w)
      # ... isn't grep great!
      matches=$(grep -ilw "$keyword" tweet_*.txt)

      # copy the matching files to a new directory
      # -p so that mkdir does not complain if a directory exists already
      mkdir -p $keyword

      # if there are no matches, skip.
      if [ "$matches" = "" ] ; then continue ; fi
      cp $matches $keyword
   done
else
   # -all argument specified
   # Check to make sure there are arguments after -all
   if [ $# -eq 1 ]
   then
      echo 'No keywords specified with -all'
      exit 0
   fi

   # Get all the arguments starting with index 2
   keywords="${@:2}"

   # Create a directory for the matching tweets
   new_dir=${keywords// /_}   # this string in $keywords and replaces spaces with _
   mkdir -p $new_dir

   # This variable will contain the names of the files matching the keywords
   # being searched for. In the beginning, the file will have the names of all
   # the tweet files. We will iterate over all the keywords, and in each
   # iteration we will throw out the files not containing that keyword. By the
   # end of the last iteration, we will only have the names of files that
   # contain all keywords.
   matches=tweet_*.txt

   # Iterate through each of the keywords and narrow down the matches
   for keyword in $keywords
   do
      matches=$(grep -ilw "$keyword" $matches)
      # if there are no more matches, stop.
      if [ "$matches" = "" ] ; then exit 0 ; fi
   done

   # Copy the matches to the new directory
   cp $matches $new_dir
fi