<?

/*
Ron Paul 2008 donation tracker, graph generator, rate smoother, and telethermometer.
Leo Made this
Use whatever techniques you find here as you see fit, as long as you credit and link to me. Also, I urge you to give me a lot of money.
*/
error_reporting(E_ERROR E_PARSE);
require_once(
"jpgraph/jpgraph.php");
require_once(
"jpgraph/jpgraph_line.php");
require_once(
"jpgraph/jpgraph_date.php");
define('SMOOTHMINUTES',15);

define('HALFLIFE',259200*2); //6 days


//connect to db
$GLOBALS['c']=mysql_connect("*****""*****""*****") or die(mysql_error());
mysql_select_db("*****");


/*
$ar=mysql_query("SELECT *, UNIX_TIMESTAMP(time) as utime FROM roncash ORDER BY time ASC;");
while(($row=mysql_fetch_assoc($ar))!==false)
{//moving average
    $thisPoint=$row;
    if(empty($prevPoint))
        $shift=0;
    else
    {
        $dTime=($thisPoint['utime']-$prevPoint['utime']);
        $shift = exp(-(log(2)/HALFLIFE) * $dTime);
    }
    $thisPoint['dCashEMA'] = $prevPoint['dCashEMA']*($shift) + (1-$shift)*$thisPoint['dCash'];
    $thisPoint['dPeopleEMA'] = $prevPoint['dPeopleEMA']*($shift) + (1-$shift)*$thisPoint['dPeople'];
    echo "$shift - `dCashEMA`='" . $thisPoint['dCashEMA'] . "', dPeopleEMA='${thisPoint['dPeopleEMA']}', time = '${thisPoint['time']}'\n";
    mysql_query("UPDATE roncash SET `dCashEMA`='" . $thisPoint['dCashEMA'] . "', dPeopleEMA='${thisPoint['dPeopleEMA']}' WHERE time = '${thisPoint['time']}'") or die(mysql_error());
    $prevPoint=$thisPoint;
}    
die();*/

//check if there are any new points to add. if so, add them. 
echo " ======== updates ======== \n";
update();

/*
echo "doing averages.";
$ar=mysql_query("SELECT * FROM roncash WHERE time < FROM_UNIXTIME(" . (time() - SMOOTHMINUTES*60*3*2). ");");
while(($rrr=mysql_fetch_assoc($ar))!==false)
{
    updateDailyAverage($rrr);
}
die();
*/



echo "\n ======== datafetch ======== \n";
//fetch present data
echo "  get current data...";
$offlineCash=mysql_fetch_assoc(mysql_query("SELECT val FROM `roncash-vars` WHERE var='offlineCash'"));
$offlineCash=$offlineCash['val'];

$quartersEnd ='2008-04-01 00:00:00';

$r=mysql_query("SELECT time, dCash, people, dPeople, dCashEMA, dPeopleEMA, donors, dDonors, if((dDonors/dPeople)>1, 1, dDonors/dPeople)*100 as percentNewDonors, offlineCount, offlineCash, (dCash/dPeople)*1000 as dDonations, (cash + (if(isnull(offlineCash), $offlineCash, 0)) + roncash.dCashEMA *((UNIX_TIMESTAMP('$quartersEnd') - UNIX_TIMESTAMP(time))/3.6))/1000000 as projection, cash + (if(isnull(offlineCash), $offlineCash, 0)) as cash FROM `roncash` order by time"$c);
$i=0;  //dirtycode
$q=0;  //dirtycode
$e=0;  //dirtycode
for($d=3$d>=0$d--)
{
    
$day[$d]=time()+3*60*60 date('H', (time()+3*60*60))*60*60 date('i')*60 date('s') - $d*60*60*24;
    
$daa[$d]=date('l dS \of F Y h:i:s A'$day[$d]);
}
echo 
"  done\n";

