import arcpy
from arcpy import env
from arcpy.sa import *
import os
import traceback
import sys
import LegalGeo_Routines_Module
import shutil
import time


def isArcMap():
	try:
		arcpy.mapping.MapDocument("CURRENT")
		return True
	except:
		return False

try:

    #Check for spatial analyst license
    if arcpy.CheckExtension("Spatial") == "Available":
        arcpy.CheckOutExtension("Spatial")
    else:
        raise LicenseError

    project_folder = arcpy.GetParameterAsText(0)
    arcpy.RefreshCatalog(project_folder)
    if arcpy.Exists(project_folder+"\\lg_input.gdb"):
        inPath = project_folder+"\\lg_input.gdb\\"
        inWS = project_folder+"\\lg_input.gdb"
        DirToRemove = project_folder+os.sep+"lg_scratch.gdb"
        if not(arcpy.Exists(project_folder+"\\lg_scratch.gdb")):
            arcpy.CreateFileGDB_management(project_folder,"lg_scratch.gdb")
        env.workspace = project_folder+"\\lg_scratch.gdb"
        outPath = project_folder+"\\lg_output.gdb\\"
        outWS = project_folder+"\\lg_output.gdb" #For adding to map view if user in ArcMap
        
        imgExt = ""
    else:
        inPath = project_folder+"\\lg_input\\"
        inWS = project_folder+"\\lg_input"
        if not(arcpy.Exists(project_folder+"\\lg_scratch")):
            arcpy.CreateFolder_management(project_folder,"lg_scratch")
        env.workspace = project_folder+"\\lg_scratch"
        outPath = project_folder+"\\lg_output\\"
        outWS = project_folder+"\\lg_output"
        DirToRemove = project_folder+os.sep+"lg_scratch"
        #arcpy.AddMessage(DirToRemove)
        imgExt=".img"

    env.overwriteOutput = 1
    lgRemsPrjOnly = inPath+"lg_remPrjOnly"+imgExt
    lgConvPrjOnly = inPath+"lg_ConvProjOnly"+imgExt 

    userParamfile = project_folder+"\\lg_user_defined_params.txt"
    paramUse = False
    if arcpy.Exists(userParamfile):
        pVals=[]
        params = open(userParamfile,"r")
        try:
            for l in params:
                if "=" in l:
                    vals = l.split("=")
                    val = vals[1]
                    val = int(val.strip())
                    pVals.append(val)
            if len(pVals)== 11:
                arcpy.AddMessage("Using input parameter file: "+userParamfile)
                paramUse = True
                
            else:
              arcpy.AddWarning("User parameter has been modified. Application used default distances.")
              pVals = [2000,1,100,10000,250,2500,100,1000,500,5000,0]               
        except:
            arcpy.AddWarning("User parameter file corrupt. Application used default distances.")
            pVals = [2000,1,100,10000,250,2500,100,1000,500,5000,0]
            
    else:
        pVals = [2000,1,100,10000,250,2500,100,1000,500,5000,0]    
    
    Rem_ZI_Dist = pVals[0]#2000
    Apply_100 = pVals[10]#0

    intCatVals = []
    catRaster = ["lgBioAll_","lgESAll_","lgLandAll_","lgLegalAll_","lgThreatAll_"]
    indvRaster = ["lgBio_","lgES_","lgLand_","lgLegal_","lgThreat_"]
    catHeadings = ["Biodiversity","Environmental Services","Landscape","Leagal","Threats"]
    intIndVals = []
    for x in range (3,30):
        val = arcpy.GetParameterAsText(x)
        if not(val):
            val = 0
        intVal = int(val)
        if x < 8:
            intCatVals.append(intVal)
        else:
            intIndVals.append(intVal)
    env.scratchWorkspace = env.workspace
    remRankName4Arcmap = arcpy.GetParameterAsText(1)
    regRankName4Arcmap = arcpy.GetParameterAsText(2)
    outRemRankName = outPath+remRankName4Arcmap+imgExt
    outRegRankName = outPath+regRankName4Arcmap+imgExt

    #arcpy.AddMessage("Indv= "+str(intIndVals))
    #arcpy.AddMessage("Cats= "+str(intCatVals))
    
    
    inputFN = os.path.join(project_folder+os.sep,"lg_analysis_log.txt")
    if arcpy.Exists(inputFN):
        crs = open(inputFN,'a')
    else:
        inputTxtFile = file(inputFN,'wt')
        crs = open(inputFN,'a')
    crs.write("\n")
    crs.write("Step 2b Prioritize Remnants and Regeneration based on user weighting " +str(datetime.datetime.now())+"\n")
    crs.write("Data Output location:  "+outPath+"\n")
    crs.write("Remnants Ranking Raster Dataset: "+outRemRankName+"\n")
    crs.write("Regeneration Ranking Raster Dataset: "+outRegRankName+"\n")
    crs.write("Weights used for analysis: \n") 
    
    convSum = []
    remSum = []    
    nonChangeCnt = intIndVals.count(1)

    if nonChangeCnt <> 22:
        arcpy.AddMessage("Running through all weight changes.")
        for num in range (0,5):
            r = catRaster[num]
            rdRem = outPath+r+"RemRank"+imgExt
            rInv = indvRaster[num]
            if arcpy.Exists(rdRem):
                crs.write ("*** "+catHeadings[num]+" Weights ***")
                crs.write("\n")
                if num == 0:
                
                    #Bio
                    catHead = catHeadings[num]
                    catWt = intCatVals[num]
                    if catWt > 0:
                        arcpy.AddMessage("Applying weights to Biodiveristy Category")
                        bioName = ["Diversity","Rarity","Richness","Other"]
                        bio = ["Si","Veg","Richness","Other"]
                        b=0
                        bioSum = []
                        for x in range(0,4):
                            indvWt = intIndVals[x]
                            rdInvRank = outPath+"lgBio_"+bio[b]+"Rank"+imgExt
                            if arcpy.Exists(rdInvRank):
                                #arcpy.AddMessage(rdInvRank)
                                crs.write(bioName[b]+" = "+str(indvWt))
                                crs.write("\n")
                                if indvWt <> 1:
                                    bTimes = Times(rdInvRank,indvWt)
                                    bTimes.save(bio[b]+imgExt)
                                    bioSum.append(bio[b]+imgExt)
                                else:
                                    bioSum.append(rdInvRank)                            
                            b+=1
    #                    arcpy.AddMessage(bioSum)    
                        bSumRank = CellStatistics(bioSum,"SUM","DATA")
                        bSumRank.save("xxlg_BioSum"+imgExt)
                        
                        #bRank = Slice("xxlg_BioSum"+imgExt,100,"NATURAL_BREAKS",1)
                        #bRank.save("xxlg_BRank"+imgExt)
                        
                        FinalBRank = LegalGeo_Routines_Module.rankVals("xxlg_BioSum"+imgExt,"bioRem",lgRemsPrjOnly,imgExt)
                        FinalBRank.save("lg_BioRankFinal"+imgExt)
                        
                        #Regeneration Rank
                        #Ranking those converted lands within 2000 meters
                        natVegRank = LegalGeo_Routines_Module.WeightedDistVeg("xxlg_BioSum"+imgExt,"BioConv",Rem_ZI_Dist,imgExt)
                        natVegRank.save("natVegConvWD"+imgExt)
                        finalConvBioRank = LegalGeo_Routines_Module.rankVals("natVegConvWD"+imgExt,"bioCon",lgConvPrjOnly,imgExt)
                        finalConvBioRank.save("lgBioAll_ConvRank"+imgExt)
                        #Need to set Cat Weight and 

                        crs.write(catHead+" Category Weight = "+str(catWt))
                        crs.write("\n")
                        if catWt <> 1:
                            remTimes = Times("lg_BioRankFinal"+imgExt,catWt)
                            remTimes.save("BioWtFinalRank"+imgExt)
                            remSum.append("BioWtFinalRank"+imgExt)
                            convTimes = Times("lgBioAll_ConvRank"+imgExt,catWt)
                            convTimes.save("BioConvWtFinalRank"+imgExt)
                            convSum.append("BioConvWtFinalRank"+imgExt)                        
                        else:
                            remSum.append("lg_BioRankFinal"+imgExt)
                            convSum.append("lgBioAll_ConvRank"+imgExt)
                    else:
                        crs.write(catHead+" Category Weight = "+str(catWt))
                        crs.write("\n")  
                        arcpy.AddMessage("Biodiversity Category removed from ranking.")
                                            
                    
                elif num == 1:
                    #ES
                    catHead = catHeadings[num]
                    catWt = intCatVals[num]
                    if catWt > 0:
                        arcpy.AddMessage("Applying weights to Environmental Services Category")
                        esName = ["Active River Area","Fragile Areas", "Spring Density", "Other"]
                        es = ["ARA","FA","SD","Other"]
                        e = 0
                        esSum =[]
                        for x in range(4,8):
                            indvWt = intIndVals[x]
                            rdInvRank = outPath+"lgES_"+es[e]+"_Rank"+imgExt
                            if arcpy.Exists(rdInvRank):
                                #arcpy.AddMessage(rdInvRank)
                                crs.write(esName[e]+" = "+str(indvWt))
                                crs.write("\n")
                                if indvWt <> 1:
                                    esTimes = Times(rdInvRank,indvWt)
                                    esTimes.save(es[e]+imgExt)
                                    esSum.append(es[e]+imgExt)
                                else:
                                    esSum.append(rdInvRank)                             
                            e+=1

                        #Final Ranking
                        esSumRank = CellStatistics(esSum,"SUM","DATA")
                        esSumRank.save("esSum"+imgExt)
                        
                        esRank = LegalGeo_Routines_Module.rankVals("esSum"+imgExt,"esRem",lgRemsPrjOnly,imgExt)
                        esRank.save("esRank"+imgExt)
                        
                        esConvRank = LegalGeo_Routines_Module.rankVals("esSum"+imgExt,"esConv",lgConvPrjOnly,imgExt)
                        esConvRank.save("esConvRank"+imgExt)                    
                        
                        
                        
                        crs.write(catHead+" Category Weight = "+str(catWt))
                        crs.write("\n")                    

                        if catWt > 1:
                            remTimes = Times("esRank"+imgExt,catWt)
                            remTimes.save("esWtFinalRank"+imgExt)
                            remSum.append("esWtFinalRank"+imgExt)
                            convTimes = Times("esConvRank"+imgExt,catWt)
                            convTimes.save("esConvWtFinalRank"+imgExt)
                            convSum.append("esConvWtFinalRank"+imgExt)                        
                        else:
                            remSum.append("esRank"+imgExt)
                            convSum.append("esConvRank"+imgExt)                    
                        
                    else:
                        crs.write(catHead+" Category Weight = "+str(catWt))
                        crs.write("\n")  
                        arcpy.AddMessage("Environmental Services Category removed from ranking.")
                    
                    
                    
                        
                elif num == 2:
                    #Land
                    catHead = catHeadings[num]
                    catWt = intCatVals[num]
                    if catWt > 0:
                        arcpy.AddMessage("Applying weights to Landscape Category")
                        landName = ["Distance from Converted", "Remnant Size","Remanant Shape","Remnant Fragmentation","Distance to Remnant","Edge Reduction","Other"]
                        land = ["Dist","Size","PerCore","Frag","ConvDist2Size","ConvEdge","Other","ConvOther"]
                        la = 0
                        #remNums = [0,1,2,3,7]
                        #convNums = [4,5,6,8]
                        laRemSum=[]
                        laConvSum=[]
                        for x in range(8,15):
                            indvWt = intIndVals[x]
                            uName = land[la]
                            rdInvRank = outPath+"lgLand_"+uName+"Rank"+imgExt
                            
                            if arcpy.Exists(rdInvRank):
                                crs.write(landName[la]+" = "+str(indvWt))
                                crs.write("\n")
                                #arcpy.AddMessage(rdInvRank) 
                                if indvWt <> 1:
                                    laTimes = Times(rdInvRank,indvWt)
                                    laTimes.save(uName+imgExt)
                                    if "Conv" in uName:
                                        laConvSum.append(uName+imgExt)
                                    else:
                                        laRemSum.append(uName+imgExt)
                                    if x ==14:
                                        addOne = la+1
                                        plusIndvRank = outPath+"lgLand_"+land[addOne]+"Rank"+imgExt
                                        if arcpy.Exists(plusIndvRank):
                                            #arcpy.AddMessage(plusIndvRank)
                                            plusTimes = Times(plusIndvRank,indvWt)
                                            plusTimes.save(land[addOne]+imgExt)
                                            laConvSum.append(land[addOne]+imgExt)
                                else:
                                    if "Conv" in uName:
                                        laConvSum.append(rdInvRank)
                                    else:
                                        laRemSum.append(rdInvRank)
                                    if x ==14:
                                        addOne = la+1
                                        plusIndvRank = outPath+"lgLand_"+land[addOne]+"Rank"+imgExt
                                        if arcpy.Exists(plusIndvRank):
                                            #arcpy.AddMessage(plusIndvRank)
                                            laConvSum.append(plusIndvRank)          
                            la +=1
                        #Final Ranking
                        laRemSumR = CellStatistics(laRemSum,"SUM","DATA")
                        laRemSumR.save("laRemSum"+imgExt)
                        laRemRank = LegalGeo_Routines_Module.rankAllVals("laRemSum"+imgExt,"landRem",imgExt)
                        laRemRank.save("laRemRank"+imgExt)
                        
                        laConvSumR = CellStatistics(laConvSum,"SUM","DATA")
                        laConvSumR.save("laConvSum"+imgExt)
                        laConvRank = LegalGeo_Routines_Module.rankAllVals("laConvSum"+imgExt,"landConv",imgExt)
                        laConvRank.save("laConvRank"+imgExt)  
                        
                        catWt = intCatVals[num]
                        catHead = catHeadings[num]
                        crs.write(catHead+" Category Weight = "+str(catWt))
                        crs.write("\n")                    

                        if catWt <> 1:
                            remTimes = Times("laRemRank"+imgExt,catWt)
                            remTimes.save("laWtFinalRank"+imgExt)
                            remSum.append("laWtFinalRank"+imgExt)
                            convTimes = Times("laConvRank"+imgExt,catWt)
                            convTimes.save("laConvWtFinalRank"+imgExt)
                            convSum.append("laConvWtFinalRank"+imgExt)                        
                        else:
                            remSum.append("laRemRank"+imgExt)
                            convSum.append("laConvRank"+imgExt)                    
                    else:
                        crs.write(catHead+" Category Weight = "+str(catWt))
                        crs.write("\n")  
                        arcpy.AddMessage("Landscape category removed from ranking.")                       
                    
                        
                elif num == 3:
                    #Legal
                    catHead = catHeadings[num]
                    catWt = intCatVals[num]
                    if catWt > 0:
                        arcpy.AddMessage("Applying weights to Legal Category")
       
                        legalNames = ["LRs","PPAs","PAs","CPAs","Other"]
                        #legal = ["LRs","ConvLRs","PPAs","ConvPPAs","PAs","ConvPAs","CPAs","Other"]
                        le=0
                        #lyrNum = 0
                        legalConvSum = []
                        legalRemSum = []
                        for x in range(15,20):
                            indvWt = intIndVals[x]
                            uName = legalNames[le]
                            rdInvRank = outPath+"lgLegal_"+uName+"Rank"+imgExt
                            if arcpy.Exists(rdInvRank):
                                #arcpy.AddMessage(rdInvRank) 
                                legalCatName = legalNames[le]
                                crs.write(legalCatName+ "="+str(indvWt))
                                crs.write("\n")
                                if x < 18:
                                    if indvWt <> 1:
                                        rdInvConvRank = outPath+"lgLegal_Conv"+uName+"Rank"+imgExt
                                        
                                        legalRemTimes = Times(rdInvRank,indvWt)
                                        legalRemTimes.save(uName+imgExt)
                                        legalRemSum.append(uName+imgExt)
                                        if arcpy.Exists(rdInvConvRank):
                                            #arcpy.AddMessage(rdInvConvRank) 
                                            legalConvTimes = Times(rdInvConvRank,indvWt)
                                            legalConvTimes.save("Conv"+uName+imgExt)
                                            legalConvSum.append("Conv"+uName+imgExt)                                       
                                    else:
                                        legalRemSum.append(rdInvRank)
                                        rdInvConvRank = outPath+"lgLegal_Conv"+uName+"Rank"+imgExt
                                        if arcpy.Exists(rdInvConvRank):
                                            legalConvSum.append(rdInvConvRank)
                                
                                else:
                     
                                    if indvWt <> 1:
                                        legalTimes = Times(rdInvRank,indvWt)
                                        legalTimes.save(uName+imgExt)
                                        legalRemSum.append(uName+imgExt)
                                    else:
                                        legalRemSum.append(rdInvRank)                                
                            #lyrNum+=1
                            le+=1
                        #Final Ranking
                        legalRemSumR = CellStatistics(legalRemSum,"SUM","DATA")
                        legalRemSumR.save("legalRemSum"+imgExt)
                        legalRemRank = LegalGeo_Routines_Module.rankAllVals("legalRemSum"+imgExt,"legalRem",imgExt)
                        legalRemRank.save("legalRemRank"+imgExt)
                        
                        legalConvSumR = CellStatistics(legalConvSum,"SUM","DATA")
                        legalConvSumR.save("legalConvSum"+imgExt)
                        legalConvRank = LegalGeo_Routines_Module.rankAllVals("legalConvSum"+imgExt,"legalConv",imgExt)
                        legalConvRank.save("legalConvRank"+imgExt)  
                        

                        crs.write(catHead+" Category Weight = "+str(catWt))
                        crs.write("\n")                    

                        if catWt <> 1:
                            remTimes = Times("legalRemRank"+imgExt,catWt)
                            remTimes.save("legalWtFinalRank"+imgExt)
                            remSum.append("legalWtFinalRank"+imgExt)
                            convTimes = Times("legalConvRank"+imgExt,catWt)
                            convTimes.save("legalConvWtFinalRank"+imgExt)
                            convSum.append("legalConvWtFinalRank"+imgExt)                        
                        else:
                            remSum.append("legalRemRank"+imgExt)
                            convSum.append("legalConvRank"+imgExt)             
                    else:
                        crs.write(catHead+" Category Weight = "+str(catWt))
                        crs.write("\n")  
                        arcpy.AddMessage("Legal Category removed from ranking.")
                           
                else:
                    #Threat
                    catHead = catHeadings[num]
                    catWt = intCatVals[num]
                    if catWt > 0:
                        arcpy.AddMessage("Applying weights to Threat Category")                    
                        threatNames = ["Accessibility","Other"]
                        threat = ["Access","Other"]
                        t = 0
                        tSum = []
                        for x in range(20,22):
                            indvWt = intIndVals[x]
                            rdInvRank = outPath+"lgThreat_"+threat[t]+"Rank"+imgExt
                            if arcpy.Exists(rdInvRank):
                                #arcpy.AddMessage(rdInvRank)
                                crs.write(threatNames[t]+ " = "+str(indvWt))
                                crs.write("\n")
                                if indvWt <> 1:
                                    tTimes = Times(rdInvRank,indvWt)
                                    tTimes.save(threat[t]+imgExt)
                                    tSum.append(threat[t]+imgExt)
                                else:
                                    tSum.append(rdInvRank)
                            
                            t+=1

                        #Final Ranking
                        tSumRank = CellStatistics(tSum,"SUM","DATA")
                        tSumRank.save("tSum"+imgExt)
                        
                        tRank = LegalGeo_Routines_Module.rankVals("tSum"+imgExt,"threatRem",lgRemsPrjOnly,imgExt)
                        tRank.save("tRank"+imgExt)
                        

                        tConvRank = LegalGeo_Routines_Module.rankVals("tSum"+imgExt,"threatConv",lgConvPrjOnly,imgExt)
                        tConvRank.save("tConvRank"+imgExt)                    
                        

                        crs.write(catHead+" Category Weight = "+str(catWt))
                        crs.write("\n")                    

                        if catWt <> 1:
                            remTimes = Times("tRank"+imgExt,catWt)
                            remTimes.save("tWtFinalRank"+imgExt)
                            remSum.append("tWtFinalRank"+imgExt)
                            convTimes = Times("tConvRank"+imgExt,catWt)
                            convTimes.save("tConvWtFinalRank"+imgExt)
                            convSum.append("tConvWtFinalRank"+imgExt)                        
                        else:
                            remSum.append("tRank"+imgExt)
                            convSum.append("tConvRank"+imgExt)                    
                    
                    else:
                        crs.write(catHead+" Category Weight = "+str(catWt))
                        crs.write("\n")  
                        arcpy.AddMessage("Threat category removed from ranking.")                         
                                            

        #arcpy.AddMessage("BioSum = "+str(bioSum))
        #arcpy.AddMessage("esSum = "+str(esSum))
        #arcpy.AddMessage("laRemSum = "+str(laRemSum))
        #arcpy.AddMessage("laConvSum = "+str(laConvSum))
        #arcpy.AddMessage("legalRemSum = "+str(legalRemSum))
        #arcpy.AddMessage("legalConvSum = "+str(legalConvSum))
        #arcpy.AddMessage("tSum = " +str(tSum))

                    
    else:
        arcpy.AddMessage("Only category weights identified as changed.")
        crs.write("Only Category Weights Changed \n")
        crs.write("Category Weights Used:\n")# Biodiversity = "+strCatVals[0]+", Enviornmental Services = "+strCatVals[1]+", Landscape = "+strCatVals[2]+", Legal = "+strCatVals[3]+", Threats = "+strCatVals[4])

        for num in range (0,5):
            r = catRaster[num]
            rdRem = outPath+r+"RemRank"+imgExt
            if arcpy.Exists(rdRem):
                wt = intCatVals[num]
                crs.write (catHeadings[num]+" Category Wt = "+str(wt)+"\n")
                rdConv = outPath+r+"ConvRank"+imgExt
                if wt != 0:
                    if wt > 1:
                        timesRem = Times(rdRem,wt)
                        
                        timesRem.save(r+"rem"+imgExt)
                        remSum.append(r+"rem"+imgExt)
                        timesConv = Times(rdConv,wt)
                        timesConv.save(r+"conv"+imgExt)
                        convSum.append(r+"conv"+imgExt)
                    else:
                        remSum.append(rdRem)
                        convSum.append(rdConv)
 

   
    #Final Ranking-----------------------------------------------------------------------------
    arcpy.AddMessage("Combining and Ranking all categories of analysis and creating final output")
    sumRemRanks = CellStatistics(remSum,"SUM","DATA")
    sumRemRanks.save("sumRemRanks"+imgExt)

    FinalRemRanking = LegalGeo_Routines_Module.rankVals("sumRemRanks"+imgExt,"finalRem",lgRemsPrjOnly,imgExt)
    #default rem rank of 100 for LRs and PAs
    #default rem rank of 100 for LRs and PAs
    if Apply_100 == 1:
        dRemRank = []
        if arcpy.Exists(inPath+"lgLegal_LR_Ones"+imgExt):
            LR100s = Times(Times(inPath+"lgLegal_LR_Ones"+imgExt,100),inPath +"lg_REM_Ones"+imgExt)
            LR100s.save("LR100s"+imgExt)
            dRemRank.append("LR100s"+imgExt)
        if arcpy.Exists(inPath+"lgLegal_PA_ones"+imgExt):
            PA100s = Times(Times(inPath+"lgLegal_PA_Ones"+imgExt,100),inPath +"lg_REM_Ones"+imgExt)
            PA100s.save("PA100s"+imgExt)

            dRemRank.append("PA100s"+imgExt)
        #arcpy.AddMessage(str(len(dRemRank)))
        if len(dRemRank) > 0:
            FinalRemRanking.save("xxFinalRemRank"+imgExt)
            dRemRank.append("xxFinalRemRank"+imgExt)
            TheFinal = CellStatistics(dRemRank,"MAXIMUM","DATA")
            TheFinal.save(outRemRankName)
        
        else:
            FinalRemRanking.save(outRemRankName)
    else:
        FinalRemRanking.save(outRemRankName)
    crs.write("Final Equal-Weight Ranking for Remnants: "+outRemRankName+"\n")
    

    #Regen
