"""

------ section 1 ------

"""


def andResult (flagOne,setOne, flagTwo,setTwo):
    
    """
    Intersection of setOne and setTwo.
    Returns newList.
    setOne has a 0 index
    and setTwo non zero.
    """
    #print '\nsetOne', setOne, 'setTwo', setTwo
    
    newList = []

    # check for nothing in setOne
    if len (setOne)  == 0 and flagOne:
        for item in setTwo:
            newList.append (item)
        
        return newList

    if len (setTwo) == 0 and flagTwo:
        for item in setOne:
            newList.append (item)
        
        return newList
    
    # setOne has the same tag as setTwo
    # move the setTwo entry into setNew
    # ie. replace it
    for i,j  in setOne:
        for k, l in setTwo:
            if i == k:
                
                newList.append ((k,l))
                
    return newList


"""
pull selected information - greater than, less than, equal to, not equal to.
values must be sorted on input.
return a set of those that meet criteria in grabBag.
"""

from bisect import bisect_left, bisect_right

# get top or bottom of stack for a particular attribute


# select higher (greater) than attributes
# actually bottom of list


def greaterThan (values, cutOffValue):
    # strip off names in order to bisect
    i = 0
    length = len (values)
    temp = []
    while i < length:
        temp.append (values [i] [0])
        i += 1
    cutOffPoint = bisect_right (temp, cutOffValue)
    #print "GT cut off point ", cutOffPoint, "cut off value ", cutOffValue, "length ", length,

    # now grab names for which attributes pass
    grabBag = set ()
    while cutOffPoint < length:
        grabBag.add (values [cutOffPoint] [1])
        cutOffPoint += 1
    
    return (grabBag)



# select lower (less) than attributes
# actually top ones in list

def lessThan (values, cutOffValue):
    # strip off names in order to bisect
    i = 0
    length = len (values)
    temp = []
    while i < length:
        temp.append (values [i] [0])
        i += 1
    #print 'temp ', temp
    cutOffPoint = bisect_left (temp, cutOffValue)
    #print "LT cut off point ", cutOffPoint, "cut off value ", cutOffValue, "length ", length

    # now grab names for which attributes pass
    # need to pick only second part of tuple
    grabBag = set ()
    i = 0
    while i < cutOffPoint:
        grabBag.add (values [i] [1])
        i += 1

    return (grabBag)



# equalTo names with this attribute
# degenerate version of greaterThan
# values does not need to be sorted on input

def equalIn (values, acceptedValue):
    grabBag = set ()
    i = 0
    length = len (values)
    while i < length:
        if values [i] [0] == acceptedValue:
            grabBag.add (values [i] [1])
        i += 1
    
    return (grabBag)



# like eaualIn but not.

def notEqualIn (values, acceptedValue):
    grabBag = set ()
    i = 0
    length = len (values)
    while i < length:
        if values [i] [0] != acceptedValue:
            grabBag.add (values [i] [1])
        i += 1
        
    return (grabBag)
       


# get list of values that have "accetedValue" in.
# values does not need to be sorted on input.
# matches on any sub string.

def strIn (values, acceptedValue):
    grabBag = set ()
    i = 0
    length = len (values)
    while i < length:
        if acceptedValue in values [i] [0]:
            grabBag.add (values [i] [1])
        i += 1
    
    return (grabBag)


# like strIn but not.

def notStrIn (values, acceptedValue):
    grabBag = set ()
    i = 0
    length = len (values)
    while i < length:
        if acceptedValue not in values [i] [0]:
            grabBag.add (values [i] [1])
        i += 1
    
    return (grabBag)




# get list of values that have "acceptedValue" in.
# values does not need to be sorted on input but
# needs to be match on a whole word

def wordIn (values, acceptedValue):
    grabBag = set ()
    i = 0
    length = len (values) - 1
    while i < length:
        i += 1
        print 'values, acceptedValue', values [i] [0], acceptedValue
        if values [i] [0] == acceptedValue:
            grabBag.add (values [i] [1])
            continue
        temp = values [i] [0].replace ('-',' ').split ()
        for item in temp:
            if item == acceptedValue:
                grabBag.add (values [i] [1])
                break
    
    return (grabBag)




# like wordIn but not.

def notWordIn (values, acceptedValue):
    grabBag = set ()
    i = -1
    length = len (values) - 1
    while i < length:
        i += 1
        # check for the whole thing
        if acceptedValue == values [i] [0]:
            continue
        # check included words
        temp = values [i] [0].replace ('-',' ').split ()
        if acceptedValue in temp:
            continue
        grabBag.add (values [i] [1])
    
    return (grabBag)



def selectTags (first, result, choice, feature, tag, inFlag):
    """
    Set up calls to greaterThan, lessThan...
    routines.
    """

    names = set ()
    if choice == 'greater than':
        names = greaterThan (feature, tag)
    elif choice == 'equal':
        if inFlag == 0:
            # look for feature equal
            names = equalIn (feature, tag)
        elif inFlag == 1:
            # look for string "in" (substring)
            names = strIn (feature, tag)
        elif inFlag == 2:
            # look for word in
            names = wordIn (feature, tag)
    elif choice == 'not equal':
        if inFlag == 0:
            # look for feature not equal
            names = notEqualIn (feature, tag)
        elif inFlag == 1:
            # look for feature "not in" (substring)
            names = notStrIn (feature, tag)
        elif inFlag == 2:
            # look for word not in
            names = notWordIn (feature, tag)
    elif choice == 'less than':
        names = lessThan (feature, tag)
                    
    if first:
        first = False
        result = names
    else:
        result = result & names

    return first, result
    


"""
------ section 2 ------
"""

def clear (request):
    """
    clear choice and selection variables for user screen
    """

    from django.shortcuts import render_to_response
    import datetime
    
    choice = []
    selection = []
    outList = []

    # preset choice, selection
    
    for i in range (21):
        choice.append ('')
        selection.append ('')

    date = datetime.datetime.now ()

    return render_to_response ("homePage.html", {'date': date, 'choice': choice, 'selection': selection, 'outList': outList})



def main (request):

    from django.shortcuts import render_to_response
    import datetime
    from dataHandler import  fromHardness,fromPercent,fromPli,fromPsi,fromRatio,fromSeconds, \
         fromViscosity,toFloat,toHardness,toPercent,toPli,toPsi, \
         toInt,toRatio,toSeconds,toViscosity
          
    mainDict = {}       # main dictionaly - used as data base

    # feature accumulators
    nameS = []
    madeByS = []
    websiteS = []
    classS = []
    polymerS = []
    typeS = []
    mixRatioS = []
    potLifeS = []
    demoldTimeS = []
    sizeS = []
    weightS = []
    priceS = []
    viscosityS = []
    hardnessS = []
    specificVolumeS = []
    colorS = []
    shrinkageS = []
    elongationS = []
    tearStrengthS = []
    compStrengthS = []
    tensileStrengthS = []


    # read back data from datastore
    try:
        # has main dictionary been loaded?
        if md:
            pass
    except:
        md = open ('C:/polymers/data/mainDict.txt')
        mainDict = eval (md.read())

    

    # flag and bucket for first filter results
    first = True
    flag0 = True
    result = set ()  

    choice = []
    selection = []

    # preset choice, selection
    for i in range (21):
        choice.append ('')
        selection.append ('')

    # note that inFlag is set True when you may want to find a substring
    # within a feature description.


    
    # name 0
    if 'nameCmp' in request.GET and request.GET ['nameCmp'] != 'any':        
        choice [0] = request.GET ['nameCmp']
        
        try:
        # has this feature been loaded?
            if f0:
                pass
        except:
            # no? load it now.
            f0 = open ('C:/polymers/data/nameIndex.txt')
            temp = f0.read ()
            nameS = eval (temp)
            
        # check for wants min and max (question mark)
        if choice [0] == '?':
            tempMin = min (nameS) [0]
            tempMax = max (nameS) [0]
            selection [0] = ('%s - %s' % (tempMin, \
                                            tempMax))
        elif 'name' in request.GET:
            name_ = request.GET ['name']
            selection [0] = name_
            
            
            name_ = name_.lower ()
            if name_ != 0:
                inFlag = 1
            # get tags that meet criterion
                first, result = selectTags (first,result,choice[0], \
                                    nameS,name_,inFlag)

    
    # madeBy 1
    if 'madeByCmp' in request.GET and request.GET ['madeByCmp'] != 'any':        
        choice [1] = request.GET ['madeByCmp']
        
        try:
        # has this feature been loaded?
            if f1:
                pass
        except:
            # no? load it now.
            f1 = open ('C:/polymers/data/madeByIndex.txt')
            temp = f1.read ()
            madeByS = eval (temp)
            
        # check for wants min and max (question mark)
        if choice [1] == '?':
            tempMin = min (madeByS) [0]
            tempMax = max (madeByS) [0]
            selection [1] = ('%s - %s' % (tempMin, \
                                            tempMax))
        elif 'madeBy' in request.GET:
            madeBy_ = request.GET ['madeBy']
            selection [1] = madeBy_
            
            
            madeBy_ = madeBy_.lower ()
            if madeBy_ != 0:
                inFlag = 1
            # get tags that meet criterion
                first, result = selectTags (first,result,choice[1], \
                                    madeByS,madeBy_,inFlag)

    
    # website 2
    if 'websiteCmp' in request.GET and request.GET ['websiteCmp'] != 'any':        
        choice [2] = request.GET ['websiteCmp']
        
        try:
        # has this feature been loaded?
            if f2:
                pass
        except:
            # no? load it now.
            f2 = open ('C:/polymers/data/websiteIndex.txt')
            temp = f2.read ()
            websiteS = eval (temp)
            
        # check for wants min and max (question mark)
        if choice [2] == '?':
            tempMin = min (websiteS) [0]
            tempMax = max (websiteS) [0]
            selection [2] = ('%s - %s' % (tempMin, \
                                            tempMax))
        elif 'website' in request.GET:
            website_ = request.GET ['website']
            selection [2] = website_
            
            
            #  convert to lower - shouldn't get here!
            website_ = website_.lower ()
            if website_ != 0:
                inFlag = 0
            # get tags that meet criterion
                first, result = selectTags (first,result,choice[2], \
                                    websiteS,website_,inFlag)

    
    # class 3
    if 'classCmp' in request.GET and request.GET ['classCmp'] != 'any':        
        choice [3] = request.GET ['classCmp']
        
        try:
        # has this feature been loaded?
            if f3:
                pass
        except:
            # no? load it now.
            f3 = open ('C:/polymers/data/classIndex.txt')
            temp = f3.read ()
            classS = eval (temp)
            
        # check for wants min and max (question mark)
        if choice [3] == '?':
            tempMin = min (classS) [0]
            tempMax = max (classS) [0]
            selection [3] = ('%s - %s' % (tempMin, \
                                            tempMax))
        elif 'class' in request.GET:
            class_ = request.GET ['class']
            selection [3] = class_
            
            
            class_ = class_.lower ()
            if class_ != 0:
                inFlag = 1
            # get tags that meet criterion
                first, result = selectTags (first,result,choice[3], \
                                    classS,class_,inFlag)

    
    # polymer 4
    if 'polymerCmp' in request.GET and request.GET ['polymerCmp'] != 'any':        
        choice [4] = request.GET ['polymerCmp']
        
        try:
        # has this feature been loaded?
            if f4:
                pass
        except:
            # no? load it now.
            f4 = open ('C:/polymers/data/polymerIndex.txt')
            temp = f4.read ()
            polymerS = eval (temp)
            
        # check for wants min and max (question mark)
        if choice [4] == '?':
            tempMin = min (polymerS) [0]
            tempMax = max (polymerS) [0]
            selection [4] = ('%s - %s' % (tempMin, \
                                            tempMax))
        elif 'polymer' in request.GET:
            polymer_ = request.GET ['polymer']
            selection [4] = polymer_
            
            
            polymer_ = polymer_.lower ()
            if polymer_ != 0:
                inFlag = 1
            # get tags that meet criterion
                first, result = selectTags (first,result,choice[4], \
                                    polymerS,polymer_,inFlag)

    
    # type 5
    if 'typeCmp' in request.GET and request.GET ['typeCmp'] != 'any':        
        choice [5] = request.GET ['typeCmp']
        
        try:
        # has this feature been loaded?
            if f5:
                pass
        except:
            # no? load it now.
            f5 = open ('C:/polymers/data/typeIndex.txt')
            temp = f5.read ()
            typeS = eval (temp)
            
        # check for wants min and max (question mark)
        if choice [5] == '?':
            tempMin = min (typeS) [0]
            tempMax = max (typeS) [0]
            selection [5] = ('%s - %s' % (tempMin, \
                                            tempMax))
        elif 'type' in request.GET:
            type_ = request.GET ['type']
            selection [5] = type_
            
            
            type_ = type_.lower ()
            if type_ != 0:
                inFlag = 2
            # get tags that meet criterion
                first, result = selectTags (first,result,choice[5], \
                                    typeS,type_,inFlag)

    
    # mixRatio 6
    if 'mixRatioCmp' in request.GET and request.GET ['mixRatioCmp'] != 'any':        
        choice [6] = request.GET ['mixRatioCmp']
        
        try:
        # has this feature been loaded?
            if f6:
                pass
        except:
            # no? load it now.
            f6 = open ('C:/polymers/data/mixRatioIndex.txt')
            temp = f6.read ()
            mixRatioS = eval (temp)
            
        # check for wants min and max (question mark)
        if choice [6] == '?':
            tempMin = min (mixRatioS) [0]
            tempMax = max (mixRatioS) [0]
            tempMin = fromRatio (tempMin)
            tempMax = fromRatio (tempMax)
            selection [6] = ('%s - %s' % (tempMin, \
                                            tempMax))
        elif 'mixRatio' in request.GET:
            mixRatio_ = request.GET ['mixRatio']
            selection [6] = mixRatio_
            
            
            mixRatio_ = toRatio (mixRatio_)
            if mixRatio_ != 0:
                inFlag = 0
            # get tags that meet criterion
                first, result = selectTags (first,result,choice[6], \
                                    mixRatioS,mixRatio_,inFlag)

    
    # potLife 7
    if 'potLifeCmp' in request.GET and request.GET ['potLifeCmp'] != 'any':        
        choice [7] = request.GET ['potLifeCmp']
        
        try:
        # has this feature been loaded?
            if f7:
                pass
        except:
            # no? load it now.
            f7 = open ('C:/polymers/data/potLifeIndex.txt')
            temp = f7.read ()
            potLifeS = eval (temp)
            
        # check for wants min and max (question mark)
        if choice [7] == '?':
            tempMin = min (potLifeS) [0]
            tempMax = max (potLifeS) [0]
            tempMin = fromSeconds (tempMin)
            tempMax = fromSeconds (tempMax)
            selection [7] = ('%s - %s' % (tempMin, \
                                            tempMax))
        elif 'potLife' in request.GET:
            potLife_ = request.GET ['potLife']
            selection [7] = potLife_
            
            
            # convert to seconds
            potLife_ = toSeconds (potLife_)
            if potLife_ != 0:
                inFlag = 0
            # get tags that meet criterion
                first, result = selectTags (first,result,choice[7], \
                                    potLifeS,potLife_,inFlag)

    
    # demoldTime 8
    if 'demoldTimeCmp' in request.GET and request.GET ['demoldTimeCmp'] != 'any':        
        choice [8] = request.GET ['demoldTimeCmp']
        
        try:
        # has this feature been loaded?
            if f8:
                pass
        except:
            # no? load it now.
            f8 = open ('C:/polymers/data/demoldTimeIndex.txt')
            temp = f8.read ()
            demoldTimeS = eval (temp)
            
        # check for wants min and max (question mark)
        if choice [8] == '?':
            tempMin = min (demoldTimeS) [0]
            tempMax = max (demoldTimeS) [0]
            tempMin = fromSeconds (tempMin)
            tempMax = fromSeconds (tempMax)
            selection [8] = ('%s - %s' % (tempMin, \
                                            tempMax))
        elif 'demoldTime' in request.GET:
            demoldTime_ = request.GET ['demoldTime']
            selection [8] = demoldTime_
            
            
            # convert to seconds
            demoldTime_ = toSeconds (demoldTime_)
            if demoldTime_ != 0:
                inFlag = 0
            # get tags that meet criterion
                first, result = selectTags (first,result,choice[8], \
                                    demoldTimeS,demoldTime_,inFlag)

    
    # size 9
    if 'sizeCmp' in request.GET and request.GET ['sizeCmp'] != 'any':        
        choice [9] = request.GET ['sizeCmp']
        
        try:
        # has this feature been loaded?
            if f9:
                pass
        except:
            # no? load it now.
            f9 = open ('C:/polymers/data/sizeIndex.txt')
            temp = f9.read ()
            sizeS = eval (temp)
            
        # check for wants min and max (question mark)
        if choice [9] == '?':
            tempMin = min (sizeS) [0]
            tempMax = max (sizeS) [0]
            selection [9] = ('%s - %s' % (tempMin, \
                                            tempMax))
        elif 'size' in request.GET:
            size_ = request.GET ['size']
            selection [9] = size_
            
            
            size_ = size_.lower ()
            if size_ != 0:
                inFlag = 1
            # get tags that meet criterion
                first, result = selectTags (first,result,choice[9], \
                                    sizeS,size_,inFlag)

    
    # weight 10
    if 'weightCmp' in request.GET and request.GET ['weightCmp'] != 'any':        
        choice [10] = request.GET ['weightCmp']
        
        try:
        # has this feature been loaded?
            if f10:
                pass
        except:
            # no? load it now.
            f10 = open ('C:/polymers/data/weightIndex.txt')
            temp = f10.read ()
            weightS = eval (temp)
            
        # check for wants min and max (question mark)
        if choice [10] == '?':
            tempMin = min (weightS) [0]
            tempMax = max (weightS) [0]
            selection [10] = ('%s - %s' % (tempMin, \
                                            tempMax))
        elif 'weight' in request.GET:
            weight_ = request.GET ['weight']
            selection [10] = weight_
            
            
            # convert to float
            weight_ = toFloat (weight_)
            if weight_ != 0:
                inFlag = 0 
            # get tags that meet criterion
                first, result = selectTags (first,result,choice[10], \
                                    weightS,weight_,inFlag)

    
    # price 11
    if 'priceCmp' in request.GET and request.GET ['priceCmp'] != 'any':        
        choice [11] = request.GET ['priceCmp']
        
        try:
        # has this feature been loaded?
            if f11:
                pass
        except:
            # no? load it now.
            f11 = open ('C:/polymers/data/priceIndex.txt')
            temp = f11.read ()
            priceS = eval (temp)
            
        # check for wants min and max (question mark)
        if choice [11] == '?':
            tempMin = min (priceS) [0]
            tempMax = max (priceS) [0]
            selection [11] = ('%s - %s' % (tempMin, \
                                            tempMax))
        elif 'price' in request.GET:
            price_ = request.GET ['price']
            selection [11] = price_
            
            
            # convert to float
            price_ = toFloat (price_)
            if price_ != 0:
                inFlag = 0 
            # get tags that meet criterion
                first, result = selectTags (first,result,choice[11], \
                                    priceS,price_,inFlag)

    
    # viscosity 12
    if 'viscosityCmp' in request.GET and request.GET ['viscosityCmp'] != 'any':        
        choice [12] = request.GET ['viscosityCmp']
        
        try:
        # has this feature been loaded?
            if f12:
                pass
        except:
            # no? load it now.
            f12 = open ('C:/polymers/data/viscosityIndex.txt')
            temp = f12.read ()
            viscosityS = eval (temp)
            
        # check for wants min and max (question mark)
        if choice [12] == '?':
            tempMin = min (viscosityS) [0]
            tempMax = max (viscosityS) [0]
            tempMin = fromViscosity (tempMin)
            tempMax = fromViscosity (tempMax)
            selection [12] = ('%s - %s' % (tempMin, \
                                            tempMax))
        elif 'viscosity' in request.GET:
            viscosity_ = request.GET ['viscosity']
            selection [12] = viscosity_
            
            
            viscosity_ = toViscosity (viscosity_)
            if viscosity_ != 0:
                inFlag = 0
            # get tags that meet criterion
                first, result = selectTags (first,result,choice[12], \
                                    viscosityS,viscosity_,inFlag)

    
    # hardness 13
    if 'hardnessCmp' in request.GET and request.GET ['hardnessCmp'] != 'any':        
        choice [13] = request.GET ['hardnessCmp']
        
        try:
        # has this feature been loaded?
            if f13:
                pass
        except:
            # no? load it now.
            f13 = open ('C:/polymers/data/hardnessIndex.txt')
            temp = f13.read ()
            hardnessS = eval (temp)
            
        # check for wants min and max (question mark)
        if choice [13] == '?':
            tempMin = min (hardnessS) [0]
            tempMax = max (hardnessS) [0]
            tempMin = fromHardness (tempMin)
            tempMax = fromHardness (tempMax)
            selection [13] = ('%s - %s' % (tempMin, \
                                            tempMax))
        elif 'hardness' in request.GET:
            hardness_ = request.GET ['hardness']
            selection [13] = hardness_
            
            
            # convert to hardness
            hardness_ = toHardness (hardness_)
            if hardness_ != 0:
                inFlag = 0
            # get tags that meet criterion
                first, result = selectTags (first,result,choice[13], \
                                    hardnessS,hardness_,inFlag)

    
    # specificVolume 14
    if 'specificVolumeCmp' in request.GET and request.GET ['specificVolumeCmp'] != 'any':        
        choice [14] = request.GET ['specificVolumeCmp']
        
        try:
        # has this feature been loaded?
            if f14:
                pass
        except:
            # no? load it now.
            f14 = open ('C:/polymers/data/specificVolumeIndex.txt')
            temp = f14.read ()
            specificVolumeS = eval (temp)
            
        # check for wants min and max (question mark)
        if choice [14] == '?':
            tempMin = min (specificVolumeS) [0]
            tempMax = max (specificVolumeS) [0]
            selection [14] = ('%s - %s' % (tempMin, \
                                            tempMax))
        elif 'specificVolume' in request.GET:
            specificVolume_ = request.GET ['specificVolume']
            selection [14] = specificVolume_
            
            
            # convert to float
            specificVolume_ = toFloat (specificVolume_)
            if specificVolume_ != 0:
                inFlag = 0 
            # get tags that meet criterion
                first, result = selectTags (first,result,choice[14], \
                                    specificVolumeS,specificVolume_,inFlag)

    
    # color 15
    if 'colorCmp' in request.GET and request.GET ['colorCmp'] != 'any':        
        choice [15] = request.GET ['colorCmp']
        
        try:
        # has this feature been loaded?
            if f15:
                pass
        except:
            # no? load it now.
            f15 = open ('C:/polymers/data/colorIndex.txt')
            temp = f15.read ()
            colorS = eval (temp)
            
        # check for wants min and max (question mark)
        if choice [15] == '?':
            tempMin = min (colorS) [0]
            tempMax = max (colorS) [0]
            selection [15] = ('%s - %s' % (tempMin, \
                                            tempMax))
        elif 'color' in request.GET:
            color_ = request.GET ['color']
            selection [15] = color_
            
            
            color_ = color_.lower ()
            if color_ != 0:
                inFlag = 1
            # get tags that meet criterion
                first, result = selectTags (first,result,choice[15], \
                                    colorS,color_,inFlag)

    
    # shrinkage 16
    if 'shrinkageCmp' in request.GET and request.GET ['shrinkageCmp'] != 'any':        
        choice [16] = request.GET ['shrinkageCmp']
        
        try:
        # has this feature been loaded?
            if f16:
                pass
        except:
            # no? load it now.
            f16 = open ('C:/polymers/data/shrinkageIndex.txt')
            temp = f16.read ()
            shrinkageS = eval (temp)
            
        # check for wants min and max (question mark)
        if choice [16] == '?':
            tempMin = min (shrinkageS) [0]
            tempMax = max (shrinkageS) [0]
            selection [16] = ('%s - %s' % (tempMin, \
                                            tempMax))
        elif 'shrinkage' in request.GET:
            shrinkage_ = request.GET ['shrinkage']
            selection [16] = shrinkage_
            
            
            # convert to float
            shrinkage_ = toFloat (shrinkage_)
            if shrinkage_ != 0:
                inFlag = 0 
            # get tags that meet criterion
                first, result = selectTags (first,result,choice[16], \
                                    shrinkageS,shrinkage_,inFlag)

    
    # elongation 17
    if 'elongationCmp' in request.GET and request.GET ['elongationCmp'] != 'any':        
        choice [17] = request.GET ['elongationCmp']
        
        try:
        # has this feature been loaded?
            if f17:
                pass
        except:
            # no? load it now.
            f17 = open ('C:/polymers/data/elongationIndex.txt')
            temp = f17.read ()
            elongationS = eval (temp)
            
        # check for wants min and max (question mark)
        if choice [17] == '?':
            tempMin = min (elongationS) [0]
            tempMax = max (elongationS) [0]
            tempMin = fromPercent (tempMin)
            tempMax = fromPercent (tempMax)
            selection [17] = ('%s - %s' % (tempMin, \
                                            tempMax))
        elif 'elongation' in request.GET:
            elongation_ = request.GET ['elongation']
            selection [17] = elongation_
            
            
            # convert to percent
            elongation_ = toPercent (elongation_)
            if elongation_ != 0:
                inFlag = 0
            # get tags that meet criterion
                first, result = selectTags (first,result,choice[17], \
                                    elongationS,elongation_,inFlag)

    
    # tearStrength 18
    if 'tearStrengthCmp' in request.GET and request.GET ['tearStrengthCmp'] != 'any':        
        choice [18] = request.GET ['tearStrengthCmp']
        
        try:
        # has this feature been loaded?
            if f18:
                pass
        except:
            # no? load it now.
            f18 = open ('C:/polymers/data/tearStrengthIndex.txt')
            temp = f18.read ()
            tearStrengthS = eval (temp)
            
        # check for wants min and max (question mark)
        if choice [18] == '?':
            tempMin = min (tearStrengthS) [0]
            tempMax = max (tearStrengthS) [0]
            tempMin = fromPli (tempMin)
            tempMax = fromPli (tempMax)
            selection [18] = ('%s - %s' % (tempMin, \
                                            tempMax))
        elif 'tearStrength' in request.GET:
            tearStrength_ = request.GET ['tearStrength']
            selection [18] = tearStrength_
            
            
            #  convert to lower - shouldn't get here!
            tearStrength_ = tearStrength_.lower ()
            if tearStrength_ != 0:
                inFlag = 0
            # get tags that meet criterion
                first, result = selectTags (first,result,choice[18], \
                                    tearStrengthS,tearStrength_,inFlag)

    
    # compStrength 19
    if 'compStrengthCmp' in request.GET and request.GET ['compStrengthCmp'] != 'any':        
        choice [19] = request.GET ['compStrengthCmp']
        
        try:
        # has this feature been loaded?
            if f19:
                pass
        except:
            # no? load it now.
            f19 = open ('C:/polymers/data/compStrengthIndex.txt')
            temp = f19.read ()
            compStrengthS = eval (temp)
            
        # check for wants min and max (question mark)
        if choice [19] == '?':
            tempMin = min (compStrengthS) [0]
            tempMax = max (compStrengthS) [0]
            tempMin = fromPsi (tempMin)
            tempMax = fromPsi (tempMax)
            selection [19] = ('%s - %s' % (tempMin, \
                                            tempMax))
        elif 'compStrength' in request.GET:
            compStrength_ = request.GET ['compStrength']
            selection [19] = compStrength_
            
            
            # convert to int
            compStrength_ = toPsi (compStrength_)
            if compStrength_ != 0:
                inFlag = 0
            # get tags that meet criterion
                first, result = selectTags (first,result,choice[19], \
                                    compStrengthS,compStrength_,inFlag)

    
    # tensileStrength 20
    if 'tensileStrengthCmp' in request.GET and request.GET ['tensileStrengthCmp'] != 'any':        
        choice [20] = request.GET ['tensileStrengthCmp']
        
        try:
        # has this feature been loaded?
            if f20:
                pass
        except:
            # no? load it now.
            f20 = open ('C:/polymers/data/tensileStrengthIndex.txt')
            temp = f20.read ()
            tensileStrengthS = eval (temp)
            
        # check for wants min and max (question mark)
        if choice [20] == '?':
            tempMin = min (tensileStrengthS) [0]
            tempMax = max (tensileStrengthS) [0]
            tempMin = fromPsi (tempMin)
            tempMax = fromPsi (tempMax)
            selection [20] = ('%s - %s' % (tempMin, \
                                            tempMax))
        elif 'tensileStrength' in request.GET:
            tensileStrength_ = request.GET ['tensileStrength']
            selection [20] = tensileStrength_
            
            
            # convert to int
            tensileStrength_ = toPsi (tensileStrength_)
            if tensileStrength_ != 0:
                inFlag = 0
            # get tags that meet criterion
                first, result = selectTags (first,result,choice[20], \
                                    tensileStrengthS,tensileStrength_,inFlag)

    

    """
------ section 3 ------
"""

    # move result (a set) to a list
    listResult = list (result)
    # sort list result
    listResult.sort ()
        
    # set up output lists
    outList = []

    for name in listResult:
        outList.append (mainDict [name])
            
    
    """ 
    print 'outList \n'        
    print outList
    """
    
    

    
    date = datetime.datetime.now ()

    return render_to_response ("homePage.html", {'date': date, 'choice': choice, 'selection': selection,
                                                  'outList': outList })