import sys
import string
import ItemGUI

class item:
    def __init__(self, len=0, tipo=None, scelte={}, formato=None, nome=None):
        self.len=len
        self.tipo=tipo
        self.scelte=scelte
        self.formato=formato
        self.nome=nome
        self.cambiato = 0

        self.attuale=""
    def estrai(self, linea):
        token=linea[:self.len]
        self.setta(token)
        self.cambiato = 0
        return linea[self.len:]

    def setta(self, token):
        self.token=token
        if( self.tipo is None):
            pass
        elif( type(self.tipo)==type("")):
            self.attuale = token
        elif( type(self.tipo)==type(1)):
            if(token==" "*self.len or string.strip(token)=="" ):
                self.attuale=0
            else:
                self.attuale = string.atoi(token)
        elif( type(self.tipo)==type(1.0)):
            if(token==" "*self.len or string.strip(token)=="" ):
                self.attuale=0.0
            else:
                self.attuale = string.atof(token)

    def ceccaCond(self, cond):
        val=self.attuale
        print " cecco ", cond
        print " val est ", val
        command="res=("+cond+")"
        exec(command)
        return res
    
    def cercaScelta(self):
        found=None
        for cond in self.scelte.keys():
            res=self.ceccaCond(cond)
            if(res):
                found = cond
                break
        if( found is None):
            return  ( None, self.scelte.keys()[0], self.scelte.values()[0])
        else:
            return  (  found , self.scelte[found])


    def getTesto(self):
        testo=""
        if(type(self.tipo)==type("")):
            testo=" "*(self.len-len(self.attuale)  )  +  self.attuale
        elif(self.tipo is None):
            res= self.token
        elif(type(self.tipo)==type(1)):
            if(string.strip(self.token)==""):
                testo=" "*self.len
            # elif(self.attuale==0):
            #     testo=" "*self.len
            else:
                testo=str(self.attuale)
                if(len(testo)>self.len):
                    raise " len(testo)>self.len "
                testo=" "*(self.len-len(testo))+testo
        elif(type(self.tipo)==type(1.0)):
            if(self.formato is None):
                raise " formato dovrebbe esserci per floats "
            else:
                testo=self.formato %(self.attuale)
                testo=magrisci(testo)
                testo=" "*(self.len-len(testo)) + testo
        return testo


def magrisci(s):
    pos=string.find(s,"e")
    if(pos==-1):
        pos=len(s)-1
        isexp=0
    else:
        pos=pos-1
        isexp=1
    sta=pos
    while(s[sta]=="0"):
        sta=sta-1
    if(s[sta]=="."):
        if(isexp):
            sta=sta-1
        else:
            sta=min(sta+1,pos)
    res=s[:sta+1]+s[pos+1:]
    return res
            


def leggilinee(fn):
    f=open(fn,"r")
    linee=[]
    for linea in f:
        if string.lstrip(linea)[:2]=="-1" :
            break
        linee.append(linea)
    return linee