echo 
"  get averages...";
//get average
$avgRes=mysql_query("SELECT *, (dCash/dPeople)*1000 as dDonations FROM `roncash-avg` order by time") or die(mysql_error());
$i=0;
while((
$avgRow=mysql_fetch_assoc($avgRes))!==false)
{
    
$range['avg']['time'][$i]=$avgRow['time'];
    
$range['avg']['cash'][$i]=$avgRow['cash']/1000;
    
$range['avg']['dCash'][$i]=$avgRow['dCash'];
    
$range['avg']['people'][$i]=$avgRow['people'];
    
$range['avg']['dPeople'][$i]=$avgRow['dPeople'];
    
$range['avg']['dDonations'][$i]=$avgRow['dDonations'];
    
//$range['avg']['dDonors'][$i]=$avgRow['dDonors'];
    //$range['avg']['percentNewDonors'][$i]=$avgRow['percentNewDonors'];
    
$i++;
}
echo 
" ... ";
$i=0;
while((
$row=mysql_fetch_assoc($r))!==false)
{
    
$total['time'][$i]=strtotime($row['time']);
    
$total['cash'][$i]=$row['cash']/1000;
    
$total['dCash'][$i]=(float) $row['dCash'];
    
$total['projection'][$i]=(float) $row['projection'];
    
$total['people'][$i]=$row['people'];
    
$total['dPeople'][$i]=(float) $row['dPeople'];
    
$total['dDonations'][$i]=(float) $row['dDonations'];
    
$total['dDonors'][$i]=(float) $row['dDonors'];
    
$total['percentNewDonors'][$i]=(float) $row['percentNewDonors'];
    
    
//points for today's graph. the if statement is overkill, but what the hell, it's affordable.
    
$thisTime strtotime($row['time']);
    if((
$whichRange=when($thisTime$day))!==false)
    {

        if(empty(
$range[$whichRange]['cash']))
            
$start[$whichRange]['cash']=$total['cash'][$i];
    
        
$range[$whichRange]['time'][]=$total['time'][$i] - $day[$whichRange];    
        
        foreach(array(
'cash','dCash','people','dPeople','dDonations''dDonors''percentNewDonors''projection') as $col)
        {
            
$range[$whichRange][$col][]= ($col == 'cash') ? $total[$col][$i] - $start[$whichRange]['cash'] : $total[$col][$i];
        }
        
$e++;
    }
    
$i++;
}
echo 
"done\n";

$style=array(
    
0=>array(
        
'color'=>'#A42B2B',
        
'shade'=>true,
        
'weight'=>3,
        
'highlightPoints'=>true,
        
'name'=>'today'),
    
1=>array(
        
'color'=>'#FF4F77',
        
'shade'=>true,
        
'weight'=>1,
        
'highlightPoints'=>false,
        
'name'=>'yesterday'),
    
2=>array(
        
'color'=>'#4F5DFF',
        
'shade'=>true,
        
'weight'=>1,
        
'highlightPoints'=>false,
        
'name'=>'2 days ago'),
    
3=>array(
        
'color'=>'#4DCF65',
        
'shade'=>true,
        
'weight'=>1,
        
'highlightPoints'=>false,
        
'name'=>'3 days ago'),
    
'avg'=>array(
        
'color'=>'#666666@0.5',
        
'shade'=>false,
        
'highlightPoints'=>false,
        
'weight'=>9,
        
'highlightPoints'=>false,
        
'name'=>'average day'),
    
'projection'=>array(
        
'color'=>'#666666',
        
'shade'=>false,
        
'highlightPoints'=>false,
        
'weight'=>1,
        
'highlightPoints'=>false,
        
'name'=>'projection'));

$label['total']['cash']='Total donations, in $1000                                                                                                        note: graph includes offline donations';
$label['total']['dCash']='Donation rate, in $1000/hour';
$label['total']['people']='Total donors';
$label['total']['donors']='Total first-time (unique) donors';
$label['total']['dDonors']='First time donor rate, in ppl/hour';
$label['total']['dPeople']='Donation rate, in donations/hour';
$label['total']['dDonations']='Donation size per person, in $';
$label['total']['projection']='Quarter projection, in millions of dollars';


$label['daily']['cash']='Daily total donations, in $1000';
$label['daily']['dCash']='Daily donation rate, in $1000/hour';
$label['daily']['people']='Daily total number of donations';
$label['daily']['dPeople']='Daily donor (new and repeated) rate, in ppl/hour';
$label['daily']['dDonors']='Daily new donor rate, in ppl/hour';
$label['daily']['percentNewDonors']='Percent new donors, %';
$label['daily']['dDonations']='Daily donation size per person, in $/person';
$label['daily']['projection']='Daily quarter projection breakdown, in millions of dollars';


echo 
"  preparing data for output...";
foreach(array(
'cash','dCash','dPeople','dDonations''projection''dDonors''percentNewDonors') as $name)
{
    foreach (
$range as $r=>$rr)
    {
        
$data[$name][$r]=array('x'=>$rr['time'], 'y'=>$rr[$name], 'color'=>$style[$r]['color'],'highlightPoints'=>$style[$r]['highlightPoints'], 'shade'=>$style[$r]['shade'], 'weight'=>$style[$r]['weight'], 'name'=>$style[$r]['name']);
    }
}

