#IN NO EVENT, UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, SHALL THE AUTHORS OR ANY PERSON BE LIABLE FOR ANY LOSS, EXPENSE OR DAMAGE, OF ANY TYPE OR NATURE ARISING OUT OF THE USE OF, OR INABILITY TO USE THIS ALGORITHM, INCLUDING, BUT NOT LIMITED TO,CLAIMS, SUITS OR CAUSES OF ACTION INVOLVING ALLEGED INFRINGEMENT OF COPYRIGHTS, PATENTS, TRADEMARKS, TRADE SECRETS, OR UNFAIR COMPETITION.
#In no event will the authors or distributors be liable to you for any damages, including any lost of profit, lost savings, lost patience or other incidental or consequential damage
#This is pseudo-code describing each step of the method.  You'll need to change the paths of input and output data as well as provide the ancillary text files for some calls (linear to decibel conversion, for instance) and adjust it to your needs (e.g. the threshold used for seeding or energy will vary depending on your input beam mode)

import os, os.path, shutil, fnmatch

from pci.exceptions import*
from pci.fimport import *
from pci.psinang import *
from pci.psiqinterp import *
from pci.iii import *
from pci.iia import *
from pci.pcimod import *
from pci.ortho2 import *
from pci.mcd import *
from pci.felee import *
from pci.thr import *
from pci.tex import *
from pci.blo import *
from pci.model import *
from pci.fav import *
from pci.pyramid import *
from pci.ras2poly import *
from pci.fexport import *
from pci.iib import *
from pci.histex import *
from pci.bit2poly import *
from pci.pspolfil import *
from pci.shrink import *
from pci.iiibit import *
from pci.his import *

# The following locale settings are used to ensure that Python is configured
# the same way as PCI's C/C++ code.  
import locale
locale.setlocale(locale.LC_ALL, "")
locale.setlocale(locale.LC_NUMERIC, "C")
###############################################

RawFolder = r"G:\RSAT2\"
InFolder = r"E:\Radarsat\Input"
OrthoDir = r"E:\Radarsat\ortho"
OutFolder = r"E:\Radarsat\output"
filedem= r"E:\Dems\dem_prairies_raw.pix"
model_bit2ras = r"C:\Data\scripts\model_bit2ras.txt"
model_inten2db = r"C:\Data\scripts\model_inten2db.txt"
model_100db = r"C:\Data\scripts\model_100db.txt"
HighestEnergy = r"C:\Data\scripts\LowestEnergy.txt"
MeanEnergy = r"C:\Data\scripts\MeanEnergy.txt"
pspolfil2db = r"C:\Data\scripts\model_pspolfil2db.txt"
SeedMask = r"C:\Data\scripts\SeedMask.txt"

if not os.path.exists(InFolder): os.makedirs(InFolder)
if not os.path.exists(OrthoDir): os.makedirs(OrthoDir)
if not os.path.exists(OutFolder): os.makedirs(OutFolder)

input_files_list = []
list_of_images = []
list_of_ofiles = []
list_of_db = []
imstat = []
exthr = 0

#------------------------------------
#Running FIMPORT **ORTHO2 and LINK didn't work with URIs 
#------------------------------------           
print "**********************************"
print "*   Importing calibrated images  *"
print "**********************************"
		   
for root, dirs, files in os.walk(RawFolder):
   for file in files:
       if file.endswith('t.xml'):
           input_files_list.append(os.path.join(root,file)+ ":Calibration Type:Sigma Nought")
           head, tail = os.path.split(root)
           
	   if len(input_files_list) > 0: #handles the case when input list is empty
		   for raw_file in input_files_list: #iterates through each image file found.   
			   fili = raw_file
			   filo = InFolder + os.sep + tail[30:] + ".pix"
			   dbiw = []
			   poption = "off"
			   dblayout = ""
		   try:
			   fimport(fili, filo, dbiw, poption, dblayout)
		   except PCIException, e:
			   print e
		   except Exception, e:
			   print e
		   else:
			   print "No image files found in " + RawFolder + " that match your filter criteria."

list_of_images = os.listdir(InFolder)

print "****************************"
print " Polarimetric Filtering *"
print "****************************"

for each_image in list_of_images:
	if each_image.endswith('SLC.pix'):
		print "Polarimetric Lee filtering for " + each_image   
		fili = InFolder + os.sep + each_image
		filo = InFolder + os.sep + os.path.splitext(each_image)[0] + "_pspolfil.pix"
		flsz = [5]      # Integer
		nlook = [1]     # Float

		try:
		   pspolfil(fili, filo, flsz, nlook)
		except PCIException, e:
		   print e
		except Exception, e:
		   print e

