#encoding: utf-8

#! /usr/bin/python

'''

 File      : ChipON_IDE_KF32prj_makefile.py

 Author    : Gaojianzheng

 E-Mail    : jianzhengg@163.com

'''

import os
import os.path
import shutil
import sys
import getopt
#sys.exit(0);
######################################################################################################################### annotate
#
#	use python to output makefile

#	@Project_Path 		the path of project 
#	@Project_Name 		project name
#	@Project_Mode		output path like Debug Release
#       @Project_Chip           chip to pass to toolchain
#	@Project_LD_Script	the script file of porject for link


#	@Tool_Path	        main path of toolchain
#	@Tool_Select 	        versel like ccr1_issue or ccr1_issue_v0



# 	@CC			wiht start of @ will not output the command itself like @kf32-gcc
# 	@CXX			now start of @ will output the command itself like kf32-g++

#	@ClassC_Flag		gcc input option
#	@ClassCPP_Flag		g++ input optin
#	@other 			the same describe
#       FileType                ['.c','.cpp','.C', '.asm','.s', '.h','.inc']
######################################################################################################################### BASE CONFIG
#path  with \\ or /  ../ ./  is ok
Project_Path = '/home/chipon/KungFu32IDE/workspace32'
Project_Name = '1233'
Project_Mode = 'Release'
Project_Chip = 'KF32F350MQV'
Chip_Kernel_lib = 'crtv1'   # like A150 is crtv1,and like A156 is crtv2 ,and so on

Tool_Path = '/home/chipon/ChipONCC32'
Tool_Select = 'ccr1_issue'
# '/home/chipon/ChipONCC32/ccr1_issue/scripting/KF32F350MQV.ld'
Project_LD_Script_Default = os.path.join(Tool_Path,Tool_Select,'scripting',Project_Chip+'.ld')
# '/home/chipon/KungFu32IDE/workspace32/1233/KF32F350MQV.ld'
Project_LD_Script_Default2 = os.path.join(Project_Path, Project_Name,   Project_Chip+'.ld')
#  pass to ld to out the elf 
Project_LD_Script =Project_LD_Script_Default   #can re-evaluate with string or var,like  Project_LD_Script_Default2 ,the ld which under the project 


#the rpath not scanf to find file. path like  abc  abc/arch  abc/arch/chipwho, you may need add element to exclude files under  other arch ,like arm
filter_rPath=["Release","RELEASE","Debug","DEBUG",'.settings','.cproject','.project','.Start_IDE.exe','.history','addyourselfpointinthis']
########################################################################################################################### TOOL

CC	= '@kf32-gcc'
CXX	= '@kf32-g++'
AR	= '@kf32-ar'
RANLIB	= 'kf32-ranlib'
STRIP	= 'kf32-strip'
NM	= 'kf32-nm'

AS	= '@kf32-as'
LD	= '@kf32-ld'   
OBJDUMP = '@kf32-objdump'
OBJCOPY = '@kf32-objcopy'


OutToolLog2File='false'
OutToolLog2File='true'       # use # to comment it to false

########################################################################################################################## default option
pre_build_command='echo \'this a demo to do first\''     # use ; or && separator the command  like  echo '123' && echo '456'
post_build_command='echo \'this a demoe to do after\''     #

MAKE_Flag='-k'                     #with -k do all or with no -k stop with first error
MAKE_JOBS='-j4'                    #default , can be -j2 -j4 j8 ,or empty


ClassC_Flag =' '
ClassC_Flag+= '-gdwarf-3 -O2' + ' '  #enable debug and optimize
ClassC_Flag+= ' -save-temps=obj'+ ' '  #keep asm and i file

ClassC_Flag+= '-MMD '+ ' '          #out depand file
ClassC_Flag+= ' -c' + ' '           #not link
ClassC_Flag+= '-fno-builtin-printf -fno-builtin-fprintf -fno-builtin-fputs '+ ' '
ClassC_Flag+= '-funsigned-char '+ ' '
ClassC_Flag+= '-fsigned-bitfields   -Wno-packed-bitfield-compat ' + ' '
ClassC_Flag+= '-std=gnu99' + ' '
ClassC_Flag+= '-ffunction-sections -fdata-sections' + ' '#need for feature
ClassC_Flag+= '-Wa,--kf32-arch=kf32r ' + ' '    #need for inline asm
   
                   
ClassCPP_Flag =' '
ClassCPP_Flag+= '-save-temps=obj'+ ' '  #keep asm and i file
ClassCPP_Flag ='-gdwarf-3  -O2' + ' '
ClassCPP_Flag+= '-MMD '+ ' '          #out depand file
ClassCPP_Flag+= '-c' + ' '           #not link
ClassCPP_Flag+= '-ffunction-sections -fdata-sections' + ' '#need for feature
ClassCPP_Flag+= '-Wa,--kf32-arch=kf32r' + ' '


ClassA_Flag='-gstabs+  --kf32-arch=kf32r '+ ' '