//damn this thing is a hack.
unset($data['dDonors']['avg']);
unset(
$data['percentNewDonors']['avg']);

echo 
"done\n";

//generate the page

echo "\n ======== output ========\n";
echo 
"  writing the page...";
exec("php -e ****/paulcash/dynamic.php > ****/tmp/index.html.temp");
echo 
"  done. moving...";
exec("mv ****/tmp/index.html.temp ****/paulcash/index.html");
echo 
"done.\n\n";

//create graphs for today 
    
    
    
unset($data['projection']['avg']);
    
    echo 
"  writing daily graphs:        cash";
    
graph(array('title'=>$label['daily']['cash'], 'width'=>950'height'=>380'datasets'=>$data['cash'], 'path'=>"****/paulcash/today-paulcash.png"'labeler'=>'hours'));
    echo 
"    dcash";
    
graph(array('title'=>$label['daily']['dCash'], 'width'=>950'height'=>300'datasets'=>$data['dCash'], 'path'=>"****/paulcash/today-paulflow.png"'labeler'=>'hours'));
    echo 
"    dPeople";
    
graph(array('title'=>$label['daily']['dPeople'], 'width'=>950'height'=>300'datasets'=>$data['dPeople'], 'path'=>"****/paulcash/today-paulpeople.png"'labeler'=>'hours'));
    echo 
"    dDonations";
    
graph(array('title'=>$label['daily']['dDonations'], 'width'=>950'height'=>300'datasets'=>$data['dDonations'], 'path'=>"****/paulcash/today-paulsize.png"'labeler'=>'hours'));
    echo 
"    dDonors";
    
graph(array('title'=>$label['daily']['dDonors'], 'width'=>950'height'=>200'datasets'=>$data['dDonors'], 'path'=>"****/paulcash/today-pauldonors.png"'labeler'=>'hours'));
    echo 
"    percentNewDonors";
    
graph(array('title'=>$label['daily']['percentNewDonors'], 'width'=>950'height'=>200'datasets'=>$data['percentNewDonors'], 'path'=>"****/paulcash/today-paulpercentNewDonors.png"'labeler'=>'hours'));
    echo 
"    ...done\n";
    
    
    echo 
"  writing projection graphs:";
    
graph(array('title'=>$label['daily']['projection'], 'width'=>950'height'=>250'datasets'=>$data['projection'], 'path'=>"****/paulcash/today-proj.png"'labeler'=>'hours'));
    
graph(array('title'=>'Quarter Projections''width'=>950'height'=>250'x'=>$total['time'], 'y'=>$total['projection'], 'path'=>"****/paulcash/total-proj.png"'labeler'=>'for2'));
    echo 
"    ...    ...    ...    ...           ...done\n";
    
    
//create graphs for the whole quarter
    
    
echo "  writing total graphs:        cash";
    
graph(array('title'=>$label['total']['cash'], 'width'=>950'height'=>480'x'=>$total['time'], 'y'=>$total['cash'], 'path'=>"****/paulcash/total-paulcash.png"'labeler'=>'for2'));
    echo 
"    dCash";
    
graph(array('title'=>$label['total']['dCash'], 'width'=>950'height'=>300'x'=>$total['time'], 'y'=>$total['dCash'], 'path'=>"****/paulcash/total-paulflow.png"'labeler'=>'for2'));
    echo 
"    dPeople";
    
graph(array('title'=>$label['total']['dPeople'], 'width'=>950'height'=>300'x'=>$total['time'], 'y'=>$total['dPeople'], 'path'=>"****/paulcash/total-paulpeople.png"'labeler'=>'for2'));
    echo 
"    dDonations";
    
graph(array('title'=>$label['total']['dDonations'], 'width'=>950'height'=>300'x'=>$total['time'], 'y'=>$total['dDonations'], 'path'=>"****/paulcash/total-paulsize.png"'labeler'=>'for2'));
    echo 
"    dDonors";
    
graph(array('title'=>$label['total']['dDonors'], 'width'=>950'height'=>200'x'=>$total['time'], 'y' => $total['dDonors'], 'path'=>"****/paulcash/total-pauldonors.png"'labeler'=>'for2'));
    echo 
"    percentNewDonors";
    
graph(array('title'=>$label['total']['percentNewDonors'], 'width'=>950'height'=>200'x'=>$total['time'], 'y' => $total['percentNewDonors'], 'yMin'=>0'yMax'=>100'path'=>"****/paulcash/total-paulpercentNewDonors.png"'labeler'=>'for2'));
    echo 