####------------------------------------
####Runnig PSINANG to get incidence angle array segment, then transferring the segment from the pix above, then ortho-rectifying the PSINANG and III to the db image image  
####------------------------------------

print "****************************"
print " Computing Incidence Angle *"
print "****************************"

for each_image in list_of_images:
   if each_image.endswith('SLC.pix'):
	   print "Computing Incident Angle for " + each_image   
	   fili = InFolder + os.sep + each_image 
	   filo = InFolder + os.sep + os.path.splitext(each_image)[0] + "_psinang.pix"
	   angletyp = u"degree" 
	   try:
		   psinang(fili, filo, angletyp)
	   except PCIException, e:
		   print e
	   except Exception, e:
		   print e


list_of_images = os.listdir(InFolder)

print "******************************************"
print " Computing decibel images (from pspolfil)*"###need to export the two real channels first, then add two to store output from linear to decibel conversion
print "******************************************"

for each_image in list_of_images:
    if each_image.endswith('_pspolfil.pix'):
		print "Exporting real components from " + each_image
		fili = InFolder + os.sep + each_image
		filo = InFolder + os.sep + os.path.splitext(each_image)[0] + "_real.pix"
		dbiw = []      # Integer
		dbic = [1,2]      # Integer
		dbib = []      # Integer
		dbvs = []      # Integer
		dblut = []      # Integer
		dbpct = []      # Integer
		ftype = u"" 
		foptions = u"" 
				
		try:
			fexport(fili, filo, dbiw, dbic, dbib, dbvs, dblut, dbpct, ftype, foptions)
		except PCIException, e:
			print e
		except Exception, e:
			print e 
	
		print "Adding  32R channels to " + filo  #to store db from pspolfil using model
		file = filo
		pciop = u"ADD"
		pcival = [0,0,0,3]
               
		try:
			pcimod(file, pciop, pcival)
		except PCIException, e:
			print e
		except Exception, e:
			print e		  

					
		print "Computing decibel image for " + each_image
		file = file 
		source = pspolfil2db
		undefval = []

		try:
			model(file, source, undefval)
		except PCIException, e:
			print e
		except Exception, e:
			print e 
           
list_of_images = os.listdir(InFolder)

# ###
# ###print "**************************************"
# ###print "*  Correcting channel descriptions   *"#Need to include MCD to Modify channel 1 & 2 description, becuase PSIQINTERP just transfer the one from FILO (except for the first file)
# ###print "**************************************"
# ###
# ###for each_image in list_of_images:
# ###    if each_image.endswith('_db.pix'):
# ###        file = InFolder + os.sep + each_image  
# ###        print "Modifying channel description for channel 1 of " + each_image
# ###        cm01 = u"HH in Decibels" 
# ###        dboc = [1]      # Integer
# ###
# ###        try:
# ###            mcd(file, cm01, dboc)
# ###        except PCIException, e:
# ###            print e
# ###        except Exception, e:
# ###            print e
# ###
# ###for each_image in list_of_images:
# ###    if each_image.endswith('_db.pix'):
# ###        file = InFolder + os.sep + each_image 
# ###        print "Modifying channel description for channel 2 of " + each_image
# ###        cm01 = u"HV in Decibels" 
# ###        dboc = [2]      # Integer
# ###
# ###        try:
# ###            mcd(file, cm01, dboc)
# ###        except PCIException, e:
# ###            print e
# ###        except Exception, e:
# ###            print e

                      
print "************************************"
print " Transferring IncAngle to db image  *"
print "************************************"

for each_image in list_of_images:
   if each_image.endswith('_psinang.pix'):
       print "Storing incidence angle in " + each_image.replace('psinang', 'pspolfil_real')
       fili = InFolder + os.sep + each_image
       filo = InFolder + os.sep + each_image.replace('psinang', 'pspolfil_real')
       dbic = [1]
       dboc = [5]
       dbiw = []
       dbow = []
       
       try:
           iii(fili, filo, dbic, dboc, dbiw, dbow)
       except PCIException, e:
           print e
       except Exception, e:
           print e
		#os.remove(fili)
		    
#
print "********************************************************"
print " Transferring non-imagery segments from raw to db image *"
print "********************************************************"

