import arcpy
from arcpy import env
from arcpy.sa import *
import os
import traceback
import sys
import tempfile
import LegalGeo_Routines_Module

class NoRemnantsError (Exception):
    pass
class PageLayoutError(Exception):
    pass

class LicenseError(Exception):
    pass

class SpatialRefProjErrorMap (Exception):
    pass

class SpatialRefProjErrorRemFC (Exception):
    pass

class matchingSpRefsError (Exception):
    pass

class BoundaryProjError (Exception):
    pass

class RasterSprefError (Exception):
    pass
   
def CopyFeatures(inFeats,outFeatsName,outWorkspaceType):
    if outWorkspaceType == "FileSystem":
        arcpy.CopyFeatures_management(inFeats,outFeatsName)
    else:
        desc = arcpy.Describe(inFeats)
        path  = desc.path
        wdDesc = arcpy.Describe(path)
        if wdDesc.dataType <> "Workspace":
          wdDesc = arcpy.Describe(wdDesc.path)
          
        inworkspaceType = wdDesc.workspaceType
        if inworkspaceType == "Filesystem":
            arcpy.CopyFeatures_management(inFeats,outFeatsName)
        else:
            #This doesn't work in code so have to copy to scracth folder first and then to geodatbase
            #scrathFold = arcpy.env.scratchFolder
            tmpName = arcpy.env.scratchFolder+"\\xxlg_tmp.shp"
            outcopy = arcpy.CopyFeatures_management(inFeats,tmpName)
            arcpy.CopyFeatures_management(tmpName,outFeatsName)
            
            
 
def Write2InputNotes(desc,parameterName,openTxtFile):
    
    fullPath = desc.catalogPath
    openTxtFile.write(parameterName+" source data:  "+fullPath+"\n")
    openTxtFile.write("\n")
    

