#!/bin/bash

process() {
   for proc in "${processed[@]}"
   do [ "$proc" == "$1" ] && return
   done
   for need in `cat "$1" | grep --text '//#needs ' | sed 's,//#needs ,,'`
   do process $need.c "$2"
   done
   "$2" "$1"
   processed=("${processed[@]}" "$1")
   echo "$1" >> order.txt
}

do_all() {
if [ -e order.txt ]
then
   for i in `cat order.txt`
   do "$1" "$i"
   done
else
   processed=( )
   for i in *.c
   do process "$i" "$1"
   done
fi
}

if [ "$1" = "Prototypes.h" ]
then
   
   new="Prototypes.h.new"
   old="Prototypes.h"

   ################################
   echo -n "Function prototypes..."
   ################################
   
   echo "#ifndef Prototypes_HEADER" > "$new"
   echo "#define Prototypes_HEADER" >> "$new"
   echo >> "$new"
   echo '#define _GNU_SOURCE' >> "$new"
   echo '#include <stdbool.h>' >> "$new"
   echo '#include <stdio.h>' >> "$new"
   echo '#include <string.h>' >> "$new"
   echo '#include <unistd.h>' >> "$new"
   echo >> "$new"
   echo '#include "Structures.h"' >> "$new"
   echo >> "$new"
   
   includes() {
      cat "$1" | grep --text "^#include"
   }

   defines() {
      cat "$1" | grep --text "^#define Display_.*"
   }
   
   proto() {
      cat "$1" | grep -v "#include" | cpp 2> /dev/null |\
      grep --text -v "^static" | grep '^[^ ].*) {$' |\
      sed 's,) {$,);,;s,inline,,' >> "$new"
   }
   
   {
   if [ `ls *.c | wc -l` != `cat order.txt | wc -l` ]
   then rm -f order.txt
   fi
   } &> /dev/null
   
   do_all includes | sort -u | tac >> "$new"
   do_all proto
   echo "#if HAVE_CURSES" >> "$new"
   do_all defines >> "$new"
   echo "#endif" >> "$new"
   
   echo >> "$new"
   echo '#include <stdlib.h>' >> "$new"
   echo '#include "debug.h"' >> "$new"
   echo '#include <assert.h>' >> "$new"
   echo >> "$new"
   echo "#endif" >> "$new"

else
   
   new="Structures.h.new"
   old="Structures.h"

   #######################
   echo -n "Structures..."
   #######################
   
   echo "#ifndef Structures_HEADER" > "$new"
   echo "#define Structures_HEADER" >> "$new"
   echo "#include \"config.h\"" >> "$new"
   echo >> "$new"
   
   cat *.c | awk '
      BEGIN {
         reading=0
      }
      /\/*{/ {
         reading=1
      }
      /}*\// {
         reading=0
      }
      /^struct .* {$/ {
         if (reading)
            print "typedef struct " $2 " " substr($2, 1, length($2)-1) ";"
      }
   ' >> "$new"
   
   struct() {
   cat "$1" | awk '
      BEGIN {
         writing=0
      }
      /\/\*{/ {
         writing=1
      }
      /}\*\// {
         writing=0
      }
      {
         if (writing==1)
            writing=2
         else if (writing == 2)
            print
      }
   ' >> "$new"
   }
   
   do_all struct
   
   echo "#endif" >> "$new"
   
fi

####
echo
####

if ! diff -q "$new" "$old"
then mv "$new" "$old"
fi