ClassLink_Flag=' '                   
ClassLink_Flag+='-lIQmath-R1 -lSeriesDIServices -lmath -lio -lstring -lstdlib -lctype -l'+ Chip_Kernel_lib +' '
#ClassLink_Flag+='--kf32-autoihex '+' '      # out ihex from elf by objcopy
ClassLink_Flag+='--gc-sections'+' '         # no use no allot
ClassLink_Flag+='--kf32-arch=kf32r'+' '     # arch 
ClassLink_Flag+='--kf32-nodisassemble'+' '  # not  ,disassemble by objdump
#ClassLink_Flag += '--with-checksum-fill=0xFF'+' '
#ClassLink_Flag += '-with-checksum1=CRC-32'+' '
#ClassLink_Flag += '--with-checksum-address1=0'+' '
#ClassLink_Flag += '--with-checksum-size1=0x120'+' '
#ClassLink_Flag += '--with-checksum-out-address1=0x100'+' '
ClassLink_Flag+='\\\n '      
#++++++++++++++++++++++++++++++++++++++++++
# binary srec ihex   wiht out s19 and bin  ,hex by link
ClassOjbcopy_Flag=''
              

ClassObjdump_Flag=' '
ClassObjdump_Flag+='-S -l'+' '
ClassObjdump_Flag+='--section=.text'+' '		#default code in flash
ClassObjdump_Flag+='--section=.data'+' '		#default idata in ram
ClassObjdump_Flag+='--section=.bss '+' '		#default bssdata in ram
ClassObjdump_Flag+='--kf32-arch=kf32r'+' '	        # arch

######################################################################################################################### function 
def tomakefilString(rPathfile):
    toreturenstring=''
    length =len(rPathfile)
    counter = 0
#    a = "Hello"
#    b = "Python" 
#    print( 'a + b out:', a + b)

    while counter<length:
#        print (rPathfile[counter],"\n")
        if rPathfile[counter]==' ':
            toreturenstring+='\\ '
        else:
            #if rPathfile[counter]=='(':
            #    toreturenstring+='\('
            #else:
            #    if rPathfile[counter]==')':
            #        toreturenstring+='\)'
            #    else:
            #       toreturenstring+=rPathfile[counter]
            if rPathfile[counter]=='\\':
                if rPathfile[counter+1]=='\\':
                    toreturenstring+='/'
                    counter +=1
                else:
                    toreturenstring+='/'
            else:
                toreturenstring+=rPathfile[counter]
        counter += 1
    return toreturenstring

def pRootPath(rPathfile):
    toreturenstring=''
    length =len(rPathfile)
    counter = 0


    while counter<length:
#        print (rPathfile[counter],"\n")
        if rPathfile[counter]!='/':
            toreturenstring+=rPathfile[counter]
        else:
           break;
        counter += 1
    return toreturenstring
######################################################################################################################### function 
def genMakefileStr(dir,ClassC_Flag,ClassCPP_Flag,ClassA_Flag,ClassLink_Flag,ClassOjbcopy_Flag,ClassObjdump_Flag):

    makefileString = ''
    sourcesString=''
    objectsString=''
    subdirString=''
###################################################################################################### base tool option
    ClassC_Flag+= '-Wa,-I"' +  Tool_Path + '/include"' + ' '
    ClassC_Flag+= '-D' + Project_Chip +' ' + '-D__'+ Project_Mode + '__ '
    
    ClassC_Flag +=' -I"'+ os.path.join(Tool_Path,'include') +'" '
    ClassC_Flag +=' -I"'+ os.path.join(Tool_Path,'include','Sys') +'" '

    ClassCPP_Flag +=' -I"'+  os.path.join(Tool_Path,'include') +'" '
    ClassCPP_Flag +=' -I"'+  os.path.join(Tool_Path,'include','Sys') +'" '

    ClassA_Flag +='-I"'+ os.path.join(Tool_Path,'include') +'" '

    ClassLink_Flag+=' -L"'+os.path.join(Tool_Path,Tool_Select,'lib') +'" '
    ClassLink_Flag+=' -L"'+os.path.join(Project_Path,Project_Name)   +'" '
    ClassLink_Flag+='\\\n ' 
    ClassLink_Flag+=' -T"'+os.path.realpath(Project_LD_Script)      +'" '
###################################################################################################### makefile system
    makefileString+='################################################################################' + '\n'
    makefileString+='# auto '+ '\n'
    makefileString+='################################################################################' + '\n\n'
    makefileString+= '-include ../makefile.init'+ '\n\n'
    makefileString+= 'RM := rm -rf' + '\n\n'

    makefileString+='VPATH = ../' + '\n'
    makefileString+='# All of the sources participating in the build are defined here' + '\n'
    makefileString+='-include sc_variable.mk' + '\n'
    makefileString+='-include sources.mk' + '\n'

    makefileString+='-include subdir.mk' + '\n'
