#Sums distances from converted ranking, size ranking, percent core ranking and fragmenation ranking below
#Creates an overall ranking based on the preceeding listing

#NOTES on ranking remnants
#   LFT 		    GUIDOS
#Rank Category	    Category Rank -- Guidos values
#   1  Patch		Islet 1 -- 9, 109
#                   Branch 10 -- 1, 101
#                   Loops 20 -- 65,165
#                   Bridges 50 -- 33,133 --These would be the corridors
#   60  Edge  	    Edge  60 -- 3,35,67
#   70  Perforated 	Perforated 70 -- 5,105
#   80 Core < 250 acres, roughly 100 ha (both calculated for this) -- 17, 117 for all cores
#   90 Core 250 acres - 500 acres (both calculated for this)
#   100 Core > 500 acres, roughly 200 ha (both calculated for this)
#Need to also get guidos value 100 which are core islands


# import required modules...
import arcpy
from arcpy import env
from arcpy.sa import *
import os
import time
import traceback
import sys
import tempfile
import math
import LegalGeo_Routines_Module


def RunLandscapeMetrics(inPath,outPath,imgExt,nameShpExt,Use_Guidos,distance4Edge,islandSize,Rem_ZI_Dist,cellSize,crs):
    try:
        
        finalSumRemRaster = [outPath+"lgLand_DistRank"+imgExt,outPath+"lgLand_SizeRank"+imgExt,outPath+"lgLand_PerCoreRank"+imgExt] 
        finalSumConvRaster = [outPath+"lgLand_ConvDist2SizeRank"+imgExt,outPath+"lgLand_ConvEdgeRank"+imgExt]

        DistFromConv(inPath,outPath,imgExt)
        crs.write("Distance from Converted:  lgLand_DistRank"+imgExt +"\n")
        
        SizeRem(inPath,outPath,Rem_ZI_Dist,imgExt)
        crs.write("Size of Remnant:  lgLand_SizeRank"+imgExt+"\n")
        crs.write("Proximity to Larger Remnants:  lgLand_ConvDist2SizeRank"+imgExt+"\n")
        crs.write("Remnant Influence Distance = "+str(Rem_ZI_Dist)+ " meters \n")
        
        RankEdgesAndIslands(islandSize,cellSize,inPath,outPath,imgExt,nameShpExt)
        crs.write("All converted areas which are "+str(islandSize)+" sq meters in size or less and completly surrounded by remnant have been ranked 100.\n")
        crs.write("Transition Edge Reduction Ranking includes all islands above scored 100:  lgLand_ConvEdgeRank"+imgExt+"\n")
        #if arcpy.Exists(outPath+"lgLand_ConvIslandsRank"+imgExt):
        #    finalSumConvRaster.append(outPath+"lgLand_ConvIslandsRank"+imgExt) 
        #    crs.write("Converted Islands: lgLand_ConvIslandsRank"+imgExt+"\n")
        #else:
        #    crs.write("No islands less than "+str(islandSize)+" sq meters in size were located in study area. \n")
        
        #RankConvEdges(inPath,outPath,imgExt)
        #crs.write("Transition Edge Reduction:  lgLand_ConvEdgeRank"+imgExt+"\n")
     
        if Use_Guidos == 1 and arcpy.Exists(inPath+"lgLand_guidos"+imgExt):
            crs.write("Used Guidos input layer to rank fragmentation.\n")
            GUIDOS_PerCore_Frag(inPath,outPath,imgExt)
            finalSumRemRaster.append(outPath+"lgLand_FragRank"+imgExt) 
        else:
            LFT_PerCore_Frag(inPath,outPath,imgExt,distance4Edge)
            crs.write("Used internal Landscape Fragmentation analysis with a edge distance of "+str(distance4Edge)+" meters to rank fragmentation.\n")
            finalSumRemRaster.append(outPath+"lgLand_FragRank"+imgExt)
        
        crs.write("Land Fragmentation = lgLand_FragRank"+imgExt+"\n")
        
        if arcpy.Exists (inPath+"lgLand_Other"+imgExt):
            RunOther(inPath,outPath,imgExt)
            if arcpy.Exists(outPath+"lgLand_OtherRank"+imgExt):
                crs.write("Landscape other for remnants:  lgLand_OtherRank"+imgExt+"\n")
                finalSumRemRaster.append(outPath+"lgLand_OtherRank"+imgExt)
            if arcpy.Exists(outPath+"lgLand_ConvOtherRank"+imgExt):
                finalSumConvRaster.append(outPath+"lgLand_ConvOtherRank"+imgExt)
                crs.write("Landscape other for converted lands:  lgLand_ConvOtherRank"+imgExt+"\n")
                        
        #Rem Rankiing
        
        #lgRemsPrjOnly = inPath+"lg_remPrjOnly"+imgExt
        #lgConvPrjOnly = inPath+"lg_ConvProjOnly"+imgExt 
        
        sumAllRems4Shape = CellStatistics(finalSumRemRaster,"SUM","DATA")
        sumAllRems4Shape.save("xxlg_sumAllRems4Shape"+imgExt)
        ToRankRemShape = Times(inPath+"lg_remPrjOnly"+imgExt,sumAllRems4Shape)
        ToRankRemShape.save("xxlg_ToRankRemShape"+imgExt) 
        FinalRankRemShape = Slice("xxlg_ToRankRemShape"+imgExt,100,"NATURAL_BREAKS",1)

        FinalRankRemShape.save("xxlg_FinalRakRemShape"+imgExt)
        FinalRankRemShapeSave= LegalGeo_Routines_Module.scaleUp("xxlg_FinalRakRemShape"+imgExt,100)
        FinalRankRemShapeSave.save(outPath+"lgLandAll_RemRank"+imgExt) 
        crs.write("Final Remnant Landscape Layer:  lgLandAll_RemRank"+imgExt)
        crs.write("\n")
        
        #Conv Ranking
       
        sumConvLandscape = CellStatistics(finalSumConvRaster,"SUM","DATA")
        sumConvLandscape.save("xxlg_SumConvLandscape"+imgExt)
        FinalRankConvLandscape = Slice("xxlg_SumConvLandscape"+imgExt,100,"NATURAL_BREAKS",1) 
        
        FinalRankConvLandscape.save("xxlg_FinalRankConvLandscape"+imgExt)
        FinalRankConvLandscapeSave = LegalGeo_Routines_Module.scaleUp("xxlg_FinalRankConvLandscape"+imgExt,100)
        FinalRankConvLandscapeSave.save(outPath+"lgLandAll_ConvRank"+imgExt)
        crs.write("Final Converted Lands Landscape Layer:  lgLandAll_ConvRank"+imgExt)
        crs.write("\n")
    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)        
        
         