for each_image in list_of_images:
   if each_image.endswith('SLC.pix'):
       print " Transfering non-imagery segments for " + each_image
       fili = InFolder + os.sep + each_image
       filo = InFolder + os.sep + each_image.replace('SLC', 'SLC_pspolfil_real')
       dbsl = [2,3,4,5]
       dbos = []
       try:
           iia(fili, filo, dbsl, dbos)
       except PCIException, e:
           print e
       except Exception, e:
           print e

      

print "**********************************"
print "*   Running Ortho-rectification   *"
print "**********************************"
                   
mfile = InFolder + os.sep + "*_real.pix" 
dbic = [3,4,5]      # Integer
mmseg = []      # Integer
dbiw = []      # Integer
srcbgd = u"" 
filo = OrthoDir 
ftype = u"" 
foptions = u"" 
outbgd = [-100]     # Float
ulx = u"" 
uly = u"" 
lrx = u"" 
lry = u"" 
edgeclip = []      # Integer
tipostrn = u"" 
mapunits = u"" 
bxpxsz = u"" 
bypxsz = u"" 
filedem = filedem 
dbec = []      # Integer
backelev = []     # Float
elevref = u"" 
elevunit = u"" 
elfactor = []     # Float
proc = u"6000" 
sampling = []      # Integer
resample = u"" 

try:
   ortho2(mfile, dbic, mmseg, dbiw, srcbgd, filo, ftype, foptions, outbgd, ulx, uly, lrx, lry, edgeclip, tipostrn, mapunits, bxpxsz, bypxsz, filedem, dbec, backelev, elevref, elevunit, elfactor, proc, sampling, resample)
except PCIException, e:
   print e
except Exception, e:
   print e
                               
#shutil.rmtree(InFolder)  # cleaning disk space 

list_of_ofiles = os.listdir(OrthoDir)
list_of_db = []

for each_image in list_of_ofiles:
    if each_image.endswith('_pspolfil_real.pix'):
        list_of_db.append(each_image)
               
               
print "****************************************"
print "*   Adding channels to ortho db images *" #Two runs, just so that 32R are altogether
print "****************************************"

for each_ortho in list_of_db:
   print "Adding 32R channels to " + each_ortho
   file = OrthoDir + os.sep + each_ortho
   pciop = "add"
   pcival = [0,0,0,6]
	
   try: pcimod(file, pciop, pcival)
   except PCIException, e:print e
   except Exception, e:
       print e

for each_ortho in list_of_db:
   print "Adding 8bit channels to " + each_ortho
   file = OrthoDir + os.sep + each_ortho
   pciop = "add"
   pcival = [6,0,0,0]
	
   try: pcimod(file, pciop, pcival)
   except PCIException, e:print e
   except Exception, e:
       print e        


print "********************************************"
print "*  Computing & Shrinking Valid Data Mask  *" #Need to compute & shrink, to have meaningful MEAN (from HISTEX)
print "********************************************"
#
for each_ortho in list_of_db:
   print "Creating valid data mask for image " + each_ortho
   file = OrthoDir + os.sep + each_ortho
   source = model_100db
   undefval = []
   
   try:
       model(file, source, undefval)
   except PCIException, e:
       print e
   except Exception, e:
       print e


for each_ortho in list_of_db:
   print "Shrinking valid data mask on " + each_ortho  # Need to shrink it, as HisMean includes edge Nodata pixels in the computations
   file = OrthoDir + os.sep + each_ortho 
   dbic = [10]      # Integer
   dboc = [11]      # Integer
   shrinksz = [2,2]      # Integer

   try:
       shrink(file, dbic, dboc, shrinksz)
   except PCIException, e:
       print e
   except Exception, e:
       print e

for each_ortho in list_of_db:
   print "Converting valid data mask to bitmap for " + each_ortho 
   file = OrthoDir + os.sep + each_ortho
   dbic = [11]      # Integer
   dbob = []      # Integer
   tval = [1]      # Float
   comp = u"OFF" 
   dbsn = u"DataMask" 
   dbsd = u"Valid Data pixels" 

   try:
       thr(file, dbic, dbob, tval, comp, dbsn, dbsd)
   except PCIException, e:
       print e
   except Exception, e:
       print e


print "*******************************"
print "*  Filtering ortho db images  *" #Need to do it under a valid Data mask to avoid padding of the pixels 
print "*******************************"