###################################################################################################### makefile system
    sourcesString=''
    sourcesString+='################################################################################' + '\n'
    sourcesString+='# auto '+ '\n'
    sourcesString+='################################################################################' + '\n\n'
    sourcesString+='O_SRCS := ' + '\n'
    sourcesString+='C_SRCS := ' + '\n'
    sourcesString+='S_UPPER_SRCS := ' + '\n'
    sourcesString+='S_SRCS := ' + '\n'
    sourcesString+='OBJ_SRCS := ' + '\n'
    sourcesString+='ASM_SRCS := ' + '\n'
    sourcesString+='ASM_UPPER_SRCS := ' + '\n\n'

    sourcesString+='C_DEPS := ' + '\n'
    sourcesString+='LD_SRCS := ' + '\n\n'

    sourcesString+='OBJS := ' + '\n'
    sourcesString+='OBJDUMP_LIST := ' + '\n'
    sourcesString+='OBJCOPY_TARGET := ' + '\n'
    sourcesString+='EXECUTABLES := ' + '\n\n'

    sourcesString+='# Every subdirectory with source files must be described here' + '\n'
    sourcesString+='SUBDIRS := \\'+'\n'
###################################################################################################### makefile system

    objectsString=''
    objectsString+='################################################################################' + '\n'
    objectsString+='# auto '+ '\n'
    objectsString+='################################################################################' + '\n\n'
    objectsString+='USER_OBJS :=' + '\n\n'
    objectsString+='LIBS :=' + '\n\n'

###################################################################################################### makefile system

    subdirString+='################################################################################' + '\n'
    subdirString+='# auto '+ '\n'
    subdirString+='################################################################################' + '\n\n'
    subdirString+='# Add inputs and outputs from these tool invocations to the build variables' + '\n\n' 
###################################################################################################### init search path

    os.chdir(dir)
    nowCurPath = os.getcwd()

    LastDealPath='x'
    
    cFirstPath='-'
    cppFirstPath='-'
    CFirstPath='-'
    asmFirstPath='-'
    sFirstPath='-'
    
    cHeadFirstPath='-'
    cppHeadFirstPath='-'
    asmHeadFirstPath='-'
#############################111111111111111111111111111
    One_subdirString=''
    ALL_subdirString=''
    for root,dirs,files in os.walk(dir):
        ALL_subdirString=One_subdirString+ALL_subdirString
        One_subdirString=''
#############################222222222222222222222222222 root like D:/workspace32/uselibtest\Release\
        for file in files:
#############################33333333333333333333333333 file like \kf32ls_basic_qei.i
                #--------------------------------------------
#                print(os.path.join(root,file))
#                print(os.path.join(file))
#                filterPath = os.path.dirname(rPath)
                rPathfile=os.path.relpath(os.path.join(root,file),nowCurPath)   #  print(rPathfile)
                rPath=os.path.dirname(rPathfile)  # for var SUBDIRS not with ../
                if rPath == '':
                    rPath='.'
                else:
                    rPath=''+rPath
                rPath=tomakefilString(rPath)   # only unix / not windows \ for target tool .like make
#                print(rPath)
                #--------------------------------------------
                if rPath in filter_rPath:
                    continue;            
                if rPath ==Project_Mode:
                    continue
                
                stratpath,withafeterpath =os.path.split(rPath)
                
                if stratpath== 'Debug':
                   continue
                if stratpath =='Release':
                    continue
                if stratpath== './Debug':
                   continue
                if stratpath =='./Release':
                    continue
                if stratpath ==Project_Mode:
                    continue
                if stratpath =="./"+Project_Mode:
                    continue    
                #--------------------------------------------
                name,extension = os.path.splitext(file)
                #--------------------------------------------
                if extension!='':
                    if LastDealPath !=rPath:
                        sourcesString+=rPath+' \\\n'
                        if not os.path.exists(os.path.join(Project_Mode,rPath)):
                            os.makedirs(os.path.join(Project_Mode,rPath))