def DistFromConv(inPath,outPath,imgExt):
        arcpy.AddMessage("-->Ranking remnants based on distance from converted.")
        distFromConv = EucDistance(inPath+"lg_converted"+imgExt)
        distFromConv.save("xxlg_distFromCon"+imgExt)
        distFromConvWOZero = Con(distFromConv,distFromConv,"","VALUE > 0")
        distFromConvWOZero.save("xxlg_distFromConvWOZero"+imgExt)
        distConRemsOnly = Times("xxlg_distFromConvWOZero"+imgExt,inPath+"lg_remPrjOnly"+imgExt)
        distConRemsOnly.save("xxlg_distConRemsOnly"+imgExt)
        distFromConvRank = Slice("xxlg_distConRemsOnly"+imgExt,100,"NATURAL_BREAKS",1)
        distFromConvRank.save("xxlg_distRank"+imgExt)
        distFromConvRankSave = LegalGeo_Routines_Module.scaleUp("xxlg_distRank"+imgExt,100)
        distFromConvRankSave.save(outPath+"lgLand_DistRank"+imgExt)

def SizeRem(inPath,outPath,Rem_ZI_Dist,imgExt):
        arcpy.AddMessage("-->Ranking remnants on size")
        #need for legal calculations
        remSize = Lookup(inPath+"lg_REMs"+imgExt,"Count")
        remSize.save("xxlg_remSizeInCells"+imgExt)
        #Changed so ranked on log of size
        remSizeLn = Ln("xxlg_remSizeInCells"+imgExt)
        remSizeLn.save("xxlg_remSizeLn"+imgExt)
        remSize2Rank = Times("xxlg_remSizeLn"+imgExt,inPath+"lg_remPrjOnly"+imgExt)
        remSize2Rank.save("xxlg_remSize2Rank"+imgExt)
        sizeRank = Slice("xxlg_remSize2Rank"+imgExt,100,"NATURAL_BREAKS",1)
        sizeRank.save("xxlg_sizeRank"+imgExt)
        sizeRankSave = LegalGeo_Routines_Module.scaleUp("xxlg_sizeRank"+imgExt,100)
        sizeRankSave.save(outPath+"lgLand_SizeRank"+imgExt)
        
        #For converted lands
        arcpy.AddMessage("-->Ranking converted lands based on proximity to largest remnants.")
        input4WD = Plus(Int(Times("xxlg_remSizeLn"+imgExt,10)),1)
        input4WD.save("xxlg_remSizeConvInput"+imgExt)
        #2000 m distance from existing remnant ranked
        convWdRemSize = LegalGeo_Routines_Module.WeightedDistVeg("xxlg_remSizeConvInput"+imgExt,"ConvSize",Rem_ZI_Dist,imgExt)
        convWdRemSize.save("xxlg_convWdRemSize"+imgExt)

        #Raster "xxlg_ConvSize_distOnly" created in Weighted distance routine, needed to rank only areas within set distance
        convwdRemSize2Rank = Times(inPath+"lg_ConvProjOnly"+imgExt,"xxlg_convWdRemSize"+imgExt)
        convwdRemSize2Rank.save("xxlg_convwdRemSize2Rank"+imgExt)
        finalSizeRem = Slice("xxlg_convwdRemSize2Rank"+imgExt,100,"NATURAL_BREAKS",1)
        finalSizeRem.save("xxlg_ConvDist2Rank"+imgExt)
        finalSizeRemSave = LegalGeo_Routines_Module.scaleUp("xxlg_ConvDist2Rank"+imgExt,100)
        finalSizeRemSave.save(outPath+"lgLand_ConvDist2SizeRank"+imgExt)

               
        