for each_ortho in list_of_db:
   print "Filtering channel 1 of " + each_ortho
   file = OrthoDir + os.sep + each_ortho 
   dbic = [1]      # Integer
   dboc = [4]      # Integer
   flsz = [3,5]      # Integer
   mask = []      # Integer
   nlook = [1]     # Float
   damp = []     # Float
   imagefmt = u"Power" 

   try:
       felee(file, dbic, dboc, flsz, mask, nlook, damp, imagefmt)
   except PCIException, e:
       print e
   except Exception, e:
       print e
        
for each_ortho in list_of_db:
    print "Filtering channel 2 of " + each_ortho
    file = OrthoDir + os.sep + each_ortho 
    dbic = [2]      # Integer
    dboc = [5]      # Integer
    flsz = [3,5]      # Integer
    mask = []      # Integer
    nlook = [1]     # Float
    damp = []     # Float
    imagefmt = u"Power" 

    try:
        felee(file, dbic, dboc, flsz, mask, nlook, damp, imagefmt)
    except PCIException, e:
        print e
    except Exception, e:
        print e


print "*************************"
print "*  Computing Seed Mask  *" # HH<-24, but done on the HISTEX Mean of HH (db) from pspolfil, to eliminate false positives ##PSPOLIFIL many DN values become too low
print "*************************"

for each_ortho in list_of_db:
	print "Copying filtered values under shrinked mask " + each_ortho
	file = OrthoDir + os.sep + each_ortho
	dbic = [4]      # Integer
	dboc = [6]      # Integer
	dbib = [2]      # Integer
	
	try:
		iiibit(file, dbic, dboc, dbib)
	except PCIException, e:
		print e
	except Exception, e:
		print e

     
for each_ortho in list_of_db:  ##this one is overwritten by the next algorithm, but is needed to create a bitmap
    print "Computing Seed Mask for " + each_ortho
    file = OrthoDir + os.sep + each_ortho
    dbic = [6]      # Integer
    dbob = []      # Integer
    tval = [-80, -20]      # Float, using -80, because everything below this value is just noise
    comp = u"OFF" 
    dbsn = u"Seeds" 
    dbsd = u"Unfiltered Seeds" 

    try:
        thr(file, dbic, dbob, tval, comp, dbsn, dbsd)
    except PCIException, e:
        print e
    except Exception, e:
        print e
		
for each_ortho in list_of_db:
    print "Computing and adjusting Seed Mask in Near range" + each_ortho
    file = OrthoDir + os.sep + each_ortho
    source = SeedMask
    undefval = []
    
    try:
        model(file, source, undefval)
    except PCIException, e:
        print e
    except Exception, e:
        print e
            
print "*******************************"
print "*  Computing Extended Mask    *"  
print "*******************************"
     
 
for each_ortho in list_of_db:
    print "Computing Energy from HH local Hist Stats " + each_ortho
    file = OrthoDir + os.sep + each_ortho
    dbic = [4]      # Integer
    texture = [10]      # Integer
    dboc = [7]      # Float
    flsz = [5,5]
    mask = [2]      # Integer
    fillpct = [10]     # Float
        
    try:
        histex(file, dbic, texture, dboc, flsz, mask, fillpct)
    except PCIException, e:
        print e
    except Exception, e:
        print e
        
for each_ortho in list_of_db:
    print "Computing Energy from HV local Hist Stats " + each_ortho
    file = OrthoDir + os.sep + each_ortho
    dbic = [5]      # Integer
    texture = [10]      # Integer
    dboc = [8]      # Float
    flsz = [5,5]
    mask = [2]      # Integer
    fillpct = [10]     # Float
        
    try:
        histex(file, dbic, texture, dboc, flsz, mask, fillpct)
    except PCIException, e:
        print e
    except Exception, e:
        print e


for each_ortho in list_of_db:
    print "Getting lowest energy from HH HV " + each_ortho
    file = OrthoDir + os.sep + each_ortho
    source = HighestEnergy
    undefval = []
    
    try:
        model(file, source, undefval)
    except PCIException, e:
        print e
    except Exception, e:
        print e
 