#Added to make sure no areas are unranked
    convSum.append(inPath+"lg_ConvProjOnly"+imgExt)
    sumConvRanks = CellStatistics(convSum,"SUM","DATA")
    sumConvRanks.save("sumConvRanks"+imgExt)
    FinalConvRanking = LegalGeo_Routines_Module.rankVals("sumConvRanks"+imgExt,"finalConv",lgConvPrjOnly,imgExt)
    FinalConvRanking.save(outRegRankName)
    
    
    
    crs.write("*********Step 2b: Weighted Priortization End************\n")
    crs.write("\n")
    crs.close()

    arcpy.AddMessage("Ranking completed.")

    blnArcmap = isArcMap()
    if blnArcmap:

        descWorkspace = arcpy.Describe(outWS)
        if descWorkspace.workspaceType == "FileSystem":
            type = "RASTER_WORKSPACE"
        else:
            type = "FILEGDB_WORKSPACE"
        try:
            mxd = arcpy.mapping.MapDocument('CURRENT')
           
            df = arcpy.mapping.ListDataFrames(mxd)[0] 
            script_path=sys.argv[0]
            symb_dir = os.path.dirname(script_path) + '\\lyrfiles'
            lyr_symb = symb_dir + '\\Remnants_Rank.lyr'
            newlayer1 = arcpy.mapping.Layer(lyr_symb)
            newlayer1.name = remRankName4Arcmap
            newlayer1.replaceDataSource(outWS,type,remRankName4Arcmap)
            arcpy.mapping.AddLayer(df, newlayer1, "TOP")
            #Regen
            lyr_symbReg = symb_dir + '\\Regeneration.lyr'
            newlayerReg = arcpy.mapping.Layer(lyr_symbReg)
            newlayerReg.name = regRankName4Arcmap
            newlayerReg.replaceDataSource(outWS,type,regRankName4Arcmap)
            arcpy.mapping.AddLayer(df, newlayerReg, "TOP")
            arcpy.RefreshActiveView()
            arcpy.RefreshTOC()
        except:
            arcpy.AddWarning("Could not create a layers for ArcMap.")
            arcpy.AddWarning("You will need to add these data manually.")
            arcpy.AddWarning("Remnants ranking: " +outRemRankName)
            arcpy.AddWarning("Regeneration ranking: " +outRegRankName)

                
                
            
    
    
    
except:
		#arcpy.AddMessage("exiting")
		tb = sys.exc_info()[2]
		tbinfo = traceback.format_tb(tb)[0]
		#arcpy.AddMessage("exiting2")
		pymsg = tbinfo + "\n" + str(sys.exc_type)+ ": " + str(sys.exc_value)
		#crs.write("*********Ranking Failed************\n")
		#crs.write(pymsg)
		#crs.write("\n")
		#crs.close()

		arcpy.AddError(pymsg)


finally:
  
    arcpy.AddMessage("Cleaning up temporary files")
    LegalGeo_Routines_Module.deleteLGScratchFiles()
		

				