try:
    #Check for spatial analyst license

    if arcpy.CheckExtension("Spatial") == "Available":
        arcpy.CheckOutExtension("Spatial")
    else:
        raise LicenseError
    #Get Variables
    project_folder = arcpy.GetParameterAsText(0)
    outputType = arcpy.GetParameterAsText(1)
    cellsize = arcpy.GetParameterAsText(2)
    study_area = arcpy.GetParameterAsText(3)
    remnants = arcpy.GetParameterAsText(4)

    #Biodiversity
    natVeg = arcpy.GetParameterAsText(5)
    vegTypeFldName = arcpy.GetParameterAsText(6)
    vegRankFldName = arcpy.GetParameterAsText(7)
    biodiversityRankFldName =  arcpy.GetParameterAsText(8) 

    #Environmental Services
    activeRiverAreas = arcpy.GetParameterAsText(9)
    fragileAreas = arcpy.GetParameterAsText(10)
    springs = arcpy.GetParameterAsText(11)
    otherES = arcpy.GetParameterAsText(12)   

    #Landscape  
    guidos = arcpy.GetParameterAsText(13)
    otherLandscape = arcpy.GetParameterAsText(14)
    waterbodies = arcpy.GetParameterAsText(15)

    #Legal  
    LRs = arcpy.GetParameterAsText(16)  
    PPAs = arcpy.GetParameterAsText(17)
    PAs = arcpy.GetParameterAsText(18)
    CPAs = arcpy.GetParameterAsText(19)
    PriorityFldCPA = arcpy.GetParameterAsText(20)
    LegalOther = arcpy.GetParameterAsText(21)
    PriorityFldLegalOther = arcpy.GetParameterAsText(22)

    #Threats 
    accessibilityRaster = arcpy.GetParameterAsText(23)
    otherThreatRaster = arcpy.GetParameterAsText(24)



    DesignatedRasters = [9,10,11,13,14,23,24]

    rasterCheck = []
    for dr in DesignatedRasters:
        drParam = arcpy.GetParameterAsText(dr)
    if arcpy.Exists(drParam):
        rasterCheck.append(drParam)


    remDesc = arcpy.Describe(remnants)
    arcpy.env.outputCoordinateSystem = remDesc.spatialReference

    if remDesc.DataType == "FeatureLayer":
        mxd = arcpy.mapping.MapDocument("CURRENT")
        if mxd.activeView == "PAGE_LAYOUT":
          raise PageLayoutError     
        df = arcpy.mapping.ListDataFrames(mxd, mxd.activeView)[0]
        if df.spatialReference.name != remDesc.spatialReference.name:
          raise SpatialRefProjErrorMap


    units = arcpy.env.outputCoordinateSystem.linearUnitName
    if "Meter" in units:
        outUnit = "Meters"
    else:
        arcpy.AddMessage("Current application only supoorts using cordinate systems having linear units of meters")
        raise SpatialRefProjErrorRemFC

    spTest = 0  
    wrongSPref = ""
    if len(rasterCheck) > 0:
        for r in rasterCheck:
            rDesc = arcpy.Describe(r)
            if remDesc.spatialReference.name != rDesc.spatialReference.name:
                spTest += 1
                if spTest == 1:
                    wrongSPref+=r
                    word = " raster"
                else:
                    wrongSPref+=", "+r
                    word = " rasters"
    if spTest > 0:
        arcpy.AddError(wrongSPref+word+" need to have the same spatial reference as the selected remnants layer.")
        raise RasterSprefError
    update = False    
    if outputType == "ESRI File Geodatabase":
        if not(arcpy.Exists(project_folder+"\\lg_input.gdb")):
            update = True
            arcpy.CreateFileGDB_management(project_folder,"lg_input.gdb")
            arcpy.CreateFileGDB_management(project_folder,"lg_output.gdb")
        env.workspace = project_folder+"\\lg_input.gdb"
        

    else:
        if not(arcpy.Exists(project_folder+"\\lg_input")):
            update = True
            arcpy.CreateFolder_management(project_folder,"lg_input")
            arcpy.CreateFolder_management(project_folder,"lg_output")
        env.workspace = project_folder+"\\lg_input"
        


    #Setting Enviornmental Variables
    env.overwriteOutput = 1
    env.scratchWorkspace = env.workspace      

    #cellSize = LegalGeo_Routines_Module.returnLinUnits(cellsizeUnits,outUnit)
    cellSize = long(cellsize)
    env.cellSize = cellSize
    #env.extent = remnants   # Needs to be this due to analysis may go outside of boundary===============REALLY NEED TO DIAL THIS IN MORE++++++++++++++

     
    wsDesc = arcpy.Describe(arcpy.env.workspace)
    nameShpExt = ""
    imgExt = ""

    if wsDesc.workspaceType == "FileSystem":
        nameShpExt=".shp"
        imgExt =".img"

  


  



    arcpy.AddMessage("Creating Remnant Input......")
    if remDesc.DataType != "FeatureLayer":
      remnantsLayer = "remnants"
      arcpy.MakeFeatureLayer_management(remnants,remnantsLayer)
    else:
      remnantsLayer  = remnants



    projectBND = "lg_Bnd_Feats" + nameShpExt
    wsType = wsDesc.workspaceType
    saDesc = arcpy.Describe(study_area)
    #arcpy.AddMessage(wsType)
    #Needed this due to copy from geodatabase to geodatabase doesn't work. Need to test for folder
    CopyFeatures(study_area,projectBND,wsType)
    bndDesc = arcpy.Describe(projectBND)
    bndExtentPoly = LegalGeo_Routines_Module.getPolyfromExt(bndDesc.extent)
    
     
    arcpy.SelectLayerByLocation_management(remnantsLayer,"intersect", projectBND)
    matchcount = int(arcpy.GetCount_management(remnantsLayer).getOutput(0))
    if matchcount == 0:
      raise NoRemnantsError

      
    inputFN = os.path.join(project_folder+os.sep,"lg_analysis_log.txt")
    inputTxtFile = file(inputFN,'wt')
    crs = open(inputFN,'a')
    if update == True:
        crs.write("*********Project Setup Update************\n")
    else:
        crs.write("*********Project Setup************\n")
    crs.write("\n")
    crs.write("Project Folder Location: " +project_folder+"\n")
    crs.write("Data Output Type: " +outputType+"\n")
    crs.write("Raster Resolution: " +cellsize+"\n")    
    crs.write("Project Projection = " +remDesc.spatialReference.name+"\n")
    crs.write("\n")
    Write2InputNotes(saDesc,"Project Study Area",crs)
    Write2InputNotes(remDesc,"Remnants",crs)  
      
      

    remnantLayer = "lg_rem_feats" + nameShpExt
    #Need to make sure polygons touching are combined into one remnant 
    #Do need to make sure complete remnants (e.g. when remnants are subdived by veg type)
    arcpy.Dissolve_management(remnantsLayer,remnantLayer,"#","#","SINGLE_PART","DISSOLVE_LINES")
    #arcpy.CopyFeatures_management(remnantsLayer,remnantLayer)
    #this needs to be set to union of boundary and remnantLayer
    remDissolveDesc = arcpy.Describe("lg_rem_feats" + nameShpExt)
    remDissolveExtPoly = LegalGeo_Routines_Module.getPolyfromExt(remDissolveDesc.extent)
    combinePoly = remDissolveExtPoly.union(bndExtentPoly)
    env.extent = combinePoly.extent


    fieldList = arcpy.ListFields(remnantLayer,"","OID")
    fieldName = fieldList[0].name
    arcpy.AddField_management(remnantLayer,"XXid","LONG")
    arcpy.CalculateField_management(remnantLayer,"XXid","!"+fieldName+"!","PYTHON_9.3") 
    remRaster = "lg_REMs"+imgExt #RegionGroup for MM's code
    arcpy.PolygonToRaster_conversion(remnantLayer,"XXid",remRaster,"MAXIMUM_COMBINED_AREA","",cellSize)
    env.snapRaster = remRaster
    whereClause = "Value >= 0"
    remEvalRaster = Con(remRaster,1,"",whereClause)
    remEvalRaster.save("lg_REM_Ones"+imgExt)  #Also Natural lands in landscape
    arcpy.SelectLayerByAttribute_management(remnantsLayer,"CLEAR_SELECTION")


    #Create boundary only raster
    arcpy.AddField_management(projectBND,"xx_ID","LONG")
    arcpy.CalculateField_management(projectBND,"xx_ID","1","VB","#")
    bndRaster = "lg_bnd_ones"+imgExt
    arcpy.PolygonToRaster_conversion(projectBND,"xx_ID",bndRaster,"MAXIMUM_COMBINED_AREA","",cellSize)




    #Landscape setup  
    #Creating waterbody grid
    waterInBnd = False
    if arcpy.Exists(waterbodies):
        
        watbodyDesc = arcpy.Describe(waterbodies)
        
        if watbodyDesc.DataType != "FeatureLayer":
          watbodyLayer = "watbodyLayer"
          arcpy.MakeFeatureLayer_management(waterbodies,watbodyLayer)
        else:
          watbodyLayer = waterbodies
        
        arcpy.SelectLayerByLocation_management(watbodyLayer,"intersect", combinePoly)
        matchcount = int(arcpy.GetCount_management(watbodyLayer).getOutput(0))
        if matchcount != 0:
          waterInBnd = True
          fieldList = arcpy.ListFields(watbodyLayer,"","OID")
          fieldName = fieldList[0].name
          waterRaster = "xxlg_WaterBodies"+imgExt
          arcpy.PolygonToRaster_conversion(watbodyLayer,fieldName,waterRaster,"MAXIMUM_COMBINED_AREA","",cellSize)
          whereClause = "Value >= 0"
          waterMask = Con(waterRaster,1,"",whereClause)
          waterMask.save("lg_WaterMask"+imgExt) 
        arcpy.SelectLayerByAttribute_management(watbodyLayer,"CLEAR_SELECTION")
        
    #Created for update capablities, user may not include water boundaries but still want to use it
    if arcpy.Exists("lg_WaterMask"+imgExt):
      xxlg_combine = CellStatistics(["lg_REM_Ones"+imgExt,"lg_WaterMask"+imgExt],"MINIMUM","DATA")
      xxlg_combine.save("xxlg_combine"+imgExt)
      lg_Converted = Con(IsNull("xxlg_combine"+imgExt),1)
    else:
      lg_Converted = Con(IsNull("lg_REM_Ones"+imgExt),1)

    lg_Converted.save("lg_converted"+imgExt)  
    #remLFT_Final.save("lg_remLFTin"+imgExt)




    arcpy.AddMessage("...Remnant Input Completed")

     #Biodiversity
    crs.write("###Vegetation Input Parameters###\n")
    if arcpy.Exists(natVeg):
        arcpy.AddMessage("Creating Vegetation input rasters.....")   
        descNatVeg = arcpy.Describe(natVeg)
        Write2InputNotes(descNatVeg,"Natural Vegetation",crs)
        if descNatVeg.DataType != "FeatureLayer":
            natVegLayer = "natVegLayer"
            arcpy.MakeFeatureLayer_management(natVeg,natVegLayer)
        else:
            natVegLayer = natVeg
        
        arcpy.AddMessage("Creating Vegetation Raster.....")
        arcpy.SelectLayerByLocation_management(natVegLayer,"intersect", combinePoly)
        matchcount = int(arcpy.GetCount_management(natVegLayer).getOutput(0))
        if matchcount > 0:
            natVegPolys = "lgBio_NatVeg_feats"+nameShpExt
            arcpy.CopyFeatures_management(natVegLayer,natVegPolys)
            natVegTypeRaster = "lgBio_NatVeg"+imgExt
            fldName4Type = arcpy.ValidateFieldName(vegTypeFldName,env.workspace)
            arcpy.PolygonToRaster_conversion(natVegPolys,fldName4Type,natVegTypeRaster,"MAXIMUM_COMBINED_AREA","",cellSize)
            crs.write("  Field used for vegetation type: " +vegTypeFldName +"\n")
            if vegRankFldName != "":
                arcpy.AddMessage("Creating Rarity Raster.....")
                natVegRankRaster = "lgBio_NatVegUserRank"+imgExt
                fldName4Rank = arcpy.ValidateFieldName(vegRankFldName,env.workspace)
                arcpy.PolygonToRaster_conversion(natVegPolys,fldName4Rank,natVegRankRaster,"MAXIMUM_COMBINED_AREA","",cellSize)
                crs.write("  Field used for vegetation rarity rank: " +vegRankFldName+"\n")
            if biodiversityRankFldName != "":
                bioVegRankRaster = "lgBio_NatVegOtherRank"+imgExt
                arcpy.AddMessage("Creating Other vegetation Raster.....")
                fldName4Bio = arcpy.ValidateFieldName(biodiversityRankFldName,arcpy.env.workspace)
                arcpy.PolygonToRaster_conversion(natVegPolys,fldName4Bio,bioVegRankRaster,"MAXIMUM_COMBINED_AREA","",cellSize)
                crs.write("  Field used for other vegetation metric: " +biodiversityRankFldName+"\n")
            arcpy.SelectLayerByAttribute_management(natVegLayer,"CLEAR_SELECTION")            
        else:
            arcpy.AddWarning("No natural vegetation polygons selected.  Please check data.")

    
    
      #Environmental Services
    crs.write("\n")
    crs.write("###Environmental Services Input Parameters###\n")
    if arcpy.Exists(activeRiverAreas) or arcpy.Exists(fragileAreas) or arcpy.Exists(springs) or arcpy.Exists(otherES):
        arcpy.AddMessage("Creating Environmental Services input rasters.....")     
    
    if arcpy.Exists(activeRiverAreas):
        esDesc = arcpy.Describe(activeRiverAreas)
        Write2InputNotes(esDesc,"Active River Areas",crs)
        arcpy.AddMessage("Creating Active River Areas Raster.....")
 
        araRas = Times(activeRiverAreas,bndRaster)
        araRas.save("lgES_ara"+imgExt)

      
    if arcpy.Exists(fragileAreas):
        arcpy.AddMessage("Creating Fragile Areas Raster.....")
        esDesc = arcpy.Describe(fragileAreas)
        Write2InputNotes(esDesc,"Fragile Areas",crs)
        faRas = Times(fragileAreas,bndRaster)
        faRas.save("lgES_fa"+imgExt)

    if arcpy.Exists(springs):
        arcpy.AddMessage("Creating Springs Density Raster.....")
        esDesc = arcpy.Describe(springs)
        Write2InputNotes(esDesc,"Water Springs",crs)
        springsLayer = "springsLayer"
        arcpy.MakeFeatureLayer_management(springs,springsLayer)
        arcpy.SelectLayerByLocation_management(springsLayer,"intersect",combinePoly, 1000)
        
        springFeats = "lgES_spring_feats"+nameShpExt
        arcpy.CopyFeatures_management(springsLayer,springFeats)
        
        
        kdensity = KernelDensity(springFeats,"NONE",cellSize, 1000, "HECTARES")
        kdensity.save("xxlg_kDensity"+imgExt)
        
        whereClause = '"VALUE" > 0'
        gtZeroKDens = Con("xxlg_kDensity"+imgExt,"xxlg_kDensity"+imgExt,"#",whereClause)
        gtZeroKDens.save("xxlg_gtZeroKDens"+imgExt)
        
        springsRas = Times("xxlg_gtZeroKDens"+imgExt,bndRaster)
        springsRas.save("lgES_spring_density"+imgExt)
 
    if arcpy.Exists(otherES):
        arcpy.AddMessage("Creating other environmental services raster.....")
        esDesc = arcpy.Describe(otherES)
        Write2InputNotes(esDesc,"Other Environmental Services",crs)
        otherESRas = Times(otherES,bndRaster) 
        otherESRas.save("lgES_other"+imgExt)
    
    #Landscape setup
    crs.write("\n")
    crs.write("###Landscape Input Parameters###\n")
    crs.write("Remnants source data provides majortiy of input.\n")
    arcpy.AddMessage("Creating Landscape input rasters.....") 
    if arcpy.Exists(guidos):
        gDes = arcpy.Describe(guidos)
        Write2InputNotes(gDes,"GUIDOS",crs)
        arcpy.AddMessage("Migrating Guidos Raster.....")
        guidos4lg = ExtractByRectangle(guidos,env.extent,"INSIDE")
        guidos4lg.save("lgLand_guidos"+imgExt)
        #guidos4lg = "lg_guidos"+imgExt
        #arcpy.Clip_management(guidos,"#",guidos4lg,"lg_clipBnd"+nameShpExt,"NoData","NONE")

    if arcpy.Exists(otherLandscape):
        oLDes = arcpy.Describe(otherLandscape)
        Write2InputNotes(oLDes,"Other Landscape Metric",crs)
        arcpy.AddMessage("Migrating Other Landscape Metric.....")
        otherLandscape4lg = ExtractByRectangle(otherLandscape,env.extent,"INSIDE")
        otherLandscape4lg.save("lgLand_Other"+imgExt)
        #otherLandscape4lg = "lg_otherLandscape"+imgExt
        #arcpy.Clip_management(otherLandscape4lg,"#",otherLandscape4lg,"lg_clipBnd"+nameShpExt,"NoData","NONE")    
    if waterInBnd:
        Write2InputNotes(watbodyDesc,"Waterbodies",crs)
    #Legal Setup
    protectedSum = []
    crs.write("\n")
    crs.write("###Legal Input Parameters###\n")
    
    if arcpy.Exists(LRs) or arcpy.Exists(PPAs) or arcpy.Exists(PAs) or arcpy.Exists(CPAs) or arcpy.Exists(LegalOther):
        arcpy.AddMessage("Creating Legal and Conservation input rasters.....")     
    if arcpy.Exists(LRs):
        arcpy.AddMessage("Creating Legal Reserve Input......")
        lrDesc = arcpy.Describe(LRs)
        Write2InputNotes(lrDesc,"Legal Reserves",crs)
        #Needed for arcmap vs arccat
        if lrDesc.DataType != "FeatureLayer":
          LrLayer = "LrLayer"
          arcpy.MakeFeatureLayer_management(LRs,LrLayer)
        else:
          LrLayer = LRs

        arcpy.SelectLayerByLocation_management(LrLayer,"intersect", combinePoly)
        matchcount = int(arcpy.GetCount_management(LrLayer).getOutput(0))
        if matchcount > 0:

          lrRaster = "lgLegal_LRs"+imgExt
          lrSave = "lgLegal_LR_feats"+ nameShpExt
          arcpy.Dissolve_management(LrLayer,lrSave,"#","#","SINGLE_PART","DISSOLVE_LINES")
          #arcpy.CopyFeatures_management(LrLayer,lrSave)
          fieldList = arcpy.ListFields(lrSave,"","OID")
          fieldName = fieldList[0].name
          
          arcpy.AddField_management(LrLayer,"XXid","LONG")
          arcpy.CalculateField_management(LrLayer,"XXid","!"+fieldName+"!","PYTHON_9.3") 

          
          arcpy.PolygonToRaster_conversion(lrSave,"XXid",lrRaster,"MAXIMUM_COMBINED_AREA","",cellSize)

          whereClause = "Value >= 0"
          lrEvalRaster = Con(lrRaster,1,"",whereClause)         
          lrEvalRaster.save("lgLegal_LR_Ones"+imgExt)
          protectedSum.append("lgLegal_LR_Ones"+imgExt)
          arcpy.SelectLayerByAttribute_management(LrLayer,"CLEAR_SELECTION")
          arcpy.AddMessage("...Legal Reserve Completeted")
          
        else:
           arcpy.AddMessage("No legal reserves found in study area! Legal reserve will not be included in analysis.") 
         
    if arcpy.Exists(PPAs):
        
        arcpy.AddMessage("Creating Permanentaly Protected Input......")
        appDesc = arcpy.Describe(PPAs)
        Write2InputNotes(appDesc,"Permanentaly Protected Areas",crs)
        #Needed for arcmap vs arccat
        if appDesc.DataType != "FeatureLayer":
          appLayer = "PPA_Layer"
          arcpy.MakeFeatureLayer_management(PPAs,appLayer)
        else:
          appLayer = PPAs

        arcpy.SelectLayerByLocation_management(appLayer,"intersect", combinePoly)
        matchcount = int(arcpy.GetCount_management(appLayer).getOutput(0))
        if matchcount > 0:

          #Removed just saving appOnes and using in app not -- appRaster = "lg_PPAs"+imgExt

        
          prjLayer = "lgLegal_PPA_feats"+ nameShpExt
          #arcpy.AddMessage(arcpy.env.outputCoordinateSystem.name+" "+ appDesc.spatialReference.name)
          arcpy.Dissolve_management(appLayer,prjLayer,"#","#","SINGLE_PART","DISSOLVE_LINES")
          #arcpy.CopyFeatures_management(appLayer,prjLayer)
          #unionTmpLayer = "xxlg_Legal_PPA"+nameShpExt
          #inFeatures = [prjLayer]
          #arcpy.Union_analysis(inFeatures,unionTmpLayer,"ONLY_FID")
          arcpy.AddField_management(prjLayer,"xx_ID","LONG")
          arcpy.CalculateField_management(prjLayer,"xx_ID","1","VB","#")
          appRaster = "lgLegal_PPA_Ones"+imgExt
          
          
          #New method

          
          arcpy.PolygonToRaster_conversion(prjLayer,"xx_ID",appRaster,"MAXIMUM_COMBINED_AREA","",cellSize)
          #arcpy.FeatureToRaster_conversion(prjLayer,fieldName,appRaster,cellSize)
          #whereClause = "Value >= 0"
          #appEvalRaster = Con(appRaster,1,"",whereClause)
          #appEvalRaster.save("lg_PPA_Ones"+imgExt)
          protectedSum.append("lgLegal_PPA_Ones"+imgExt)
          arcpy.SelectLayerByAttribute_management(appLayer,"CLEAR_SELECTION")
          arcpy.AddMessage("...Permanentaly Protected Completed")

          
        else:
           arcpy.AddMessage("No permanently protected areas found in study area! PPAs will not be included in analysis.")

    if arcpy.Exists(PAs):
        
        arcpy.AddMessage("Creating Protected Area input......")
        paDesc = arcpy.Describe(PAs)
        Write2InputNotes(paDesc,"Protected Areas",crs)
        #Needed for arcmap vs arccat
        if paDesc.DataType != "FeatureLayer":
          paLayer = "paLayer"
          arcpy.MakeFeatureLayer_management(PAs,paLayer)
        else:
          paLayer = PAs

        arcpy.SelectLayerByLocation_management(paLayer,"intersect", combinePoly)
        matchcount = int(arcpy.GetCount_management(paLayer).getOutput(0))
        if matchcount > 0:
          
          paRaster = "lgLegal_PAs"+imgExt
          prjLayer = "lgLegal_PA_feats"+ nameShpExt
          arcpy.Dissolve_management(paLayer,prjLayer,"#","#","SINGLE_PART","DISSOLVE_LINES")
          #arcpy.CopyFeatures_management(paLayer,prjLayer)
          fieldList = arcpy.ListFields(prjLayer,"","OID")
          fieldName = fieldList[0].name
          arcpy.AddField_management(prjLayer,"XXid","LONG")
          arcpy.CalculateField_management(prjLayer,"XXid","!"+fieldName+"!","PYTHON_9.3") 
                      
          #arcpy.FeatureToRaster_conversion(prjLayer,fieldName,paRaster,cellSize)
          arcpy.PolygonToRaster_conversion(prjLayer,"XXid",paRaster,"MAXIMUM_COMBINED_AREA","",cellSize)

         
          whereClause = "Value >= 0"
          paEvalRaster = Con(paRaster,1,"",whereClause)         
          paEvalRaster.save("lgLegal_PA_Ones"+imgExt)
          protectedSum.append("lgLegal_PA_Ones"+imgExt)
          arcpy.SelectLayerByAttribute_management(paLayer,"CLEAR_SELECTION")
          arcpy.AddMessage("...Protected Area Completed")
          
        else:
           arcpy.AddMessage("No protected areas found in study area! PAs will not be included in analysis.")
             
    if arcpy.Exists(CPAs):
        arcpy.AddMessage("Creating Conservation Priority input......")
        prioDesc = arcpy.Describe(CPAs)
        Write2InputNotes(prioDesc,"Conservation Priority Areas",crs)
        #Needed for arcmap vs arccat
        if prioDesc.DataType != "FeatureLayer":
          prioLayer = "prioLayer"
          arcpy.MakeFeatureLayer_management(CPAs,prioLayer)
        else:
          prioLayer = CPAs

        arcpy.SelectLayerByLocation_management(prioLayer,"intersect", combinePoly)
        matchcount = int(arcpy.GetCount_management(prioLayer).getOutput(0))
        
        if matchcount > 0:    
         #Need to identify field
          fieldName = arcpy.ValidateFieldName(PriorityFldCPA,arcpy.env.workspace)
          prioRaster = "lgLegal_CPAs"+imgExt
          prjLayer = "lgLegal_CPA_feats"+ nameShpExt
          arcpy.CopyFeatures_management(prioLayer,prjLayer)
          
          arcpy.PolygonToRaster_conversion(prjLayer,fieldName,prioRaster,"MAXIMUM_COMBINED_AREA","",cellSize)
          #arcpy.FeatureToRaster_conversion(prjLayer,fieldName,prioRaster,cellSize)
          arcpy.SelectLayerByAttribute_management(prioLayer,"CLEAR_SELECTION")
          arcpy.AddMessage("...Conservation Priority Areas Completed")
        else:
           arcpy.AddMessage("No Conservation Priority areas found in study area! Conservation Priority areas will not be included in analysis.")
     
    if arcpy.Exists(LegalOther):
        arcpy.AddMessage("Creating Ecological or Other Zoning input......")
        ecoDesc = arcpy.Describe(LegalOther)
        Write2InputNotes(ecoDesc,"Legal Other",crs)
        #Needed for arcmap vs arccat
        if ecoDesc.DataType != "FeatureLayer":
          ecoLayer = "prioLayer"
          arcpy.MakeFeatureLayer_management(LegalOther,ecoLayer)
        else:
          ecoLayer = LegalOther

        arcpy.SelectLayerByLocation_management(ecoLayer,"intersect", combinePoly)
        matchcount = int(arcpy.GetCount_management(ecoLayer).getOutput(0))
        
        if matchcount > 0:    
          fieldName = arcpy.ValidateFieldName(PriorityFldLegalOther,arcpy.env.workspace)
          ecoRaster = "lgLegal_Other"+imgExt
          prjLayer = "lgLegal_Other_feats"+ nameShpExt
          arcpy.CopyFeatures_management(ecoLayer,prjLayer)
          
          arcpy.PolygonToRaster_conversion(prjLayer,fieldName,ecoRaster,"MAXIMUM_COMBINED_AREA","",cellSize)
          #arcpy.FeatureToRaster_conversion(prjLayer,fieldName,prioRaster,cellSize)
          arcpy.SelectLayerByAttribute_management(ecoLayer,"CLEAR_SELECTION")
          arcpy.AddMessage("...Legal Other Completed")
        else:
           arcpy.AddMessage("Legal other layer was selected however no features exists within study area and therefore will not be included in analysis.")
     

    #Threats
    crs.write("\n")
    crs.write("###Threat Input Parameters###\n") 
    if arcpy.Exists(accessibilityRaster) or arcpy.Exists(otherThreatRaster):
        arcpy.AddMessage("Creating Threat input rasters.....")
    if arcpy.Exists(accessibilityRaster):
        accDesc = arcpy.Describe(accessibilityRaster)
        Write2InputNotes(accDesc,"Accessibility",crs)
        arcpy.AddMessage("Creating Accessibility Raster.....")
        accessibilityRas = Times(accessibilityRaster,bndRaster)
        accessibilityRas.save("lgThreat_Access"+imgExt)
        #accessibilityRas = "lg_accessibility"+imgExt
        #arcpy.Clip_management(accessibilityRaster,"#",accessibilityRas,"lg_clipBnd"+nameShpExt,"NoData","NONE")

    if arcpy.Exists(otherThreatRaster):
        otherTDesc = arcpy.Describe(otherThreatRaster)
        Write2InputNotes(otherTDesc,"Other Threat",crs)
        arcpy.AddMessage("Creating Threat Raster.....")
        threatRas = Times(otherThreatRaster,bndRaster)
        threatRas.save("lgThreat_Other"+imgExt)

 
    crs.write("*********Project Setup End************\n")
    crs.write("\n")
    crs.close()
      

      
      
      #Create neg mask if data exists to support this
    
    if not(arcpy.Exists("lg_remPrjOnly"+imgExt)):
        if len(protectedSum) > 0:
            protected = CellStatistics(protectedSum,"MAXIMUM","DATA")
            protected.save("xxlg_protected"+imgExt)
            notProtected = Con(IsNull("xxlg_protected"+imgExt),1)
            notProtected.save("xxlg_NotProtected"+imgExt)
            remsPrjOnly = Times(Times("lg_bnd_ones"+imgExt,"lg_REM_Ones"+imgExt),"xxlg_NotProtected"+imgExt)    
            convPrjOnly = Times(Times("lg_bnd_ones"+imgExt,"lg_converted"+imgExt),"xxlg_NotProtected"+imgExt)
        else:
            remsPrjOnly = Times("lg_bnd_ones"+imgExt,"lg_REM_Ones"+imgExt)    
            convPrjOnly = Times("lg_bnd_ones"+imgExt,"lg_converted"+imgExt)
               
        remsPrjOnly.save("lg_remPrjOnly"+imgExt)
        convPrjOnly.save("lg_ConvProjOnly"+imgExt)
    else:
        if len(protectedSum)>0:
            pSum2 = []
            if arcpy.Exists("lgLegal_LR_Ones"+imgExt):
                pSum2.append("lgLegal_LR_Ones"+imgExt)
            if arcpy.Exists("lgLegal_PA_Ones"+imgExt):
                pSum2.append("lgLegal_PA_Ones"+imgExt)
            if arcpy.Exists("lgLegal_PPA_Ones"+imgExt):
                pSum2.append("lgLegal_PPA_Ones"+imgExt)
            protected = CellStatistics(pSum2,"MAXIMUM","DATA")
            protected.save("xxlg_protected"+imgExt)
            notProtected = Con(IsNull("xxlg_protected"+imgExt),1)
            notProtected.save("xxlg_NotProtected"+imgExt)
            remsPrjOnly = Times(Times("lg_bnd_ones"+imgExt,"lg_REM_Ones"+imgExt),"xxlg_NotProtected"+imgExt)    
            convPrjOnly = Times(Times("lg_bnd_ones"+imgExt,"lg_converted"+imgExt),"xxlg_NotProtected"+imgExt)
            remsPrjOnly.save("lg_remPrjOnly"+imgExt)
            convPrjOnly.save("lg_ConvProjOnly"+imgExt)
        
     


