#! /usr/bin/python3

# !/usr/local/bin/python  deprecated for Raspberry Pi
# IX_textnames.py renamed and enhanced to n.py vsn
# by D@CC on 2022CMar26
# 2022CMar25 added lNo (input line numbers) & function uses: "calls"
####################################################################
# first line (shebang) must be #! /usr/bin/python3                 #
# place the n.py and the package into Desktop and Sandbox          #
# Version: v05 by D@CC on 2024BFeb08    2 edits                    #
#                                                                  #
# Usage:  >$ cd Desktop/                                           #
#         >sudo chmod +x n.py                                      #
#         >$ python3 ../n.py  < ../adcRead_pkg.py                  #
# or:     >$ cd Desktop                                            #
#         >$ ./n.py -acdghimosu < adcRead_pkg.py                   #
# NB In terminal, the above should list the names of the           #
#       files that exist in the package or file named in stdin.    #
# NB recently added is the listing of used-functions i.e. "calls"  #
# NB now, can also list packages using true O'Reilly markers       # 
#                    but excluding many std python functions       #
# Due to the Unix trick line 1 "#!/usr...                          #
#     and the last line if __name__ ...  mainroutine()             #
# the command line below works (afer chmod ...):                   #
# >$ ./n.py -all <adcRead_pkg.py                                   #
####################################################################


# from textpack import marker            # use common separator key but