"    ...done\n";
    
    
    
//small ones
    
echo "  writing small daily graphs:    cash";
    
graph(array('title'=>$label['daily']['cash'],  'width'=>400'height'=>250'datasets'=>$data['cash'], 'path'=>"****/paulcash/today-paulcash-small.png"'labeler'=>'hours'));
    echo 
"    dcash";
    
graph(array('title'=>$label['daily']['dCash'],  'width'=>400'height'=>250'datasets'=>$data['dCash'], 'path'=>"****/paulcash/today-paulflow-small.png"'labeler'=>'hours'));
    echo 
"    dPeople";
    
graph(array('title'=>$label['daily']['dPeople'],  'width'=>400'height'=>250'datasets'=>$data['dPeople'], 'path'=>"****/paulcash/today-paulpeople-small.png"'labeler'=>'hours'));
    echo 
"    dDonations";
    
graph(array('title'=>$label['daily']['dDonations'],  'width'=>400'height'=>250'datasets'=>$data['dDonations'], 'path'=>"****/paulcash/today-paulsize-small.png"'yMin'=>0'yMax'=>100'labeler'=>'hours'));
    echo 
"    ...done\n";



function 
graph($p)
{
    
// Create the new graph
    
$graph = new Graph($p['width'],$p['height']);

    
// Slightly larger than normal margins at the bottom to have room for
    // the x-axis labels
    
$graph->SetMargin(40,20,20,50);
    
    
//var_dump(!empty($p['yMax']) || !empty($p['yMin']));
    
    
if(!empty($p['yMax']) || !empty($p['yMin']))
        
$graph->SetScale('datlin'$p['yMin'],$p['yMax']);
    elseif(!empty(
$p['y']))
        
$graph->SetScale('datlin',min($p['y']),max($p['y'])*1.05);
    else
        
$graph->SetScale('datlin');

    
// Set the angle for the labels to 90 degrees
    
$graph->xaxis->SetLabelAngle(0);
    
$graph->xaxis->scale->SetDateFormat('m/j');


    
//$graph->img->SetAntiAliasing();

    // Adjust the start/end to a specific alignment
    
$graph->xaxis->scale->SetTimeAlign(HOURADJ_2MINADJ_1);
    
$graph->xaxis->SetLabelFormatCallback((!empty($p['labeler'])) ? $p['labeler'] : 'format');
    
$graph->xgrid->Show (true,false);
    
$graph->ygrid->Show (true,true);
    
    
$graph->ygrid->SetFill (true'#EFFBFF','white');  //alternate fill
    
$graph->SetTickDensity(TICKD_SPARSETICKD_SPARSE);
    
    
    
$graph->xaxis->SetFont(FF_TIMES); 
    
$graph->yaxis->SetFont(FF_TIMES);
    
$graph->setMarginColor("#EFEFEF");
    
    if(!empty(
$p['y']))
    {    
$line = new LinePlot($p['y'],$p['x']);
        
$line->SetColor("#A42B2B");
        
$line->SetFastStroke();
        
$graph->Add($line);
    }
    else
    {
        
$q=0;
        
$lines=array();

        foreach(
$p['datasets'] as $k=>$data)
        {
            
$lines[$q] = new LinePlot($data['y'],$data['x']);
            
$lines[$q]->setColor($data['color']);
            if(
$data['shade'])
                
$lines[$q]->AddArea(0max($data['x']), LP_AREA_FILLED$data['color'] . '@0.8'false);
            
$lines[$q]->setWeight($data['weight']);
            if(
$data['highlightPoints'])
            {
                
$lines[$q]->mark->setType(MARK_CIRCLE);
                
$lines[$q]->mark->SetColor($data['color']);
                
$lines[$q]->mark->setWidth($data['weight']);
                
$lines[$q]->mark->show(true);
            }
            
$lines[$q]->setLegend($data['name']);
            
$graph->Add($lines[$q]);
            
$q++;    
        }
        
$graph->legend->SetFillColor('#EBEBEB@0.5'); 
    }
    
$graph->title->SetMargin (4);
    
$graph->title-> SetFontFF_TIMESFS_NORMAL11); 
    
$graph->title->align('left');
    
$graph->title->Set('          ' $p['title']);
    