def RankEdgesAndIslands(islandSize,cellSize,inPath,outPath,imgExt,nameShpExt):
    arcpy.AddMessage("-->Identifying Converted Patches within Natural Remenants with a size less than "+str(islandSize)+" sq meters.")
    arcpy.RasterToPolygon_conversion(inPath+"lg_REM_Ones"+imgExt,"xxlg_natpoly"+nameShpExt,"NO_SIMPLIFY","Value")
    arcpy.RasterToPolygon_conversion(inPath+"lg_converted"+imgExt,"xxlg_convpoly"+nameShpExt,"NO_SIMPLIFY","Value")
    arcpy.EliminatePolygonPart_management("xxlg_natpoly"+nameShpExt,"xxlg_natfull"+nameShpExt,"AREA", islandSize,"0","CONTAINED_ONLY")
    arcpy.MakeFeatureLayer_management("xxlg_convpoly"+nameShpExt,"convlayer")
    arcpy.SelectLayerByLocation_management("convlayer","COMPLETELY_WITHIN","xxlg_natfull"+nameShpExt)
    results = arcpy.GetCount_management("convlayer")
    matchcount = int(results.getOutput(0))
    #arcpy.AddMessage(str(matchcount))
    if matchcount > 0:
        #Cant believe it but default raster to feature creates 'grid_code' field for geodatabase raster and 'GRIDCODE' field for imgs---This was for arcmap 10.2 check on for imgs in 10.3
        fldName = "GRIDCODE"
        gridFld = arcpy.ListFields("xxlg_convpoly"+nameShpExt,fldName)
        if len(gridFld) == 0:
            fldName = "grid_code"
            
        arcpy.FeatureToRaster_conversion("convlayer",fldName,"xxlg_core_islands1"+imgExt,cellSize)
        
        coreIslands = Times("xxlg_core_islands1"+imgExt,100)
        coreIslands.save("xxlg_coreIslands"+imgExt)
        #finalIslandCoreOnly = Times("xxlg_coreIslands"+imgExt,inPath+"lg_ConvProjOnly"+imgExt)
        #finalIslandCoreOnly.save(outPath+"lgLand_ConvIslandsRank"+imgExt)
    else:
        arcpy.AddMessage("-->No islands found at set size.")
    

    #May help but I don't want to make everything in_memory and have to change code 
    #arcpy.Delete_management("convlayer")
    #arcpy.Delete_management("in_memory"+"\\"+"xxlg_convpoly")
    
    arcpy.AddMessage("-->Ranking converted lands based on edge shape.")
    remEdge2Rank = LegalGeo_Routines_Module.newFocalDist(inPath+"lg_REM_Ones"+imgExt,"ConvEdge",imgExt)
    remEdge2Rank.save("xxlg_Land_ConvEdge"+imgExt)
    convEdge = Times(inPath+"lg_ConvProjOnly"+imgExt,"xxlg_Land_ConvEdge"+imgExt)
    convEdge.save("xxlg_LandConvEdge2rank"+imgExt)
    edgeRank = Slice("xxlg_LandConvEdge2rank"+imgExt,100,"NATURAL_BREAKS",1)
    edgeRank.save("xxlg_edgeRank"+imgExt)
    convEdgeSU = LegalGeo_Routines_Module.scaleUp("xxlg_edgeRank"+imgExt,100)
    convEdgeSU.save("xxlg_convEdgeSu"+imgExt)
    convEdgeSave = CellStatistics(["xxlg_convEdgeSu"+imgExt,"xxlg_coreIslands"+imgExt],"MAXIMUM","DATA")
    convEdgeSave.save(outPath+"lgLand_ConvEdgeRank"+imgExt)
        