for each_ortho in list_of_db:
	print "Computing Histogram stats on energy for  " + each_ortho
	file = OrthoDir + os.sep + each_ortho 
	dbic = [9]      # Integer
	gmod = u"" 
	cmod = u"" 
	pcmo = u"" 
	nsam = []      # Integer
	trim = [2]     # Float
	hisw = []     # Float
	mask = [2]      # Integer
	imstat = []     # Float

	try:
		his(file, dbic, gmod, cmod, pcmo, nsam, trim, hisw, mask, imstat)
	except PCIException, e:
		print e
	except Exception, e:
		print e
		
	print imstat
	print exthr
	mean = imstat[1]
	stdev = imstat[3]
	Min = imstat[10]
	Max = imstat[11]
	exthr = mean + (1.25*stdev)
	print exthr
	
	print "Thresholding lowest Energy for " + each_ortho
	file = file 
	dbic = [9]      # Integer
	dbob = []      # Integer
	tval = [exthr]      # Float
	comp = u"OFF" 
	dbsn = u"Ext_Ener" 
	dbsd = u"Unfilt.Ext from energy HV" 
	try:
		thr(file, dbic, dbob, tval, comp, dbsn, dbsd)
	except PCIException, e:
		print e
	except Exception, e:
		print e

	f = open (MeanEnergy, 'a+')
	print "Writting energy stats for " + each_ortho
	f.write(each_ortho + "," + str(mean) + "," + str(stdev) + "," + str(Min) + "," + str(Max) + "\n")
	f.close()
	
## 
# for each_ortho in list_of_db:  #### energy  is sufficient for the extended mask but might have to do it to clean no-data pixels in the edges
   # print "Computing Final Extended Mask for " + each_ortho
   # file = OrthoDir + os.sep + each_ortho
   # logfunc = u"AND" 
   # dbsn = u"Extended" 
   # dbsd = u"Final HV+TexEn Ext Mask BLO" 
   # dbib = [2,4]      # Integer
   # dbob = []      # Integer
   # lasc = []      # Integer

   # try:
       # blo(file, logfunc, dbsn, dbsd, dbib, dbob, lasc)
   # except PCIException, e:
       # print e
   # except Exception, e:
       # print e

print "*********************************"
print "*  Burning Masks to channels    *"
print "*********************************"

for each_ortho in list_of_db:
    print "Burning Masks of " + each_ortho
    file = OrthoDir + os.sep + each_ortho
    source = model_bit2ras
    undefval = []
    
    try:
        model(file, source, undefval)
    except PCIException, e:
        print e
    except Exception, e:
        print e
        
####print "**************************************"
####print "*  Assigning channel descriptions   *"
####print "**************************************"
####
####for each_ortho in list_of_db:
####    print "Modifying channel description for channel 9 of " + each_ortho
####    file = OrthoDir + os.sep + each_ortho
####    cm01 = u"Seed" 
####    dboc = [15]      # Integer
####
####    try:
####        mcd(file, cm01, dboc)
####    except PCIException, e:
####        print e
####    except Exception, e:
####        print e
####
####for each_ortho in list_of_db:
####    print "Modifying channel description for channel 10 of " + each_ortho
####    file = OrthoDir + os.sep + each_ortho
####    cm01 = u"Extended" 
####    dboc = [16]      # Integer
####
####    try:
####        mcd(file, cm01, dboc)
####    except PCIException, e:
####        print e
####    except Exception, e:
####        print e            
#
print "******************************"
print "* Filtering the Seed mask    *"  #Calling FAV on a binary (with binary output) is really doing a MODE filter - FMOD didn't work on this file
print "******************************"

for each_ortho in list_of_db:
    print "Filtering seed mask of " + each_ortho
    file = OrthoDir + os.sep + each_ortho
    dbic = [12]      # Integer
    dboc = [14]      # Integer
    flsz = [3,3]      # Integer
    mask = []      # Integer
    bgrange = []     # Float
    failvalu = []     # Float
    bgzero = u"" 

    try:
        fav(file, dbic, dboc, flsz, mask, bgrange, failvalu, bgzero)
    except PCIException, e:
        print e
    except Exception, e:
        print e
            
print "**********************************"
print "* Filtering the Extended mask    *"
print "**********************************"

for each_ortho in list_of_db:
    print "Filtering extended mask of " + each_ortho
    file = OrthoDir + os.sep + each_ortho
    dbic = [13]      # Integer
    dboc = [15]      # Integer
    flsz = [7,7]      # Integer
    mask = []      # Integer
    bgrange = []     # Float
    failvalu = []     # Float
    bgzero = u"" 

    try:
        fav(file, dbic, dboc, flsz, mask, bgrange, failvalu, bgzero)
    except PCIException, e:
        print e
    except Exception, e:
        print e