#                        if rPath!='.':
#                            makefileString+='-include '+rPath+'/subdir.mk' + '\n'
                        cFirstPath='-'
                        cppFirstPath='-'
                        CFirstPath='-'
                        asmFirstPath='-'
                        sFirstPath='-'


                        cHeadFirstPath='-'
                        cppHeadFirstPath='-'
                        asmHeadFirstPath='-'
                        LastDealPath = rPath
                        
                #--------------------------------------------
                if extension == '.c':
                    nowrPath = rPath
                    if nowrPath=='.':
                        nowrPath=''
                    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                    if LastDealPath !=cFirstPath:

                        One_subdirString+='# Each subdirectory must supply rules for building sources it contributes'+  '\n'
                        if nowrPath=='':
                            One_subdirString+= nowrPath+'%.o: ..'+nowrPath+'/%.c'+  '\n'
                        else:
                            One_subdirString+= nowrPath+'/%.o: ../'+nowrPath+'/%.c'+  '\n'
                        One_subdirString+='\t@echo \'Building file: $<\'' + '\n'
                        One_subdirString+='#	@echo \'Invoking: ChipON C Compiler\'' + '\n'                        
                        One_subdirString+='\t'+CC +'\t'+ '$(ClassC_Flag)' + ' $< -o "$@"' + '\n'
                        One_subdirString+='\t@echo \'Finished building: $<\'' + '\n\n\n'
                        cFirstPath = LastDealPath
                    if nowrPath=='':
                        One_subdirString+='C_SRCS += '+ os.path.join('..'+nowrPath+'/'+file) + '\n'
                        One_subdirString+='OBJS   +=   '+ os.path.join('.'+nowrPath+'/'+name+'.o') + '\n'
                        One_subdirString+='C_DEPS +=   '+ os.path.join('.'+nowrPath+'/'+name+'.d') + '\n\n'   
                    else:
                        One_subdirString+='C_SRCS += '+ os.path.join('../'+nowrPath+'/'+file) + '\n'
                        One_subdirString+='OBJS   +=   '+ os.path.join('./'+nowrPath+'/'+name+'.o') + '\n'
                        One_subdirString+='C_DEPS +=   '+ os.path.join('./'+nowrPath+'/'+name+'.d') + '\n\n'                    
                    #--------------------------------------------
                if extension == '.cpp':
                    nowrPath = rPath
                    if nowrPath=='.':
                        nowrPath=''
                    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                    if LastDealPath !=cppFirstPath:
                        One_subdirString+='# Each subdirectory must supply rules for building sources it contributes'+  '\n'
                        if nowrPath=='':
                            One_subdirString+= nowrPath+'%.o: ..'+nowrPath+'/%.cpp'+  '\n'
                        else:
                            One_subdirString+= nowrPath+'/%.o: ../'+nowrPath+'/%.cpp'+  '\n'
                        One_subdirString+='\t@echo \'Building file: $<\'' + '\n'
                        One_subdirString+='#	@echo \'Invoking: ChipON C Compiler\'' + '\n'

						#subdirString+='\t@mkdir -p "_static_code_analysis"' + '\n'
                        One_subdirString+='\t'+CXX +'\t'+ '$(ClassCPP_Flag)' + ' $< -o "$@"' + '\n'
                        One_subdirString+='\t#@echo \'Finished building: $<\'' + '\n\n\n'
                        cppFirstPath = LastDealPath
                    if nowrPath=='':
                        subdirString+='C_SRCS += '+ os.path.join('..'+nowrPath+'/'+file) + '\n'
                        subdirString+='OBJS   +=   '+ os.path.join('.'+nowrPath+'/'+name+'.o') + '\n'
                        subdirString+='C_DEPS +=   '+ os.path.join('.'+nowrPath+'/'+name+'.d') + '\n\n'   
                    else:
                        subdirString+='C_SRCS += '+ os.path.join('../'+nowrPath+'/'+file) + '\n'
                        subdirString+='OBJS   +=   '+ os.path.join('./'+nowrPath+'/'+name+'.o') + '\n'
                        subdirString+='C_DEPS +=   '+ os.path.join('./'+nowrPath+'/'+name+'.d') + '\n\n'   
                    #--------------------------------------------
                if extension == '.C':
                    nowrPath = rPath
                    if nowrPath=='.':
                        nowrPath=''
                   #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                    if LastDealPath !=CFirstPath:
                        One_subdirString+='# Each subdirectory must supply rules for building sources it contributes'+  '\n'
                        if nowrPath=='':
                            One_subdirString+= nowrPath+'%.o: ..'+nowrPath+'/%.C'+  '\n'
                        else:
                            One_subdirString+= nowrPath+'/%.o: ../'+nowrPath+'/%.C'+  '\n'
                        One_subdirString+='\t@echo \'Building file: $<\'' + '\n'
                        One_subdirString+='#	@echo \'Invoking: ChipON C Compiler\'' + '\n'
                        #One_subdirString+='\t@mkdir -p "_static_code_analysis"' + '\n'
                        One_subdirString+='\t'+CXX +'\t'+ '$(ClassCPP_Flag)'  + ' $< -o "$@"' + '\n'
                        One_subdirString+='\t#@echo \'Finished building: $<\'' + '\n\n\n'
                        CFirstPath = LastDealPath
                    if nowrPath=='':
                        One_subdirString+='C_SRCS += '+ os.path.join('..'+nowrPath+'/'+file) + '\n'
                        One_subdirString+='OBJS   +=   '+ os.path.join('.'+nowrPath+'/'+name+'.o') + '\n'
                        One_subdirString+='C_DEPS +=   '+ os.path.join('.'+nowrPath+'/'+name+'.d') + '\n\n'   
                    else:
                        One_subdirString+='C_SRCS += '+ os.path.join('../'+nowrPath+'/'+file) + '\n'
                        One_subdirString+='OBJS   +=   '+ os.path.join('./'+nowrPath+'/'+name+'.o') + '\n'
                        One_subdirString+='C_DEPS +=   '+ os.path.join('./'+nowrPath+'/'+name+'.d') + '\n\n'   
                    #--------------------------------------------
                if extension == '.asm':
                    nowrPath = rPath
                    if nowrPath == '.':
                        nowrPath=''
                   #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                    if LastDealPath !=asmFirstPath:
                        One_subdirString+='# Each subdirectory must supply rules for building sources it contributes'+  '\n'
                        if nowrPath=='':
                            One_subdirString+= nowrPath+'%.o: ..'+nowrPath+'/%.asm'+  '\n'
                        else:
                            One_subdirString+= nowrPath+'/%.o: ../'+nowrPath+'/%.asm'+  '\n'
                        One_subdirString+='\t@echo \'Building file: $<\'' + '\n'
                        One_subdirString+='#	@echo \'Invoking: ChipON C Compiler\'' + '\n'
                        #One_subdirString+='\t@mkdir -p "_static_code_analysis"' + '\n'
                        One_subdirString+='\t'+AS +'\t'+ ClassCPP_Flag  + ' $< -o "$@"' + '\n'
                        One_subdirString+='\t#@echo \'Finished building: $<\'' + '\n\n\n'
                        asmFirstPath = LastDealPath
                    if nowrPath=='':
                        One_subdirString+='ASM_SRCS += '+ os.path.join('..'+nowrPath+'/'+file) + '\n'
                        One_subdirString+='OBJS   +=   '+ os.path.join('.'+nowrPath+'/'+name+'.o') + '\n'
                        One_subdirString+='C_DEPS +=   '+ os.path.join('.'+nowrPath+'/'+name+'.d') + '\n\n'   
                    else:
                        One_subdirString+='ASM_SRCS += '+ os.path.join('../',nowrPath,file) + '\n'
                        One_subdirString+='OBJS   +=   '+ os.path.join('./',nowrPath+'/'+name+'.o') + '\n'
                        One_subdirString+='C_DEPS +=   '+ os.path.join('./',nowrPath+'/'+name+'.d') + '\n\n'   
                    #--------------------------------------------
                if extension == '.s':                    
                    nowrPath = rPath
                    if nowrPath=='.':
                        nowrPath=''
                   #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                    if LastDealPath !=sFirstPath:
                        One_subdirString+='# Each subdirectory must supply rules for building sources it contributes'+  '\n'
                        if nowrPath=='':
                            One_subdirString+= nowrPath+'%.o: ..'+nowrPath+'/%.s'+  '\n'
                        else:
                            One_subdirString+= nowrPath+'/%.o: ../'+nowrPath+'/%.s'+  '\n'
                        One_subdirString+='\t@echo \'Building file: $<\'' + '\n'
                        One_subdirString+='#	@echo \'Invoking: ChipON C Compiler\'' + '\n'
                        #One_subdirString+='\t@mkdir -p "_static_code_analysis"' + '\n'
                        One_subdirString+='\t'+AS +'\t'+ ClassCPP_Flag  + '$< -o "$@"' + '\n'
                        One_subdirString+='\t#@echo \'Finished building: $<\'' + '\n\n\n'
                        sFirstPath = LastDealPath
                    if nowrPath=='':
                        One_subdirString+='S_SRCS += '+ os.path.join('..'+nowrPath+'/'+file) + '\n'
                        One_subdirString+='OBJS   +=   '+ os.path.join('.'+nowrPath+'/'+name+'.o') + '\n'
                        One_subdirString+='C_DEPS +=   '+ os.path.join('.'+nowrPath+'/'+name+'.d') + '\n\n'   
                    else:
                        One_subdirString+='S_SRCS += '+ os.path.join('../'+nowrPath+'/'+file) + '\n'
                        One_subdirString+='OBJS   +=   '+ os.path.join('./',nowrPath+'/'+name+'.o') + '\n'
                        One_subdirString+='C_DEPS +=   '+ os.path.join('./',nowrPath+'/'+name+'.d') + '\n\n'   
                    #--------------------------------------------
                if extension == '.inc':
                    if LastDealPath !=asmHeadFirstPath:
                        ClassA_Flag +='-I"'+ os.path.dirname(os.path.join(root,file))+'" '
                        asmHeadFirstPath = LastDealPath
                               
                    #--------------------------------------------
                if extension == '.h':
                   if LastDealPath !=cHeadFirstPath:
                        ClassC_Flag +=' -I"'+ os.path.dirname(os.path.join(root,file)) +'" '
                        ClassCPP_Flag +=' -I"'+ os.path.dirname(os.path.join(root,file)) +'" '
                        cHeadFirstPath =   LastDealPath         
                    #--------------------------------------------
                #--------------------------------------------                    
                #break # only search the current directory
        continue
    ALL_subdirString=One_subdirString + ALL_subdirString
    subdirString+=ALL_subdirString