def LFT_PerCore_Frag (inPath,outPath,imgExt,edgeWidth):

        lgRemOnes = inPath + "lg_REM_Ones"+imgExt
        lgConv = inPath + "lg_converted"+imgExt

        desc = arcpy.Describe(lgRemOnes)    # describe object
        cellsize = desc.MeanCellHeight
        spatRef = desc.SpatialReference
        units = spatRef.LinearUnitName         
        arcpy.AddMessage("-->Using Landscape Fragmentation Tool to rank fragmentation and percent core of remnants")
        f_buf = EucDistance(lgRemOnes, edgeWidth, cellsize)
        f_buf.save("xxlg_f_buf"+imgExt)
 
        # extract fragmenting class periphery (1) and core (2)...
        remap = "0 NoData;0 %s 1;NoData 2" % edgeWidth


        nf_peri_core = Reclassify(f_buf, "Value", remap, "data")
        nf_peri_core.save("xxlg_nf_peri_core"+imgExt)

        # region group fragmenting class...
        nf_grp = RegionGroup(lgConv, "EIGHT", "WITHIN")
        nf_grp.save("xxlg_nf_grp"+imgExt)

        # identify fragmenting class groups as core or periphery.
        nf_core_peri_grps = ZonalStatistics(nf_grp, "VALUE", nf_peri_core, "MAXIMUM", "DATA")
        nf_core_peri_grps.save("xxlg_nf_core_peri_grps"+imgExt)



        nf_core = Reclassify("xxlg_nf_core_peri_grps"+imgExt, "Value", "2 1", "NODATA")
        nf_core.save("xxlg_nf_core"+imgExt)


        # buffer fragementing class core groups by width of edge zone...
        #arcpy.AddMessage("EucDist")
        nf_core_buf = EucDistance("xxlg_nf_core"+imgExt, edgeWidth, cellsize, "")
        nf_core_buf.save("xxlg_nf_core_buf"+imgExt)

        # extract edge forest (1)...
        remap = "0 NODATA;0 %s 1;NODATA 0" % edgeWidth
        edge = Reclassify("xxlg_nf_core_buf"+imgExt, "Value", remap, "DATA")
        edge.save("xxlg_edge"+imgExt)

        #arcpy.AddMessage("what")    
        #arcpy.AddMessage("...EDGE FRAGMENTATION IDENTIFIED")
        # print "EDGE FRAGMENTATION IDENTIFIED"

        #---------------------------------------------------
        # EXTRACT PATCH, CORE, AND PERIPHERY OF FRAGMENTED CLASS...

        # buffer fragmenting class by width of edge zone...
        # arcpy.AddMessage("eucdistance2")
        nf_buf = EucDistance(lgConv, edgeWidth, cellsize,"")
        nf_buf.save("xxlg_nf_buf"+imgExt)

        # extract core and periphery of fragmented class...
        remap = "0 NoData;0 %s 2;NoData 4" % edgeWidth
        f_peri_core = Reclassify(nf_buf, "Value", remap, "NODATA")  
        f_peri_core.save("xxlg_f_peri_core"+imgExt)

        # region group fragmented class...
        f_grp = RegionGroup(lgRemOnes, "FOUR", "WITHIN")
        f_grp.save("xxlg_f_grp"+imgExt)
        


        # identify fragmented class groups as core or periphery...
        f_core_peri_grps = ZonalStatistics(f_grp, "VALUE", f_peri_core, "MAXIMUM", "DATA")
        f_core_peri_grps.save("xxlg_f_core_peri_grps"+imgExt)

        # extract patch forest (0)...
        remap = "2 0;4 1;NoData 1"
        patch0_1 = Reclassify(f_core_peri_grps, "Value", remap, "NODATA") 
        patch0_1.save("xxlg_patch0_1"+imgExt)

        #arcpy.AddMessage("...INTERIOR, PATCH, AND PERFORATED FRAGMENTATION IDENTIFIED")

        #---------------------------------------------------
        # COMBINE FRAGMENTATION CLASSES AND CREATE FINAL FRAGMENTATION MAP...
        # Replace a layer/table view name with a path to a dataset (which can be a layer file) or create the layer/table view within the script
        # The following inputs are layers or table views: "f_peri_core", "edge"
        # combine fragmented class edge, core, and perforated...

        nonPatch = Plus("xxlg_f_peri_core"+imgExt,"xxlg_edge"+imgExt)

        # combine non-patch classes with patch - for fragemented class...
        nonPatch.save("xxlg_fragnPatch"+imgExt)


        fragMap1 = Times("xxlg_fragnPatch"+imgExt,"xxlg_patch0_1"+imgExt)
        fragMap1.save("xxlg_fragMap1"+imgExt)

        # reclassify patch forest to 1...
        #added this so the final will be similar to correct ranking
        fragMap2 = Reclassify(fragMap1, "Value", "0 1;2 3;3 2", "DATA") 
        fragMap2.save("xxlg_fragMap2"+imgExt)

        fragMap2_f = Times("xxlg_fragMap2"+imgExt,lgRemOnes)
        #Need to check this to make sure it works
        fragMap2_f.save("xxlg_fragMap2_f"+imgExt)


        #Final Frag Map = fragMap2_f.img
        #Now should be #1=patch, 2=edge, 3=perforated, 4 = core

        # CLASSIFY CORE FOREST BASED ON PATCH SIZE


        #arcpy.env.workspace = TempWS

        #arcpy.AddMessage("...CATEGORIZING CORE FOREST PATCHES...")
        #print "CATEGORIZING CORE FOREST PATCHES..."
        whereClause = "VALUE = 4"
        core_1 = Con("xxlg_fragMap2_f"+imgExt,1,"",whereClause) 
        core_1.save("xxlg_core_habitat"+imgExt)
        
        #Added to calculate percent core values
        whereClause = "Value > 1 and Value <4"
        allEdges = Con(fragMap2_f,1,"",whereClause) 
        allEdges.save("xxlg_allEdges"+imgExt)

        sumCore = ZonalStatistics("xxlg_f_grp"+imgExt,"Value","xxlg_core_habitat"+imgExt,"SUM","DATA")
        sumCore.save("xxlg_sumCores"+imgExt)
        sumEdges = ZonalStatistics("xxlg_f_grp"+imgExt,"Value","xxlg_allEdges"+imgExt,"SUM","DATA")
        sumEdges.save("xxlg_sumEdges"+imgExt)

        perFloatwithCoreOnly = Float(Times(Divide("xxlg_sumCores"+imgExt,Plus("xxlg_sumCores"+imgExt,"xxlg_sumEdges"+imgExt)),100))
        perFloatwithCoreOnly.save("xxlg_perFloatWithCoreOnly"+imgExt)

        #Dont need because 0 gets ranked to 1 withother low numbers just keep to 0
        #whereClause = "VALUE > 0"
        #remZeros = Con(fragMap2_f,0,"",whereClause) 
        #remZeros.save("xxlg_remZeros"+imgExt)
        
        #perFloat = CellStatistics(["xxlg_perFloatWithCoreOnly"+imgExt,"xxlg_remZeros"+imgExt],"SUM","DATA")
        #perFloat.save("xxlg_perFloat"+imgExt)
        perCoreRankTimes= Times("xxlg_perFloatWithCoreOnly"+imgExt,inPath+"lg_remPrjOnly"+imgExt)
        perCoreRankTimes.save("xxlg_perCoreTimes"+imgExt)
        perCoreRank = Slice("xxlg_perCoreTimes"+imgExt,100,"NATURAL_BREAKS",1)
        perCoreRank.save("xxlg_PerCoreRank"+imgExt)
        perCoreRankSave = LegalGeo_Routines_Module.scaleUp("xxlg_PerCoreRank"+imgExt,100)
        perCoreRankSave.save(outPath+"lgLand_PerCoreRank"+imgExt)               

        core_grp = RegionGroup("xxlg_core_habitat"+imgExt, "EIGHT", "WITHIN","NO_LINK","#")
        core_grp.save("xxlg_core_grp"+imgExt)

        
        coreGrpSize = Lookup("xxlg_core_grp"+imgExt,"Count")
        coreGrpSize.save("xxlg_coreGrpSize"+imgExt)

        if "Foot" in units:
            cf = 1              # no correction needed
            bufferCF = 3.2808  
        else:
            cf = 3.2808          # correction factor to convert meters to feet
            bufferCF = 1

        
   #HERE*****************************************     
        #Got rid of a bunch of stuff which sets core sizes based on area check original if you want to do this
        highCellCount = int(500 * 43560 / (cellsize*cf)**2)  #500 acres = roughly 200 hectares at 30m resolution data this would be 2248 cells
        medCellCount =  highCellCount/2 #int(250 * 43560 /(cellsize*cf)**2)  #roughly 100 hectares 
        
        remap = "1 %s 4;%s %s 5" % (medCellCount,medCellCount+1,highCellCount)
        coreRanksFirst = Reclassify("xxlg_coreGrpSize"+imgExt,"Value",remap,"DATA")
        coreRanksFirst.save("xxlg_coreRanksFirstTwo"+imgExt)
        #arcpy.AddMessage("Here")
        coreRanksFinal = Con("xxlg_coreRanksFirstTwo"+imgExt,6,"xxlg_coreRanksFirstTwo"+imgExt,"Value > 5")
        coreRanksFinal.save("xxlg_coreRanksFinal"+imgExt)
        finalLFT = CellStatistics(["xxlg_coreRanksFinal"+imgExt,"xxlg_fragMap2_f"+imgExt],"MAXIMUM","DATA")
        finalLFT.save("xxlg_finalLFTout"+imgExt)
        
        #RankingLFT = Con(finalLFT,Plus(finalLFT,4),1,"Value > 1")
        #RankingLFT.save("xxlg_RankingLFT"+imgExt)
        LftRankRemOnly = Times("xxlg_finalLFTout"+imgExt,inPath+"lg_remPrjOnly"+imgExt)
        LftRankRemOnly.save("xxlg_LftFragRemsOnly"+imgExt)
        remap = "1 1;2 60;3 70;4 80;5 90;6 100"
        finalLFTrank = Reclassify("xxlg_LftFragRemsOnly"+imgExt,"Value",remap,"NODATA")
        #finalLFTrank = LegalGeo_Routines_Module.scaleUp("xxlg_LftFragRemsOnly"+imgExt,100)
        finalLFTrank.save(outPath+"lgLand_FragRank"+imgExt)
         