def getControlsItems():
    itemlist=[]
    itemlist.append(
        item(len=1,
             tipo=1,
             nome="ITPOW",
             scelte={"val==1 or val>2": " print SCF iteration information (NITER, DELT, ALFM); this information is sent to the monitor screen if IW6 <0" ,
                     "val>1" : " call POWER to print <r**m>"
                     }
             )
        )

    itemlist.append(
        item(len=1,
             tipo=1,
             nome="ITPVU",
             scelte={
        "val>0" : "print Fk and Gk",
        "val>1":  "print Coulomb interaction energies ", 
        "val>2":  "print wavefunction overlap integrals",
        "val>3":  "print HFS potentials (RU, RUEE, etc)", 
        "val>4":  "print HX or HF potentials (Vnl) ",
        "val>5":  "in SCHEQ, print relativistic contribution to potential"
        }
             )
        )
    
    itemlist.append(
        item(len=1,
             tipo=1,
             nome="IPTEB",
             scelte={
        "val>0":" print EE, JJJ, R(JJJ), AZ ",
        "val>1":" print Ekin, etc ",
        }
             )
        )

    
    itemlist.append(
        item(len=2,
             tipo=1,
             nome="NORBPT",
             scelte={
        "val<0":" do not print wavefunctions ",
        "val>0":" print first two and last NORBPT wavefunctions at every fifth mesh point ",
        "val>5":" print continuum wavefunctions at every mesh point (for configurations 1, 5, 10, 15, ... only, if 0<NORBPT<6)  any, write on tape 2 or 7 the last |NORBPT| wavefunctions (at least 2; if |NORBPT|=9, write all wavefunctions) "
        }
             )
        )



    itemlist.append(
        item(len=1,
             tipo=1,
             nome="IZHXBW",
             scelte={
        "val>0":" in HF8, calculate and print all quantities using the (HX) input wavefunctions (primarily to give zeta calculated by the Blume-Watson method; of no great use, as the Blume-Watson method is now used in RCN as well as in HF8) "
           }
             )
        )



    itemlist.append(
        item(len=2,
             tipo=1,
             nome="IPHFWF",
             scelte={
        "val>0":" in HF8, print the last |IHFWF| wavefunctions at every mesh point ",
        "val<0":" same, except print at only every fourth mesh point ",
        "val==9 or val==-9":" print all wavefunctions "
        }
             )
        )


    itemlist.append(
        item(len=2,
             tipo=1,
             nome="IHF",
             scelte={
        "val==0":" signifies an RCN calculation only (hence, do not load HF8) ",
        "val==1":" RCN output wavefunctions are for input to HF8 (via tape 7, rather than for RCN2 (via tape 2); if IREL > 1, RCN calculation of radial integrals is skipped; if IREL=0 and TOLEND < 1.E-4, only ZETA1 is called (to calculate relativistic energy correction for Eav in HF8) ",
       "val==2":" carry out a Hartree-Fock calculation within RCN "
        }
             )
        )


    itemlist.append(
        item(len=3,
             tipo=1,
             nome="IBB",
             scelte={
        "val!=0":"sets the outer boundary of the atom at mesh point IBB; do not use this option, as it is not completely debugged.",
        "val==0":"Safe option"
        }
             )
        )

    itemlist.append(
        item(len=2,
             tipo=1.0,
             formato="%2.1f",
             nome="TTOLSTB",
             scelte={
        "1==1":" it's a referring calculation parameter of the Hartree-Fock calculation; when DELTA(cycle parameter) < TOLSTB , RCN31 begin the wavefunctions calculation by those of the subroutine SCHEQ.DELTA is a difference between the calculated potential and that of the preceeding cycle."
        }
             )
        )
    

    itemlist.append(
        item(len=5,
             tipo=1.0,
             formato="%5.1e",
             nome="TOLKM2",
             scelte={
        "1==1":"it's a control parameter related to calculation potential; when DELTA < TOLKM2, RCN31 stop the calculation of the pure HFS potential, and begin with an HX or HF calculation, in the manner that depends on the value of KUT (see De Groot manual for explanations). In this case TOLKM2=1.0"
        }
             )
        )


    itemlist.append(
        item(len=10,
             tipo=1.0,
             formato="%10.1e",
             nome="TOLEND",
             scelte={
        "1==1":"is the maximum permissible value of DELTA (the absolute value of the change in RU) for ending the SCF iteration (see the main program, statements number 530-550 and 700-780). "
        }
             )
        )

    
    

    itemlist.append(
        item(len=10,
             tipo=1.0,
             formato="%10.1e",
             nome="THRESH",
             scelte={
        "1==1":"is the maximum permissible fractional change in the value of the eigenvalue E to end the eigenvalue iteration (SCHEQ, statements 805 and 205).   "
        }
             )
        )

    
 
    itemlist.append(
        item(len=2,
             tipo=1,
             nome="KUTD",
             scelte={
        "val==-2":"it's related to KUT, wich select the type of calculation on the potential .",
        "val!=-2":"WARNING Documentation I found on the web doesnt tell much. But it looks like it is often -2"
        }
             )
        )
 
    itemlist.append(
        item(len=2,
             tipo=1,
             nome="KUT",
             scelte={
        "val ==1":"UNUSUAL  HFS calculation with no tail cutoff (KUT=1)",
        "val ==0": "USUAL HFS  with tail cutoff (KUT=0)  ",
        }
             )
        )
 
    itemlist.append(
        item(len=1,
             tipo=1,
             nome="IVINTI",
             scelte={
        " val == 0 ":"USUAL 	 no call of subroutine VINTI",
        "val  >0 ":" 	Vinti integrals calculated and printed",
        "val  > 1":" 	some debugging information printed"
        }
             )
        )

    itemlist.append(
        item(len=1,
             tipo=1,
             nome="IREL",
             scelte={

        "val==0":"If IREL=0, relativistic terms are omitted from the differential equations (HX or HF)",
        "val>0":"if IREL > 0, these terms are included (HXR or HFR).",
        "val>1":"If IREL > 1, approximate Breit magnetic and retardation energies will be included, provided the dimensions of QNL are the same as those of PNL.",
        "val>3":"If IREL > 3, some diagnostic printouts will occur. "
        }
             )
        )
    
    

    itemlist.append(
        item(len=2,
             tipo=1,
             nome="MAXIT",
             scelte={
        "val==90":"COMMON value : is the maximum allowable number of SCF iterations; if convergence has not been reached within MAXIT cycles, the calculation is continued for 4 more cycles with diagnostic printout produced via NPR > 0 (RCN, 710-729)",
        "val!=90":" Other value : is the maximum allowable number of SCF iterations; if convergence has not been reached within MAXIT cycles, the calculation is continued for 4 more cycles with diagnostic printout produced via NPR > 0 (RCN, 710-729) "
        }
             )
        )

   

    itemlist.append(
        item(len=2,
             tipo=1,
             nome="NPR",
             scelte={
        "val!=0":"not 0, diagnostic potentials and diagnostic wavefunctions are printed during the course of the RCN SCF iteration ",
        "val==0":" diagnostic potentials and diagnostic wavefunctions are NOT  printed during the course of the RCN SCF iteration "
      }
             )
        )


    
    


    itemlist.append(
        item(len=5,
             tipo=1.0,
             formato="%5.5f",
             nome="EXF10",
             scelte={
        "val==1.0":"Kohn and Sham's modified value for the coefficient of Slater's exchange term for an HFS calculation with no tail cutoff (KUT=1) or with tail cutoff (KUT=0) (RCN 411-417).",
        "val==1.5":"EXF10=1.5 is Slater's original value  "
        }
             )
        )

    


    itemlist.append(
        item(len=5,
             tipo=1.0,
             formato="%5.5f",
             nome="EXFM1",
             scelte={
        "val==0":"are values of k1, k3, and k2, respectively, for KUT=-1 in an HX calculation [Phys. Rev.163, 54 (1967), Eqs. (13)-(14) or TASS, Eqs. (7.49)-(7.50)]. Provided IHF=0, EXFM1=0.0 will give a Hartree calculation for KUT=-1, and KUT=-2 gives an HS calculation. (CAO and CA1 are no longer read in from the control card, but simply set to 0.5 and 0.7, respectively, in the code.) "
        }
             )
        )


    itemlist.append(
        item(len=5,
             tipo=1.0,
             formato="%5.5f",
             nome="EMX",
             scelte={
        "val==0.0":"EMX(column 61th-65th):selection parameter for the construction of the mesh points (es: 0.0)."
        }
             )
        )




    itemlist.append(
        item(len=5,
             tipo=1.0,
             formato="%5.5f",
             nome="CORRF",
             scelte={
        "val==0.0":" factor for correlation ",
        "val==1.0":" factor for correlation ",
        }
             )
        )
    



    itemlist.append(
        item(len=5,
             tipo=1,
             nome="IW6",
             scelte={
        "-6":"I dont knwo what it is but from what I see around it is quite often(always) set to -6"
        }
             )
        )
    
    return itemlist
    
    

    