#############################222222222222222222222222222
###################################################################################################### makefile system
    makefileString+='-include objects.mk' + '\n\n'
    makefileString+='-include $(C_DEPS)' + '\n\n'

    makefileString+='-include ../makefile.defs' + '\n\n'
        
    makefileString+='# Add inputs and outputs from these tool invocations to the build variables ' + '\n'
    makefileString+='OBJCOPY_TARGET += \\' + '\n'
    makefileString+=Project_Name+'.s19 \\' + '\n\n'

    makefileString+='OBJDUMP_LIST += \\' + '\n'
    makefileString+=Project_Name+'.lst \\' + '\n\n'


    makefileString+='LD_SRCS ='+tomakefilString(Project_LD_Script) + '\n\n'  

    makefileString+='EXECUTABLES	= '+ Project_Name+'.elf' + '\n'
    makefileString+='# all target' + '\n'
    if pre_build_command!='':
        makefileString+='all: pre-build main-build' + '\n\n'
        makefileString+='# main build'+ '\n'
        makefileString+='main-build: '+Project_Name+'.elf secondary-outputs' + '\n\n'
    else:
        makefileString+='all: '+Project_Name+'.elf secondary-outputs' + '\n\n'

    makefileString+='# invok tool' + '\n'
    makefileString+=Project_Name+'.elf: $(OBJS) $(USER_RELS) $(LD_SRCS)' + '\n'
    makefileString+='	@echo \'Building target: $@\'' + '\n'
    makefileString+='#	@echo \'Invoking: ChipON Linker\'' + '\n'
    makefileString+='\t'+LD +' $(OBJS) $(USER_RELS) $(LIBS) '+ '$(ClassLink_Flag)' + ' -o  \"'+Project_Name+'.elf\" -Map \"'+Project_Name+'.map\"' + '\n'
    makefileString+='	@echo \'Finished building target: $@\'' + '\n'
    makefileString+='#	@echo \' \'' + '\n'
    makefileString+='' + '\n'
    
    makefileString+=''+Project_Name+'.s19: $(OBJS) $(EXECUTABLES) $(USER_RELS) $(LD_SRCS)' + '\n'
    makefileString+='#	@echo \'Invoking: ChipON ObjCopy\'' + '\n'
    makefileString+='\t'+OBJCOPY+' $(ClassObjcopy_Flag)'+  '-O ihex '   +'\"' + Project_Name    +'.elf\"   \"'      +   Project_Name+'.hex\"' + '\n'
    makefileString+='\t'+OBJCOPY+' $(ClassObjcopy_Flag)'+  '-O srec '   +'\"' + Project_Name    +'.elf\"   \"'      +   Project_Name+'.s19\"' + '\n'
    makefileString+='\t'+OBJCOPY+' $(ClassObjcopy_Flag)' + '-O binary ' +'\"' + Project_Name    +'.elf\"   \"'      +   Project_Name+'.bin\"' + '\n'
    makefileString+='	@echo \'Finished building: $@\'' + '\n'
    makefileString+='#	@echo \' \'' + '\n'
    if post_build_command!='':
         makefileString+='\t$(MAKE) --no-print-directory post-build' + '\n'
    makefileString+='' + '\n'

    makefileString+=''+Project_Name+'.lst: $(OBJS) $(EXECUTABLES) $(USER_RELS) $(LD_SRCS)' + '\n'
    makefileString+='#	@echo \'Invoking: ChipON ObjDump\'' + '\n'
    makefileString+='\t'+OBJDUMP + ' $(ClassObjdump_Flag)'+' \"'+Project_Name+'.elf\"   > \"'+Project_Name+'.lst\"' + '\n'
    makefileString+='	@echo \'Finished building: $@\'' + '\n'
    makefileString+='#	@echo \' \'' + '\n'
    makefileString+='' + '\n'
    
    makefileString+='# other' + '\n'
    makefileString+='clean:' + '\n'
    makefileString+='	-$(RM)  $(OBJS) $(EXECUTABLES) $(C_DEPS) '+Project_Name+'.elf \'$(basename $(OBJDUMP_LIST)).lst\' \'$(basename $(OBJCOPY_TARGET)).hex\'   \'$(basename $(OBJCOPY_TARGET)).bin\'  \'$(basename $(OBJCOPY_TARGET)).s19\' \'$(basename $(OBJCOPY_TARGET)).map\'' + '\n'
    makefileString+='#	-@echo \' \'' + '\n'
    makefileString+='' + '\n'
    #wiht - means it's error can be do other
    if pre_build_command!='':
        makefileString+='pre-build:' + '\n'
        makefileString+='\t-' +pre_build_command + '\n'
        makefileString+='\t-@echo \' \'' + '\n'
        makefileString+='' + '\n'
        
    if post_build_command!='':
        makefileString+='post-build:' + '\n'
        makefileString+='\t-' +post_build_command + '\n'
        makefileString+='\t-@echo \' \'' + '\n'
        makefileString+='' + '\n'
        
    makefileString+='secondary-outputs: '+Project_Name+'.lst '+Project_Name+'.s19' + '\n'
    makefileString+='' + '\n'
    makefileString+='.PHONY: all clean dependents' + '\n'
    
    makefileString+='.SECONDARY:'
    if pre_build_command!='':
        makefileString+=' main-build pre-build '
    if post_build_command!='':
        makefileString+='post-build'   
    makefileString+='' + '\n\n'
    makefileString+='-include ../makefile.targets' + '\n'

    #print msg
