#!/bin/sh
## This file grabs a list of all #includes from the given C/C++ file.
## Works *recursive*!
##

DEPENDS=''
CHECKED=''


## Checks whether the given dependency is already known.
##
check_dependency() {
  for DEPENDENCYFILE in $DEPENDS; do
    if [ "$DEPENDENCYFILE" = "$1" ]; then
      return 1
    fi
  done
  return 0
}


## Checks whether the given file has already been scanned for dependencies.
##
check_checked() {
  for CHECKEDFILE in $CHECKED; do
    if [ "$CHECKEDFILE" = "$1" ]; then
      return 1
    fi
  done
  return 0
}


## Recursive function grabbing all includes of the given file.
##
get_depends() {
  BASEPATH=`echo $1 | sed 's/\/*[^\/]*$//'`
  # Grab all dependencies of the given file.
  NEW_DEPENDS=`egrep -o "^# *include  *\".*\"" $1 | sed 's/# *include *"\(.*\)"/\1/'`
  for FILE in $NEW_DEPENDS; do
    #echo Found dependency $FILE.
    # If the dependency is not already known, append it to the list.
    check_dependency "$BASEPATH/$FILE"
    if [ $? -eq 0 ]; then
      #echo Appended new dependency $BASEPATH/$FILE.
      DEPENDS=`echo $DEPENDS $BASEPATH/$FILE`
    fi
  done
  
  # Now, check the dependencies of the found files (recursive).
  for RECURSIVEFILE in $DEPENDS; do
    #echo Checking dependency $RECURSIVEFILE.
    # If the file has not already been checked before, do it now.
    check_checked "$RECURSIVEFILE"
    if [ $? -eq 0 ]; then
      #echo Checking valid dependency $RECURSIVEFILE.
      CHECKED="$CHECKED $RECURSIVEFILE"
      get_depends $RECURSIVEFILE
    fi
  done
}

get_depends $1
echo $DEPENDS