print "*******************************************"
print "* Converting Filtered Masks to bitmap    *"#Need to convert the raster back to bit, then to vec, just so that the background 
print "*******************************************"#is not exported as a polygon, like when run ras2poly or expolras, also bit2poly is faster

for each_ortho in list_of_db:
    print "Converting filtered seed mask from " + each_ortho
    file = OrthoDir + os.sep + each_ortho
    dbic = [14]      # Integer
    dbob = []      # Integer
    tval = [1]      # Float
    comp = u"OFF" 
    dbsn = u"Seeds" 
    dbsd = u"Filtered Seeds"
        
    try:
        thr(file, dbic, dbob, tval, comp, dbsn, dbsd)
    except PCIException, e:
        print e
    except Exception, e:
            print e
            
for each_ortho in list_of_db:
    print "Converting extended mask from " + each_ortho
    file = OrthoDir + os.sep + each_ortho 
    dbic = [15]      # Integer
    dbob = []      # Integer
    tval = [1]      # Float
    comp = u"OFF" 
    dbsn = u"Extended" 
    dbsd = u"Filtered Extended" 

    try:
        thr(file, dbic, dbob, tval, comp, dbsn, dbsd)
    except PCIException, e:
        print e
    except Exception, e:
        print e

   
print "*******************************************************************************"
print "* Exporting HH+HV filtered db channels + bitmaps (To minimize disk space for QA) *"
print "*******************************************************************************"

for each_ortho in list_of_db:
    if each_ortho.endswith("_real.pix"):
        print "Exporting filtered channels & bitmaps from " + each_ortho  
        fili = OrthoDir + os.sep + each_ortho
        filo = OutFolder + os.sep + os.path.splitext(each_ortho)[0] + "_qa.pix"  
        dbiw = []      # Integer
        dbic = [4,5]      # Integer
        dbib = [2,3,4,5,6,7]      # Integer
        dbvs = []      # Integer
        dblut = []      # Integer
        dbpct = []      # Integer
        ftype = u"" 
        foptions = u"" 

        try:
            fexport(fili, filo, dbiw, dbic, dbib, dbvs, dblut, dbpct, ftype, foptions)
        except PCIException, e:
            print e
        except Exception, e:
            print e
	# os.remove(fili) #removes input as it produces the ortho, to avoid running out of disk space
           
# for each_ortho in list_of_db:
   # if each_ortho.endswith("_db.pix"):
       # os.remove(os.path.join(OutFolder, each_ortho))

list_of_db = os.listdir(OutFolder)

print "*********************************************************"
print "*  Running Pyramids (to make display faster during QA)  *"
print "*********************************************************"

for each_ortho in list_of_db:
    if each_ortho.endswith("_qa.pix"):
        print "Building pyramids for " + each_ortho  
        file = OutFolder + os.sep + each_ortho 
        dboc = []      # Integer
        force = u"YES" 
        olevels = []      # Integer
        poption = u"" 

        try:
            pyramid(file, dboc, force, olevels, poption)
        except PCIException, e:
            print e
        except Exception, e:
            print e


print "*******************************************"
print "* Converting Filtered bitmaps to polygons *"
print "*******************************************"

for each_ortho in list_of_db:
    if each_ortho.endswith("_qa.pix"):
        print "Converting seed mask from " + each_ortho + " to polygons"
        fili = OutFolder + os.sep + each_ortho
        dbib = [6]      # Integer
        filo = OutFolder + os.sep + os.path.splitext(each_ortho)[0] + "_seeds.shp"
        smoothv = u"YES" 
        dbsd = u"Filtered Seeds" 
        ftype = u"SHP" 
        foptions = u"" 

        try:
            bit2poly(fili, dbib, filo, smoothv, dbsd, ftype, foptions)
        except PCIException, e:
            print e
        except Exception, e:
            print e

for each_ortho in list_of_db:
    if each_ortho.endswith("_qa.pix"):
        print "Converting extended mask from " + each_ortho + " to polygons"
        fili = OutFolder + os.sep + each_ortho 
        dbib = [7]      # Integer
        filo = OutFolder + os.sep + os.path.splitext(each_ortho)[0] + "_Extended.shp"
        smoothv = u"YES" 
        dbsd = u"Filtered Extended" 
        ftype = u"SHP" 
        foptions = u"" 

        try:
            bit2poly(fili, dbib, filo, smoothv, dbsd, ftype, foptions)
        except PCIException, e:
            print e
        except Exception, e:
            print e            

## Topological intersection of polygons in QGIS 