###################################################################################################### makefile system
    os.chdir(os.path.join(dir,Project_Mode))
    file = open("makefile","w")
    file.write(makefileString)
    file.close()

    sourcesString+='\n'
    file = open("sources.mk","w")
    file.write(sourcesString)
    file.close()

    file = open("objects.mk","w")
    file.write(objectsString)
    file.close()

    file = open("subdir.mk","w")
    file.write(subdirString)
    file.close()

    file = open("sc_variable.mk","w")
    file.write('################################################################################' + '\n')
    file.write('# auto '+ '\n')
    file.write('################################################################################' + '\n\n')
    file.write('ClassC_Flag:=\t'+ ''+ ClassC_Flag + '' +'\n\n')
    file.write('ClassCPP_Flag:=\t'+ ''+  ClassCPP_Flag + '' + '\n\n')
    file.write('ClassA_Flag:=\t'+ ''+ ClassA_Flag + '' +'\n\n')
    file.write('ClassLink_Flag:=\t'+  ''+ ClassLink_Flag + '' +'\n\n')
    file.write('ClassOjbcopy_Flag:=\t'+  ''+ ClassOjbcopy_Flag + '' +'\n\n')
    file.write('ClassObjdump_Flag:=\t'+  ''+ ClassObjdump_Flag + '' +'\n\n')
    file.close()