except PageLayoutError:
    arcpy.AddError ("Application will not run in the Page Layout View. Please switch to Data View to run the analysis.")
    
except SpatialRefProjErrorMap:
    arcpy.AddError ("Current coordinate system used in the data frame does not match remnant layer coordinate system.  Applicaton requires both are set to the same coordinate system.")

except SpatialRefProjErrorRemFC:
    arcpy.AddError ("The remenants feature class must use a projected coordinate system to run")

except LicenseError:
    arcpy.AddError ("Spatial Analyst license is unavailable")   

except matchingSpRefsError:
    arcpy.AddError ("Spatial reference of data frame must match the spatial reference of the DEM being used") 

except NoRemnantsError:
    arcpy.AddError ("No remnant features are found within project area.  Analysis reguires remnants at minimum be present.")

except BoundaryProjError:
    arcpy.AddError ("Spatial reference of project boundary data must be the same as remnants layer.") 

except RasterSprefError:
    arcpy.AddError ("Raster spatial refrence error")

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)

    arcpy.AddError(pymsg)
finally:
    arcpy.AddMessage("Setup Completed")
    arcpy.AddMessage("Removing any intermediary files")
    if arcpy.Exists(project_folder+"\\scratch"):
        try:
            arcpy.Delete_management(project_folder+"\\scratch")
        except:
            arcpy.AddWarning("Could not delete folder: "+project_folder+"\\scratch  Can be removed by user.")
      
    LegalGeo_Routines_Module.deleteTempFiles()

                         
    