$graph->title->SetColor('#3F3F3F');
    if(
$p['width']>500)
    {
        
$graph->footer->right->Set("Generated on " date('M j Y \a\t g:ia \E\S\T', (time() + 10800)));
        
$graph->footer-> center->Set("http://paulcash.slact.net");
        
$graph->footer-> center-> SetColor("blue");
        
$graph->footer-> center-> SetFontFF_ARIALFS_BOLD11); 
    }
    else
    {
        
$graph->footer->right->Set("" date('n/j/y \a\t g:ia \E\S\T', (time() + 10800)));
        
$graph->footer-> left->Set("http://paulcash.slact.net");
        
$graph->footer-> left-> SetColor("blue");
        
$graph->footer-> left-> SetFontFF_ARIALFS_BOLD11); 
        
        
//move the legend
        
$graph ->legend->Pos0.6,0.14,"top","left");
    }
    
$graph->Stroke($p['path'] . ".tmp");
    
rename($p['path'] . ".tmp"$p['path']);
}

function 
smooth($x$y$r$start=null$end=null$dVal)
{

    
//smooth graph using a normal distribution for weighing
    
echo "\nnow smoothing " count($x) . " points for $dVal ...\n";
    foreach(
$x as $i=>$v)
    {
        
$sum=1;
        echo 
"\n$i...";
        if(
$v $start && $v $end)
        {
            
$mSum=0;
            foreach(
$x as $ii=>$vv)
            {
                
                if(
$vv $v+($r*3) && $vv $v-($r*3))
                {
                    
                    
$m=normal($vv$r$v);
                    
$out[$i][$ii]=$m*$y[$ii];
                    
//echo("$m , $vv, {$y[$ii]}, " . $out[$i][$ii] . " \n");
                    
$mSum+=$m;
                }
            }
            
//now normalize
            
$out[$i]=array_sum($out[$i])*(1/$mSum);
            
mysql_query("UPDATE roncash SET $dVal = '{$out[$i]}' WHERE `time` = FROM_UNIXTIME(${x[$i]});") or die(mysql_error());
            echo 
"\r $i / $all - $out[$i]";
        }
        else 
        {
            echo 
"\r$i skipped                   ";
        
        }
    }
    return 
$out;
}
function 
for2($t)
{
    return 
format($t1);

}

function 
format($t$everyWhichDay=1)
{
    
$tee=explode(" "date("m j G g i a"$t));
    static 
$everyNth=2;
    static 
$nth=0;
    return (
$tee[1] % $everyWhichDay == && ((++$nth)%$everyNth)==0) ? ($tee[0] . "/" $tee[1]) : '';
    
    
    
//return date("G-i", $t)=="0-00" ? date("M j", $t) : ((date("i", $t)=='00') ? date("ga",$t) : '');
}

function 
hours($t)
{
    return (
$t%3600==0) ? (($t==0) ? '12am' : (($t/3600 12) ? ($t/3600 'am') : ($t==43200 '12pm' : (($t43200)/3600 'pm')))) : ''
}


function 
normal($x$stdev=1$mean=0)
{
//normal distribution
    
return(
        (
1/(sqrt(2*pi())))
        * 
exp(
            -(
pow(($x-$mean),2)) /
             (
2*pow($stdev,2))));
}