###################################################################################################### makefile system end
    return "OK"


###################################################################################################### main function to work            
if __name__ == '__main__':
###################################################################################################### can with arg to modiy base config
    if len(sys.argv)>1 :
        try:
            opts,args=getopt.getopt(sys.argv[1:],"p:n:m:c:t:s:l:",["path=","name=","mode=","chip=","toolpath=","toolsel=","ld="])                        
        except getopt.GetopError:
            print("err input")
            sys.exit()
            
        for opt,arg in opts:
            if opt in ("-p","--path"):
               Project_Path=arg
            elif opt in ("-n","--name"):
                Project_Name=arg
                
            elif opt in ("-m","--mode"):
               Project_Mode=arg
            elif opt in ("-c","--chip"):
                Project_Chip=arg

            elif opt in ("-t","--toolpath"):
                Tool_Path=arg
            elif opt in ("-s","--toolsel"):
                Tool_Select=arg

            elif opt in ("-l","--ld"):
                Project_LD_Script=arg    

            
###################################################################################################### register tool 
    print('####################################	0 start ')
    #sys.path.append(Tool_Path + Tool_Select+'/bin')  sys.path.insert(0,os.path.join(Tool_Path , Tool_Select,'./bin'))
    sys.path.insert(0,"\""+os.path.join(Tool_Path , Tool_Select,'bin')+"\"")
    sys.path.insert(1,os.path.join(Tool_Path , Tool_Select, 'kf32/bin'))
    sys.path.insert(2,os.path.join(Tool_Path , Tool_Select , 'lib/gcc/kf32/4.7.0'))
    sys.path.insert(3,os.path.join(Tool_Path , 'common') )

   
    os.environ["PATH"] = os.path.join(Tool_Path , 'common') + os.pathsep  +os.environ["PATH"]
    os.environ["PATH"] = os.path.join(Tool_Path , Tool_Select,'lib/gcc/kf32/4.7.0') + os.pathsep  +os.environ["PATH"]
    os.environ["PATH"] = os.path.join(Tool_Path , Tool_Select,'kf32/bin') + os.pathsep  +os.environ["PATH"]
    os.environ["PATH"] = os.path.join(Tool_Path , Tool_Select,'bin') + os.pathsep  +os.environ["PATH"]

    os.environ["CYGWIN"] = 'nodosfilewarning'
    #print('####################################the tool version :\n')
    #os.system( 'gmake -v')