def main():
    linee = leggilinee(sys.argv[1])
    items = getControlsItems ()

    count=0
    for item in items:
        print count+1, "-" ,count+item.len,"   " ,item.nome
        count=count+item.len

    

    primalinea= linee[0]
    for item in items:
        primalinea=item.estrai(primalinea)
        print item.nome," ", item.attuale,"  ", item.getTesto(),"  ", item.cercaScelta()



    
    import qt
    app=  qt.QApplication([])

    qspl0 = qt.QSplitter()
    qspl0.setOrientation( qt.Qt.Vertical )
    
    sv       = qt.QScrollView(qspl0)
    ledoc    =  qt.QTextEdit(qspl0)
    leinput  =  qt.QTextEdit(qspl0)
    

##     QScrollView* sv = new QScrollView(...);
##     QLabel* child1 = new QLabel("CHILD", sv->viewport());
##     sv->addChild(child1);
##     QLabel* child2 = new QLabel("CHILD", sv->viewport());
##     sv->addChild(child2);
##     QLabel* child3 = new QLabel("CHILD", sv->viewport());
##     sv->addChild(child3);


    H=0
    for iITEM in range(len( items )):
        ob=ItemGUI.ItemGUI(parent = sv.viewport(), ITEM=items[iITEM])
        sv.addChild(ob,0,H)
        H=H+ob.height()

    sv.resizeContents(  ob.width(), H+ ob.height() )
    qspl0.resize ( ob.width()+20 , 400 )



    
    print  ob.width()
    
    ## sv.show()
    qspl0.show()
    
    app.exec_loop()
    


        
main()
