#!/bin/bash

# This is a quick script I used to check the length of a cfa file post-
# preprocessing. It takes compilation flags and strips out ones that might
# cause problems, adds the -E flag and passes all of them to gcc.
#
# To check the standard library go to a target's src directory and enter:
# > make CFA=expanded-line-count.sh
#
# Output is placed in:
OUTPUT_FILE=std-lib-wc.txt

has_quote() (echo "$1" | grep -q '"')

filter_args() (
    for arg; do
        case "$arg" in
        (-I*|-D*|-W*|-f*)
            if has_quote "$arg"; then continue; fi
            echo "$arg"
            ;;
        (-*|*.Tpo|*.Po|*.lo|*.o)
            continue
            ;;
        (*)
            if has_quote "$arg"; then continue; fi
            echo "$arg"
            ;;
        esac
    done
)
ARGS=($(filter_args "$@"))

find_name() (
    next=false
    for arg; do
        if $next; then
            echo $arg
            break
        elif [ "-o" == "$arg" ]; then
            next=true
        fi
    done
)
FILE_NAME="$(find_name "$@")"

deps_file() (sed -e "s|.libs/|.deps/|" -e "s|.o$|.Tpo|" <<< $1)

LINES=$(~/cfa-cc/driver/cfa -E "${ARGS[@]}" | wc -l)
touch $(deps_file $FILE_NAME)

echo "Record of pre-processed file lengths:" >$OUTPUT_FILE
echo $FILE_NAME=$LINES | tee -a $OUTPUT_FILE