def GUIDOS_PerCore_Frag (inPath,outPath,imgExt):        
        arcpy.AddMessage("-->Using Guidos output to rank fragmentation and percent core of remnants")
        lgRemOnes = inPath+"lg_REM_Ones"+imgExt
        lgGuidos = inPath+"lgLand_guidos"+imgExt
        
        desc = arcpy.Describe(lgRemOnes)    # describe object
        cellsize = desc.MeanCellHeight
        spatRef = desc.SpatialReference
        units = spatRef.LinearUnitName          
        
        remap = "9 1;109 1;1 2;101 2;65 3;165 3;33 5;133 5;3 6;103 6;35 6;67 6;167 7;5 7;105 7; 69 7;169 7;37 7;137 7;17 8;117 8"
        GuidosRemapped = Reclassify(lgGuidos,"Value",remap,"NODATA")
        GuidosRemapped.save("xxlg_guidosRemapped"+imgExt)
        
        
        GuidosCoresOnly = Con("xxlg_guidosRemapped"+imgExt,1,"","Value = 8")
        GuidosCoresOnly.save("xxlg_core_habitat"+imgExt)
        
        whereClause = "Value > 5 and Value < 8"
        allEdges = Con("xxlg_guidosRemapped"+imgExt,1,"",whereClause)
        allEdges.save("xxlg_allEdges"+imgExt)
        
        # region group fragmented class...
        f_grp = RegionGroup(lgRemOnes, "FOUR", "WITHIN")
        f_grp.save("xxlg_f_grp"+imgExt)  