def mainroutine():

    vsn="v05"    # of mainroutine
    import sys
    from functionList_pkg import functionList
    from functionList_pkg import posNxFnUsed

    # functionList_v & posNxFnUsed_v are called in -h (help)

    marker = '#' + ':'*10 + 'textpak=>'      # the IX Marker is different
    omarker = ':'*10 + 'textpak=>'           # the original O'Reilly Marker
    mlen = len(marker)                       # file names appear after markers
    olen = len(omarker)

    cmdList0="[n]"  #default value
    argStr=str(sys.argv[1:])
    #print("argStr1:"+argStr)
    alen=len(argStr)
    argExt=argStr[alen-5:alen-2]
    #print("argExt:"+argExt)
    isBadArg=False
    if argExt==".py": isBadArg=True              #flag a Bad Argument
    if argExt.find("pkg")>-1 : isBadArg=True     #flag a Bad Argument
    #if end
    if isBadArg==True:
        continueDoh=True
        print('#::: Be sure to precede the Pkg name with a "<".')   
        return #from names    
    else:
        #print("argStr2:"+argStr)  
        #print("cmdList02:"+cmdList0)
        if False:
            continueDoh=True
        else:
            #print("argStr3:"+argStr)
            #for cmdList in sys.argv[1:]:
            if argStr=="[]": 
                cmdList=cmdList0
            else:
                cmdList=argStr
            #if end
            #print("cmdList3:"+cmdList)
            if cmdList.find("h")>-1 :
                uS="_"
                print("#:::: Help for python n.py "+vsn+" [IX pkg names list pgm]")
                print("#:::: Syntax: ./n.py [args] <pkg")
                print('#:::: Enhanced args = -acdghimosu_ or null')
                print("#:::: a:all,c:class,d:def,g:global,h:help,i:import,m:marker,")
                print('#::::    o:oreillyMarkers,s:source:,u:usedfunctions,_:"_'+'_"')
                print("#:::: NB use IX_textpack.py to create an IX package")
                print('#:::: NB for more help info see: IX_textpack.txt')
                print('#:::: NB IX marker is "#::::::::::'+'textpak=>"')
                print("#:::: (Cudos to:O'Reilly for textpack.py)")
                print("#:::: Source: http://index-of.es/Programming/Python/O'Reilly%20-%20Programming%20Python,%203rd%20Ed%20Aug2006.pdf")
                print("#:::: NB not to be confused with the Textpack pkg")

                v="unknown"

                print("#::::   mainroutine:n.py:  "+vsn)
                print("#::::   posNxFnUsed  vsn:  v",posNxFnUsed("",0,"?") )
                print("#::::   functionList vsn:  "+str(functionList("","?") )) #v05
                return   #from names 
            #if end
            if cmdList.find("all")>-1 :
               cmdList="-cdimogsu"     #all means list all (except h_)
            #endif
            if cmdList.find("a")>-1 :
               cmdList="-cdimogs"     #a means list all (except hu)
            #endif
            if cmdList.find("<")>-1 :
                print("#:::: ERROR precede the < with a space")
                return   #from names 
            #if end
            print("#::: Enhanced n.py "+vsn+" [IX pkg names list prg -h for help]:")
            
            if True:
                lNo=0
                markCnt=0
                for line in sys.stdin.readlines(  ):     # for all input lines
                    lNo=lNo+1
                    #print("before first line")
                    #if line=="": break
                    #if line==None: break
                    markIn=line[0:mlen]

                    #if cmdList.find("m")>-1 :           # always show markers
                    #if markCnt==0:
                    if False :
                        print("mlen:",mlen)
                        print("line.mlen:"+line[:mlen])
                        print("mkr:"+marker)
                    #if end
                    if(line[:mlen]== marker):            # is it a marker line
                        markCnt+=1
                        llen=len(line)
                        filename=line[mlen:llen-1]       # get filename without LF
                        print("#",lNo, "m "+filename)
                    #if end
                    #if cmdList.find("o")>-1 functionList on line:           # also show oreilly markers
                    if(line[:olen]== omarker):            # is it a o-marker line
                        markCnt+=1
                        llen=len(line)
                        filename=line[olen:llen-1]       # get filename without LF
                        print()
                        print("#",lNo, "o "+filename+" oooooooo Oreilly marker oooooooo")
                        print()
                    #if end
                    ##if end
                    isY=False
                    if cmdList.find("c")>-1 :
                        if line.find("class ")>-1: isY=True           # is it an class line
                        if isY :
                            llen=len(line)
                            pline="  "+line[:llen-1]       # get line without LF
                            print("#",lNo,pline)
                        #if end
                    #if end 
                    isY=False
                    if cmdList.find("i")>-1 :
                        if line.find("import ")>-1: isY=True           # is it an import line
                        if isY :
                            llen=len(line)
                            pline=" "+line[:llen-1]       # get line without LF
                            print("#",lNo,pline)
                        #if end
                    #if end
                    isY=False
                    if cmdList.find("g")>-1 :
                        if line.find("global ")>-1: isY=True           # is it a global line
                        if line.find("global(")>-1: isY=True           # is it a global line
                        if isY :
                            llen=len(line)
                            pline="  "+line[:llen-1]       # get line without LF
                            print("#",lNo,pline)
                        #if end
                    #if end
                    isY=False
                    if cmdList.find("s")>-1 :
                        if line.find("source:"     )>-1: isY=True     # is it a source line
                        if line.find("Source:"     )>-1: isY=True     # is it a Source line
                        if line.find("Web Source M")>-1: isY=True     # is it a Source line
                        if isY :
                            llen=len(line)
                            pline="  "+line[:llen-1]       # get line without LF
                            print("#",lNo,pline)
                        #if end
                    #if end
                    isY=False
                    uS="_"
                    if cmdList.find("_")>-1 :
                        if line.find(uS+uS)>-1: isY=True           # is it a source line
                        if isY :
                            llen=len(line)
                            pline="  "+line[:llen-1]       # get line without LF
                            print("#",lNo,pline)
                        #if end
                    #if end
                    isY=False
                    if cmdList.find("u")>-1 :
                        #print("in n.py before calling functionListNew")
                        for fName in functionList(line,0):

                            isY=True                     # default is to print the function name
                            #                            # but don't print std python function names
                            pyL=    ",if,append,close,cleanup,exit,fltest,find,findall,finditer"
                            pyL=pyL+",globals,imports,input,int,len,lstrip" #v05
                            pyL=pyL+",names,number,not,open"
                            pyL=pyL+",output,pac,print,read,range,read,readline,readlines"
                            pyL=pyL+",remove,replace,rstrip,search,sleep,start,split,str"
                            pyL=pyL+",strip,system,time,type,sub,write,yield,"
                            if fName in pyL: isY=False
                            if False :
                                if  fName=="if"     :isY=False           # bad
                                #if  fName=="functionList" :isY=False    #in IX
                                if  fName=="globals" :isY=False          #IX main test
                                if  fName=="imports" :isY=False          #IX main test
                                if  fName=="mainroutine"  :isY=False     #IX main test
                                if  fName=="names"  :isY=False           #IX main test
                                #if  fName=="output"  :isY=False
                                #if  fName=="posNFnUsed" :isY=False      #in IX
                                #if  fName=="setup"  :isY=False
                                #if  fName=="setmode"  :isY=False
                                #if  fName=="SMBus" :isY=False           #in IX
                            #if end
                            if cmdList.find("d")>-1 :
                                if line.find("def ") >-1 :  #so "d" will also print it out
                                    isY=False               #so don't print it twice
                                #if end
                            #if end
                            if isY :
                                print("#",lNo,"   "+fName+"()")
                                #print("#",lNo,line)
                            #if end
                        #for end
                    #if end
                    isY=False
                    if cmdList.find("d")>-1 :
                        if line.find("def " )>-1:
                            isY=True           # is it a def line
                            #defList=defList+[1]
                        if line.find("#def ")>-1: isY=False
                        if line.find("#end def ")>-1: isY=False
                        if line.find("#def end ")>-1: isY=False
                        if isY :
                            llen=len(line)
                            pline="  "+line[:llen-1]       # get line without LF
                            print("#",lNo,pline)
                        #if end
                    #if end
                #for end
                if markCnt==0 : print("#::: WARNING: pkg has no markers")
            print("#",lNo,"eof")
            print("#::: end of list by n.py "+vsn)
        #if end
    #if end
#def end mainroutine

if __name__ == '__main__' : mainroutine( )
#end of n_v05.py