   Serial.print(", thi = ");
   Serial.print(thresholdHigh);
   Serial.print(", dmin = ");
-  Serial.print(dayMin);
+  Serial.print(average.average + average.minimum);
   Serial.print(", dmax = ");
-  Serial.println(dayMax);
+  Serial.println(average.average + average.maximum);
 
+  // switch the relays!
   if (sensorValue < thresholdLow) {
     // HIGH means setting the relay to NC
     digitalWrite(relaisPin, HIGH);

  pinMode(relaisPin, OUTPUT);
  pinMode(sensorPin, INPUT);
  digitalWrite(relaisPin, HIGH);
}

void loop(){
  sensorValue = analogRead(sensorPin);
  sensorValue = MAXVALUE - sensorValue;
  curday = day();
  if (firstRun == 1) {
    // first run, initialize threshold to sane values
    firstRun = 0;
    prevday = curday;
    thresholdLow = constrain(sensorValue - 10, 0, MAXVALUE);
    thresholdHigh = constrain(sensorValue + 10, 0, MAXVALUE);
    dayMin = thresholdLow;
    dayMax = thresholdHigh;
  }
  dayMin = constrain(sensorValue, 0, dayMin);
  dayMax = constrain(sensorValue, dayMax, MAXVALUE);
  if (prevday != curday) {
    prevday = curday;
    diff = dayMax - dayMin;
    avg = dayMin + diff / 2;
    thresholdLow = avg - diff / 4;
    thresholdHigh = avg + diff / 4;
    dayMin = sensorValue;
    dayMax = sensorValue;
  }

  Serial.print("humidity = ");
  Serial.print(sensorValue);
  Serial.print(", tlow = ");


const int relaisPin =  11;
const int sensorPin = A0;    // select the input pin for the potentiometer
const int MINVALUE = 0;
const int MAXVALUE = 1023;
int sensorValue = 0;  // variable to store the value coming from the sensor
int thresholdLow = 0;
int thresholdHigh = 0;
int hourMax = MINVALUE;
int hourMin = MAXVALUE;
int prevweekday = 0, prevhour = 0;
int curweekday = 0, curhour = 0;

/* Three arrays that keep track of sensor values (one every 5 minutes),
 * and averages (24 hours a day, then 7 days in a week)
 */
struct sensordata {
  int average;
  int minimum;
  int maximum;
};
typedef struct sensordata sensordata;

const int hum_hour_max = 12; // 12 * 5 minutes in one hour
const int hum_day_max = 24; // hours in a day
const int hum_week_max = 7; // days in a week
sensordata hum_hour[hum_hour_max];
sensordata hum_day[hum_day_max];
sensordata hum_week[hum_week_max];
int hum_hour_len = 0;
int hum_day_len = 0;
int hum_week_len = 0;

sensordata average;

int humidity() {
  sensorValue = analogRead(sensorPin);
  
  // sensor value is high when humidity is low, this is
  // counterintuitive (it's a dryness sensor!), so we
  // reverse it:
  return MAXVALUE - sensorValue;
}

void avg_min_max(const struct sensordata *sdata, int length, struct sensordata *out) {
  out->average = 0;
  out->minimum = MAXVALUE;
  out->maximum = MINVALUE;

  for (int i = 0; i < length; ++i) {
    out->average =+ sdata[i].average;
    out->minimum = min(sdata[i].minimum, out->minimum);
    out->maximum = max(sdata[i].maximum, out->maximum);
  }
  out->average /= length;
}

void setup() {
  // initialize the 11 pin as an output:
