#!/s/std/bin/python

import sys
import os
import string
import whrandom
import random
import time
import re

Qheader = """<?xml version="1.0"?>
<!-- Nasdaq Stock Quotes.  Randomly genenrated. -->
<!DOCTYPE Quotes SYSTEM "quote.dtd">
<Quotes>
"""

Matcher = re.compile("^(.*)<Time>.*")

def process_file() :
    timenow = time.ctime(time.time())
    tfn = "q_tmp_.xml"
    qfn = "quotes.xml"
    tmpf = open(tfn, "w")
    qf = open(qfn, "r")
    for line in qf.readlines() :
	if(line[:7]=="<Quote>") :
	    process_line(tmpf, line, timenow)
	else :
	    tmpf.write(line)
    tmpf.close()
    qf.close()
    os.rename(tfn, qfn)
    # end of process file
    
def process_line(tf, line, timenow) :
    m = Matcher.match(line)
    outl = m.group(1)
    
    openp = whrandom.uniform(20.0, 200.0)     
    closep = openp - whrandom.random()       
    change = random.gauss(0, 1)              
    if(change > 10.0) :                      
	change = 10.0                    
    if(change < -10.0) :                     
   	change = -10.0                   
    currp = openp * (1.0 + change/100.0)     
    volume = whrandom.randint(1000, 1000000) 
    employee = whrandom.randint(10, 100000)  
    dl = whrandom.uniform(openp/2, openp)    
    dh = whrandom.uniform(openp, openp*2)    
    yl = whrandom.uniform(dl/3, dl)          
    yh = whrandom.uniform(dh, dh*3)          
    ya = whrandom.uniform(yl, yh)             

    outl = outl + "<Time><Year>1999</Year>"                              
    outl = outl + "<Date>%(timenow)s</Date></Time>" % vars()                   
    outl = outl + "<CurrentPrice>%(currp).2f</CurrentPrice>" % vars()    
    outl = outl + "<OpenPrice>%(openp).2f</OpenPrice>" % vars()          
    outl = outl + "<Change>%(change).2f</Change>" % vars()               
    outl = outl + "<PrevClosePrice>%(closep).2f</PrevClosePrice>" % vars()
    outl = outl + "<Volume>%(volume)d</Volume>" % vars()                 
    outl = outl + "<DayRange><Low>%(dl).2f</Low>" % vars()               
    outl = outl + "<High>%(dh).2f</High></DayRange>" % vars()            
    outl = outl + "<Week_52_Info><Low>%(yl).2f</Low>" % vars()           
    outl = outl + "<High>%(yh).2f</High>" % vars()                       
    outl = outl + "<Average>%(ya).2f</Average></Week_52_Info>" % vars()  
    outl = outl + "</Quote>\n"                                            

    tf.write(outl)    
    tf.flush()
    # end of process_line
    
if(__name__=="__main__") :
    while(1) :
	time.sleep(30)
	process_file()