#Start of calculating percent core SHAPE**********        
        sumCore = ZonalStatistics("xxlg_f_grp"+imgExt,"Value","xxlg_core_habitat"+imgExt,"SUM","DATA")
        sumCore.save("xxlg_sumCores"+imgExt)
        sumEdges = ZonalStatistics("xxlg_f_grp"+imgExt,"Value","xxlg_allEdges"+imgExt,"SUM","DATA")
        sumEdges.save("xxlg_sumEdges"+imgExt)

        perFloatwithCoreOnly = Float(Times(Divide("xxlg_sumCores"+imgExt,Plus("xxlg_sumCores"+imgExt,"xxlg_sumEdges"+imgExt)),100))
        perFloatwithCoreOnly.save("xxlg_perFloatWithCoreOnly"+imgExt)
        
        perCorePrjOnly = Times("xxlg_perFloatWithCoreOnly"+imgExt,inPath+"lg_remPrjOnly"+imgExt)
        perCorePrjOnly.save("xxlg_perCorePrjOnly"+imgExt)

        perCoreRank = Slice("xxlg_perCorePrjOnly"+imgExt,100,"NATURAL_BREAKS",1)
        
        perCoreRank.save("xxlg_PerCoreRank"+imgExt)
        perCoreRankSave = LegalGeo_Routines_Module.scaleUp("xxlg_PerCoreRank"+imgExt,100)
        perCoreRankSave.save(outPath+"lgLand_PerCoreRank"+imgExt)         

        
        
        core_grp = RegionGroup("xxlg_core_habitat"+imgExt, "EIGHT", "WITHIN","NO_LINK","#")
        core_grp.save("xxlg_core_grp"+imgExt)

        
        coreGrpSize = Lookup("xxlg_core_grp"+imgExt,"Count")
        coreGrpSize.save("xxlg_coreGrpSize"+imgExt)

        

