#!/bin/bash 
while getopts "i:n:"  OPTION 2>/dev/null  
  do
  case $OPTION in
  i) arg1="$OPTARG";;
  n) fw_name="$OPTARG";;
  \?) err="1" ;;
  :)  err= "1" ;; 
      esac
  done  
  
cp $fw_name autogen_tmp/tmp_fw

  sed -e "s/__indvar__/$arg1/g" autogen_tmp/tmp_fw | sed -e "s/mbank_a/MBANK_A/g" | sed -e "s/mbank_b/MBANK_B/g" |sed -e "s/mbank_c/MBANK_C/g" | sed -e "s/mbank_d/MBANK_D/g" | sed -e "s/#\(._MBANK_.\), /\1/g" > $fw_name
  echo "" > $fw_name+mem
  egrep -o "(L)<.*><.*>" $fw_name >$fw_name+mem #
  echo "S">>$fw_name+mem
  egrep -o "(S)<.*><.*>" $fw_name >>$fw_name+mem #
  
cat $fw_name > $fw_name+prior
  l_switch=0
  n_switch=0
  pro_found=""
  ep_found=""
  echo "">autogen_tmp/tmp_fw
  while read line
      do  
          pro_found=`echo $line | egrep -o "(L)<.*>"`
          ep_found=`echo $line | egrep -o "(S)<.*>"`
          
          if [ -n "$ep_found" ]
              then
              n_switch=1
          fi
          
          if [ -n "$pro_found" ]
              then              
              if [ $l_switch -eq 0 ] 
                  then
                    l_switch=1                    
              fi                                
          fi  
          if [ -z "$pro_found" ] 
              then
              if [ $l_switch -eq 1 ]
                  then 
                  if [ $n_switch -eq 0 ] 
                        then
                          echo "                "$line >> autogen_tmp/tmp_fw
                  fi
              fi
          fi
              
       
          pro_found=""
      done < $fw_name
  fw_name_inc=$fw_name
 fw_name_inc=`echo $fw_name_inc | sed -e "s/autogen_tmp\/\(.*\)\.c/\1/g"` 
echo "" > autogen_tmp/$fw_name_inc\_inc_def.h
 for x in $( egrep -o "(S|L)_MBANK_.* " < $fw_name )
  do
   x="#define "${x}" 1"
   echo $x >>autogen_tmp/$fw_name_inc\_inc_def.h
  done 

 echo "#include \"${fw_name_inc}_inc_def.h\"" > $fw_name
 echo "#include \"${fw_name_inc}_linc_def.h\"" >> $fw_name
  cat autogen_tmp/link/prolog >> $fw_name 
  cat autogen_tmp/tmp_fw >> $fw_name
  cat autogen_tmp/link/epilog >> $fw_name
  ep_found=""
  ep_found=`egrep -o "pb2dfu_set_inc" $fw_name`
  if [ -z "$ep_found" ] 
      then      
          rm autogen_tmp/tmp_fw
          rm $fw_name
          exit 1
  fi
      
  exit 0
  