function 
update()
{
//messy update
    
$offlineCash=mysql_fetch_assoc(mysql_query("SELECT val FROM `roncash-vars` WHERE var='offlineCash'"));
    
$offlineCash=$offlineCash['val'];
    
    
$lastPoint=mysql_fetch_assoc(mysql_query("SELECT cash + (if(isnull(offlineCash), $offlineCash, 0)) as cash, people, time, dCash, dPeople, donors, offlineCash, offlineCount FROM roncash ORDER BY time DESC LIMIT 1"));

    
$last=strtotime($lastPoint['time']);
    
    echo 
"  Fetching current donation state...";
    
    
$f=file_get_contents("http://www.ronpaul2008.com/webservices/REST/donation.stats?format=nvp");
    
parse_str($f$rawParams);
    
    
    
$param['sum']=$rawParams['current_quarter_online_sum']+$rawParams['current_quarter_offline_sum'];
    
$param['count']=$rawParams['current_quarter_online_count']+$rawParams['current_quarter_offline_count'];
    
$param['time']=$rawParams['time'];
    
$param['donors']=$rawParams['current_quarter_donor_count'];
    
$param['offlineCount']=$rawParams['current_quarter_offline_count'];
    
$param['offlineCash']=$rawParams['current_quarter_offline_sum'];
    
    if((
$last +1*60) < ($param['time'] + 3*60*60))
    {
        echo 
"new enough. \n  Importing...";
        
//$dCash=smooth($time, $dCash, time() - strtotime("20 minutes ago"));
        
if(!empty($param['sum']))
        {    
        
            
            
mysql_query("INSERT INTO roncash SET time = FROM_UNIXTIME(" mysql_real_escape_string($param['time'] + 60*60*3) . "), cash = '" mysql_real_escape_string($param['sum']) . "', dCash='" . ($param['sum']-$lastPoint['cash'])/(($param['time'] + 60*60*3) - strtotime($lastPoint['time'])) . "', dPeople='". ($param['count']-$lastPoint['people'])/(($param['time'] + 60*60*3) - strtotime($lastPoint['time'])) ."', people='" mysql_real_escape_string($param['count']) . "', donors='" mysql_real_escape_string($param['donors']) . "', offlineCash = '" $param['offlineCash'] . "', offlineCount='" .$param['offlineCount']. "' ;") or die(mysql_error());
        
        
        }
    
        echo 
"done.\n  fetching smoothable points...";
    
        
$mean=3*60*60 $param['time'];
        
$stDev SMOOTHMINUTES*60;
        
        
$res mysql_query("SELECT * FROM roncash WHERE time < FROM_UNIXTIME(" . ($mean+$stDev*3*2) . ") AND time > FROM_UNIXTIME(" . ($mean-$stDev*3*2) . ") order by time;") or die(mysql_error());
        
$i=0;
        while((
$row=mysql_fetch_assoc($res))!==false)
        {
            
$time[$i]=strtotime($row['time']);
            
$dTime=($time[$i] - $time[$i-1]);
            
$cash[$i]=$row['cash']/1000;
            
//echo($cash2[$i] .", ". ($cash2[$i] - $cash2[$i-1]) . ", " . $dTime . "\n");
            
$people[$i]=$row['people'];
            
$donors[$i]=$row['donors'];
            
$dCash[$i]=($cash[$i]-$cash[$i-1])/$dTime*60*60;
            
$dPeople[$i]=($people[$i]-$people[$i-1])/$dTime*60*60;
            
$dDonors[$i]=($donors[$i]-$donors[$i-1])/$dTime*60*60;
            
$i++;
        }
        echo 
"done.\n";
        
//var_dump($dCash);
        
unset($time[0],$cash[0],$dCash[0], $dPeople[0]);
        
        
smooth($time$dCash$stDev, ($mean-$stDev*3), ($mean+$stDev*3), 'dCash');
        
smooth($time$dPeople$stDev, ($mean-$stDev*3), ($mean+$stDev*3), 'dPeople');
        
smooth($time$dDonors$stDev, ($mean-$stDev*3), ($mean+$stDev*3), 'dDonors');
        
        
//averages!!
        
$thisPoint=mysql_fetch_assoc(mysql_query("SELECT *, UNIX_TIMESTAMP(time) as utime FROM roncash ORDER BY time DESC LIMIT 1"));
        
$prevPoint=mysql_fetch_assoc(mysql_query("SELECT *, UNIX_TIMESTAMP(time) as utime FROM roncash WHERE time<'${thisPoint['time']}' ORDER BY time DESC LIMIT 1"));
        
        
updateEMA($thisPoint$prevPoint);
        
        
//what was the last averaged point time?
        /*
        $lastAveraged=mysql_fetch_assoc(mysql_query("select val from `roncash-vars` where var='lastAvg'"));
        $avgRes=mysql_query("SELECT * FROM roncash WHERE time > '${lastAveraged['val']}' AND time < FROM_UNIXTIME(" . (strtotime($thisPoint['time'])-$stDev*3*2) . ") order by time;") or die(mysql_error());
        echo "\nmust average " . mysql_num_rows($avgRes) . " stable points...";
        while(($avPt=mysql_fetch_assoc($avgRes))!==false)
        {
            if(!($avPt['dCash']==NULL || $avPt['dPeople']==NULL))
                updateDailyAverage($avPt);
        }
        echo "done.\n";
        */
        
        
        
    
}
    else 
        echo 
"no need to insert.\n";
}

function 
updateEMA($thisPoint$prevPoint)
{
        
//moving average
        
$dTime=($thisPoint['utime']-$prevPoint['utime']);
        
$shift exp(-(log(2)/HALFLIFE) * $dTime);
        
        if(
$prevPoint['dCashEMA']==|| $prevPoint['dPeopleEMA']==0)
        {
            echo 
"EMAing prev point...\n";
            
$pp