###################################################################################################### default out file clear
    if(os.path.isfile(os.path.join(Project_Path,Project_Name,   Project_Mode+'_'+Project_Name+'.elf'))):
        os.remove( os.path.join(Project_Path,Project_Name,   Project_Mode+'_'+Project_Name+'.elf'))
    if(os.path.isfile(os.path.join(Project_Path,Project_Name,   Project_Mode+'_'+Project_Name+'.hex'))):
        os.remove( os.path.join(Project_Path,Project_Name,   Project_Mode+'_'+Project_Name+'.hex'))
       
    if(os.path.isfile(os.path.join(Project_Path,Project_Name,   Project_Mode+'_'+Project_Name+'.s19'))):
        os.remove( os.path.join(Project_Path,Project_Name,   Project_Mode+'_'+Project_Name+'.s19'))
       
    if(os.path.isfile(os.path.join(Project_Path,Project_Name,   Project_Mode+'_'+Project_Name+'.map'))):
        os.remove( os.path.join(Project_Path,Project_Name,   Project_Mode+'_'+Project_Name+'.map'))
    if(os.path.isfile(os.path.join(Project_Path,Project_Name,   Project_Mode+'_'+Project_Name+'.lst'))):
        os.remove( os.path.join(Project_Path,Project_Name,  Project_Mode+'_'+Project_Name+'.lst'))

    heremkdir = os.getcwd()
    topath=os.path.join(Project_Path,Project_Name,Project_Mode,'_static_code_analysis')
    if not os.path.exists(topath):
        os.makedirs(topath)
###################################################################################################### course 1 ,call function to out makefile
    print('####################################	1 the makefile output :\n')
    genMakefileStr(os.path.join(Project_Path,Project_Name),ClassC_Flag,ClassCPP_Flag,ClassA_Flag,ClassLink_Flag,ClassOjbcopy_Flag,ClassObjdump_Flag)
    print('Done')

        
    os.chdir(os.path.join(Project_Path,Project_Name,Project_Mode))
    heremkdir = os.getcwd()
###################################################################################################### course 2 ,call make to out file like elf
    print('####################################	2 run gmake compiler  :\n') 
    #os.system('gmake -k clean')   
    #os.system('cmd /k gmake -k all')                   #with cmd /k will not quit build env ,can look all build message
    #os.system('cmd /k gmake -k pre-build main-build')  #with all :the order is no ok
                                                        # 1>build_log.txt  2>&1 all build message to one file
    MakeCommand=''
    if pre_build_command!='':
        #MakeCommand='cmd /k gmake  '+MAKE_Flag+ ' ' + MAKE_JOBS +' pre-build main-build'
        if OutToolLog2File=='true':
            MakeCommand='gmake  '+MAKE_Flag+ ' ' + MAKE_JOBS +' pre-build main-build' + ' 1>../build_log.txt  2>&1'
        else:
            MakeCommand='gmake  '+MAKE_Flag+ ' ' + MAKE_JOBS +' pre-build main-build' 
    else:
        #MakeCommand='cmd /k gmake  '+MAKE_Flag+ ' ' + MAKE_JOBS +' all'
        if OutToolLog2File=='true':
            MakeCommand='gmake  '+MAKE_Flag+ ' ' + MAKE_JOBS +' all' + ' 1>../build_log.txt  2>&1'
        else:
            MakeCommand='gmake  '+MAKE_Flag+ ' ' + MAKE_JOBS +' all'
            
    print(MakeCommand)
    os.system(MakeCommand)
    
    topath=os.path.join(Project_Path)
    os.chdir(topath)
###################################################################################################### course 3 ,out file bak out the path under project with prefix "mode
    if(os.path.isfile(os.path.join(Project_Path,Project_Name,   Project_Mode,Project_Name+'.elf'))):
        shutil.copyfile( os.path.join(Project_Path,Project_Name,Project_Mode,Project_Name+'.elf'),os.path.join(Project_Path,Project_Name,   Project_Mode+'_'+Project_Name+'.elf'))
        print(' file elf out find')
    if(os.path.isfile(os.path.join(Project_Path,Project_Name,   Project_Mode,Project_Name+'.hex'))):
        shutil.copyfile( os.path.join(Project_Path,Project_Name,Project_Mode,Project_Name+'.hex'),os.path.join(Project_Path,Project_Name,   Project_Mode+'_'+Project_Name+'.hex'))
        print(' file hex out find')
    if(os.path.isfile(os.path.join(Project_Path,Project_Name,   Project_Mode,Project_Name+'.s19'))):
        shutil.copyfile( os.path.join(Project_Path,Project_Name,Project_Mode,Project_Name+'.s19'),os.path.join(Project_Path,Project_Name,   Project_Mode+'_'+Project_Name+'.s19'))
        print(' file s19 out find')
    if(os.path.isfile(os.path.join(Project_Path,Project_Name,   Project_Mode,Project_Name+'.map'))):
        shutil.copyfile( os.path.join(Project_Path,Project_Name,Project_Mode,Project_Name+'.map'),os.path.join(Project_Path,Project_Name,   Project_Mode+'_'+Project_Name+'.map'))
        print(' file map out find')
    if(os.path.isfile(os.path.join(Project_Path,Project_Name,   Project_Mode,Project_Name+'.lst'))):
        shutil.copyfile( os.path.join(Project_Path,Project_Name,Project_Mode,Project_Name+'.lst'),os.path.join(Project_Path,Project_Name,  Project_Mode+'_'+Project_Name+'.lst'))
        print(' file lst out find')
    print('####################################	3 end ')

#########################################################################################################################
#########################################################################################################################
    