#Calculating values for ranking based on guidos value Fragmentation Rank****************************************************
        if "Foot" in units:
            cf = 1              # no correction needed
            bufferCF = 3.2808 
        else:
            cf = 3.2808          # correction factor to convert meters to feet
            bufferCF = 1
        # if units are not in feet or meters, full analysis cannot be completed - exit script...

        highCellCount = int(500 * 43560 / (cellsize*cf)**2)  #500 acres = roughly 200 hectares at 30m resolution data this would be 2248 cells
        medCellCount =  highCellCount/2 #int(250 * 43560 /(cellsize*cf)**2)  #roughly 100 hectares 
        
        remap = "1 %s 8;%s %s 9" % (medCellCount,medCellCount+1,highCellCount)        
        coreRanksFirst = Reclassify("xxlg_coreGrpSize"+imgExt,"Value",remap,"DATA")
        coreRanksFirst.save("xxlg_coreRanksFirstTwo"+imgExt)
        coreRanksFinal = Con(coreRanksFirst,10,coreRanksFirst,"Value > 9")
        coreRanksFinal.save("xxlg_coreRanksFinal"+imgExt)
        
        guidosFinalRank = CellStatistics(["xxlg_coreRanksFinal"+imgExt,"xxlg_guidosRemapped"+imgExt],"MAXIMUM","DATA")
        guidosFinalRank.save("xxlg_GuidosAllRank"+imgExt)
        guidosRankRemOnly = Times("xxlg_GuidosAllRank"+imgExt,inPath+"lg_remPrjOnly"+imgExt)
        guidosRankRemOnly.save("xxlg_GuidosRemRank"+imgExt)
        
        remap = "1 1;2 10;3 20;5 50;6 60;7 70;8 80;9 90;10 100"
        guidosFinalRankSave = Reclassify("xxlg_GuidosRemRank"+imgExt,"Value",remap,"NODATA")
        #guidosFinalRankSave = LegalGeo_Routines_Module.scaleUp("xxlg_GuidosRemRank"+imgExt,100)
        guidosFinalRankSave.save(outPath+"lgLand_FragRank"+imgExt)

        
def RunOther(inPath,outPath,imgExt):
        #arcpy.AddMessage("-->Runnning Other Landscape Metric")
        intOtherLand = LegalGeo_Routines_Module.createInt(inPath+"lgLand_Other"+imgExt)
        intOtherLand.save("intOtherLand"+imgExt)  
        
        #Remnants
        otherRem = Times("intOtherLand"+imgExt,inPath+"lg_remPrjOnly"+imgExt)
        otherRem.save("xxlg_LandOtherRem"+imgExt)
        if LegalGeo_Routines_Module.testRaster("xxlg_LandOtherRem"+imgExt):
            arcpy.AddMessage("-->Runnning Other Landscape Metric for Remmants") 
            otherSlice = Slice("xxlg_LandOtherRem"+imgExt,100,"NATURAL_BREAKS",1)
            otherSlice.save("xxlg_landOtherSlice"+imgExt)
            otherRanking = LegalGeo_Routines_Module.scaleUp("xxlg_landOtherSlice"+imgExt,100)
            otherRanking.save(outPath+"lgLand_OtherRank"+imgExt)           

        #Converted
        otherConv = Times("intOtherLand"+imgExt,inPath+"lg_ConvProjOnly"+imgExt)
        otherConv.save("xxlg_LandOtherConv"+imgExt)
        if LegalGeo_Routines_Module.testRaster("xxlg_LandOtherConv"+imgExt):
            arcpy.AddMessage("-->Runnning Other Landscape Metric for Converted Lands") 
            otherSlice = Slice("xxlg_LandOtherConv"+imgExt,100,"NATURAL_BREAKS",1)
            otherSlice.save("xxlg_landConvOtherSlice"+imgExt)
            otherRanking = LegalGeo_Routines_Module.scaleUp("xxlg_landConvOtherSlice"+imgExt,100)
            otherRanking.save(outPath+"lgLand_ConvOtherRank"+imgExt)           
        
        
        
 