www/import/from_brouwhulp.php

Tue, 31 Aug 2021 20:48:37 +0200

author
Michiel Broek <mbroek@mbse.eu>
date
Tue, 31 Aug 2021 20:48:37 +0200
changeset 774
92e1e8f175a2
parent 460
046ff5fdc96c
child 840
ba607babc468
permissions
-rw-r--r--

Split batch, adjust mash step volume. In the duplicated log_brew handle the missing values. In save product, round the mash step sg to 4 decimals. In prod_edit, ingredients are stored as strings, not arrays. This triggered a memory corruption that only happened in rare circumstances. Don't fix mash step fields in the javascript, it is already done during load from the database. Calculation of the mash volume is rounded to 6 decimals. Enter mash step Brix/Plato value, the SG result is rounded to 4 decimals.

<?php
/* 
 * Import inventory from brouwhulp
 */

require("../config.php");
require("../version.php");
require("../includes/formulas.php");

echo "Start adding data from brouwhulp\n";

$db = mysqli_connect(DBASE_HOST, DBASE_USER, DBASE_PASS, DBASE_NAME);
if (! $db) {
	die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
mysqli_set_charset($db, "utf8" );

$brouwhulp = '/home/mbroek/Documents/brouwhulp';
$pCara = 0;
$pSugar = 0;
$svg = 77;
$efficiency = 75;
$batch_size = 20;
$colorw = 0;
$f_sugars = 0;

function get_miscs_cost($miscname) {
	global $db;

	if ($result = mysqli_query($db, "SELECT cost FROM inventory_miscs WHERE name='$miscname'")) {
		if ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
			return floatval($row['cost']);
		}
	}
	return 0.0;
}



function do_fermentables()
{
	global $brouwhulp, $db;

	echo "  Start adding fermentables to the database\n";
	$sql = "TRUNCATE TABLE inventory_fermentables;";
	if (! $result = mysqli_query($db, $sql)) {
		printf("Error: %s\n", mysqli_error($db));
	}
	$myfermentables = simplexml_load_file($brouwhulp . '/fermentables.xml');

	foreach ($myfermentables->FERMENTABLE as $fermentable) {

		$sql  = "INSERT INTO inventory_fermentables SET name='" . mysqli_real_escape_string($db, $fermentable->NAME);
		if ($fermentable->TYPE == 'Grain')
			$sql .= "', type='0";
		else if ($fermentable->TYPE == 'Sugar')
			$sql .= "', type='1";
		else if ($fermentable->TYPE == 'Extract')
			$sql .= "', type='2";
		else if ($fermentable->TYPE == 'Dry extract')
			$sql .= "', type='3";
		else if ($fermentable->TYPE == 'Adjunct')
			$sql .= "', type='4";
		else
			echo "Unknown TYPE " . $fermentable->TYPE . PHP_EOL;
		if ($fermentable->YIELD)
			$sql .= "', yield='" . floatval($fermentable->YIELD);
		if ($fermentable->COLOR) {
			$sql .= "', color='" . srm_to_ebc(floatval($fermentable->COLOR));
		}
		($fermentable->ADD_AFTER_BOIL == "TRUE") ? $sql .= "', add_after_boil='1" : $sql .= "', add_after_boil='0";
		if ($fermentable->ADDED == 'Mash')
			$sql .= "', added='0";
		else if ($fermentable->ADDED == 'Boil')
			$sql .= "', added='1";
		else if ($fermentable->ADDED == 'Fermentation')
			$sql .= "', added='2";
		else if ($fermentable->ADDED == 'Lagering')
			$sql .= "', added='3";
		else if ($fermentable->ADDED == 'Bottle')
			$sql .= "', added='4";
		else
			echo "Unknown ADDED " . $fermentable->ADDED . PHP_EOL;

		$sql .= "', origin='" . mysqli_real_escape_string($db, $fermentable->ORIGIN);
		$sql .= "', supplier='" . mysqli_real_escape_string($db, $fermentable->SUPPLIER);
		$sql .= "', notes='" . mysqli_real_escape_string($db, $fermentable->NOTES);
		if ($fermentable->COARSE_FINE_DIFF)
			$sql .= "', coarse_fine_diff='" . floatval($fermentable->COARSE_FINE_DIFF);
		if ($fermentable->MOISTURE)
			$sql .= "', moisture='" . floatval($fermentable->MOISTURE);
		if ($fermentable->DIASTATIC_POWER)
			$sql .= "', diastatic_power='" . floatval($fermentable->DIASTATIC_POWER);
		if ($fermentable->PROTEIN)
			$sql .= "', protein='" . floatval($fermentable->PROTEIN);
		if ($fermentable->DISSOLVED_PROTEIN)
			$sql .= "', dissolved_protein='" . floatval($fermentable->DISSOLVED_PROTEIN);
		if ($fermentable->MAX_IN_BATCH)
			$sql .= "', max_in_batch='" . floatval($fermentable->MAX_IN_BATCH);
		($fermentable->RECOMMEND_MASH == "TRUE") ? $sql .= "', recommend_mash='1" : $sql .= "', recommend_mash='0";
		($fermentable->ALWAYS_ON_STOCK == "TRUE") ? $sql .= "', always_on_stock='1" : $sql .= "', always_on_stock='0";
		if ($fermentable->INVENTORY)
			$sql .= "', inventory='" . floatval($fermentable->INVENTORY);
		if ($fermentable->COST)
			$sql .= "', cost='" . floatval($fermentable->COST);
		/*
		 * These are not beerxml standard:
		 */
		if ($fermentable->DI_pH)
			$sql .= "', di_ph='" . floatval($fermentable->DI_pH);
		if ($fermentable->{'ACID_TO_pH_5.7'})
			$sql .= "', acid_to_ph_57='" . floatval($fermentable->{'ACID_TO_pH_5.7'});
		if ($fermentable->GRAINTYPE == 'Base')
			$sql .= "', graintype='0";
		else if ($fermentable->GRAINTYPE == 'Roast')
			$sql .= "', graintype='1";
		else if ($fermentable->GRAINTYPE == 'Crystal')
			$sql .= "', graintype='2";
		else if ($fermentable->GRAINTYPE == 'Kilned')
			$sql .= "', graintype='3";
		else if ($fermentable->GRAINTYPE == 'Sour malt')
			$sql .= "', graintype='4";
		else if ($fermentable->GRAINTYPE == 'Special')
			$sql .= "', graintype='5";
		else if ($fermentable->GRAINTYPE == 'No malt')
			$sql .= "', graintype='6";
		else
			echo "Unknown GRAINTYPE " . $fermentable->GRAINTYPE . PHP_EOL;
		$sql .= "';";
		if (! $result = mysqli_query($db, $sql)) {
			printf("Error: %s\n", mysqli_error($db));
		}
	}
}


function do_hops()
{
	global $brouwhulp, $db;

	echo "  Start adding hops to the database\n";
	$sql = "TRUNCATE TABLE inventory_hops;";
	if (! $result = mysqli_query($db, $sql)) {
		printf("Error: %s\n", mysqli_error($db));
	}

	$myhops = simplexml_load_file($brouwhulp . '/hops.xml');

	foreach ($myhops->HOP as $hop) {

		$sql  = "INSERT INTO inventory_hops SET name='" . mysqli_real_escape_string($db, $hop->NAME);
		if ($hop->ALPHA)
			$sql .= "', alpha='" . floatval($hop->ALPHA);
		if ($hop->BETA)
			$sql .= "', beta='" . floatval($hop->BETA);
		if ($hop->HUMULENE)
			$sql .= "', humulene='" . floatval($hop->HUMULENE);
		if ($hop->CAROPHYLLENE)
			$sql .= "', caryophyllene='" . floatval($hop->CAROPHYLLENE);
		if ($hop->COHUMULONE)
			$sql .= "', cohumulone='" . floatval($hop->COHUMULONE);
		if ($hop->MYRCENE)
			$sql .= "', myrcene='" . floatval($hop->MYRCENE);
		if ($hop->HSI)
			$sql .= "', hsi='" . floatval($hop->HSI);

		if ($hop->TYPE == 'Bittering')
			$sql .= "', type='0";
		else if ($hop->TYPE == 'Aroma')
			$sql .= "', type='1";
		else if ($hop->TYPE == 'Both')
			$sql .= "', type='2";
		else
			echo "Unknown TYPE " . $hop->TYPE . PHP_EOL;

		if ($hop->FORM == 'Pellet')
			$sql .= "', form='0";
		else if ($hop->FORM == 'Plug')
			$sql .= "', form='1";
		else if ($hop->FORM == 'Leaf')
			$sql .= "', form='2";
		else
			echo "Unknown FORM " . $hop->FORM . PHP_EOL;

		$sql .= "', notes='" . mysqli_real_escape_string($db, $hop->NOTES);
		$sql .= "', origin='" . mysqli_real_escape_string($db, $hop->ORIGIN);
		$sql .= "', substitutes='" . mysqli_real_escape_string($db, $hop->SUBSTITUTES);
		($hop->ALWAYS_ON_STOCK == 'TRUE') ? $sql .= "', always_on_stock='1" : $sql .= "', always_on_stock='0";
		if ($hop->INVENTORY)
			$sql .= "', inventory='" . floatval($hop->INVENTORY) / 1000.0;
		if ($hop->COST)
			$sql .= "', cost='" . floatval($hop->COST);
		if ($hop->TOTAL_OIL)
			$sql .= "', total_oil='" . floatval($hop->TOTAL_OIL);
		if ($hop->HARVEST_DATE) {
			$date = substr($hop->HARVEST_DATE, 6, 4).'-'.substr($hop->HARVEST_DATE, 3, 2).'-'.substr($hop->HARVEST_DATE, 0, 2);
			$sql .= "', production_date='" . $date;
		}
		$sql .= "';";
		if (! $result = mysqli_query($db, $sql)) {
			printf("Error: %s\n", mysqli_error($db));
		}
	}

}



function do_yeasts()
{
	global $brouwhulp, $db;

	echo "  Start adding yeasts to the database\n";
	$sql = "TRUNCATE TABLE inventory_yeasts;";
	if (! $result = mysqli_query($db, $sql)) {
		printf("Error: %s\n", mysqli_error($db));
	}

	$yeasts = simplexml_load_file($brouwhulp . '/yeasts.xml');

	foreach ($yeasts->YEAST as $yeast) {

		$sql  = "INSERT INTO inventory_yeasts SET name='" . mysqli_real_escape_string($db, $yeast->NAME);

		if ($yeast->TYPE == 'Lager')
			$sql .= "', type='0";
		else if ($yeast->TYPE == 'Ale')
			$sql .= "', type='1";
		else if ($yeast->TYPE == 'Wheat')
			$sql .= "', type='2";
		else if ($yeast->TYPE == 'Wine')
			$sql .= "', type='3";
		else if ($yeast->TYPE == 'Champagne')
			$sql .= "', type='4";
		else
			echo "Unknown TYPE " . $yeast->TYPE . PHP_EOL;

		if ($yeast->FORM == 'Liquid')
			$sql .= "', form='0";
		else if ($yeast->FORM == 'Dry')
			$sql .= "', form='1";
		else if ($yeast->FORM == 'Slant')
			$sql .= "', form='2";
		else if ($yeast->FORM == 'Culture')
			$sql .= "', form='3";
		else if ($yeast->FORM == 'Frozen')
			$sql .= "', form='4";
		else if ($yeast->FORM == 'Bottle')
			$sql .= "', form='5";
		else
			echo "Unknown FORM " . $yeast->FORM . PHP_EOL;

		$sql .= "', laboratory='" . mysqli_real_escape_string($db, $yeast->LABORATORY);
		$sql .= "', product_id='" . mysqli_real_escape_string($db, $yeast->PRODUCT_ID);
		if ($yeast->MIN_TEMPERATURE)
			$sql .= "', min_temperature='" . floatval($yeast->MIN_TEMPERATURE);
		if ($yeast->MAX_TEMPERATURE)
			$sql .= "', max_temperature='" . floatval($yeast->MAX_TEMPERATURE);

		if ($yeast->FLOCCULATION == 'Low')
			$sql .= "', flocculation='0";
		else if ($yeast->FLOCCULATION == 'Medium')
			$sql .= "', flocculation='1";
		else if ($yeast->FLOCCULATION == 'High')
			$sql .= "', flocculation='2";
		else if ($yeast->FLOCCULATION == 'Very high')
			$sql .= "', flocculation='3";
		else
			echo "Unknown FLOCCULATION " . $yeast->FLOCCULATION . PHP_EOL;

		if ($yeast->ATTENUATION)
			$sql .= "', attenuation='" . floatval($yeast->ATTENUATION);
		$sql .= "', notes='" . mysqli_real_escape_string($db, $yeast->NOTES);
		$sql .= "', best_for='" . mysqli_real_escape_string($db, $yeast->BEST_FOR);
		if ($yeast->MAX_REUSE)
			$sql .= "', max_reuse='" . $yeast->MAX_REUSE;

		if ($yeast->FORM == 'Liquid') {
			if ($yeast->LABORATORY == 'Imperial Yeast')
				$sql .= "', cells='200000000000";	// 200 billion cells per pack
			else
				$sql .= "', cells='100000000000";	// 100 billion cells per pack
			if ($yeast->COST)
				$sql .= "', cost='" . floatval($yeast->COST);
			if ($yeast->INVENTORY)
				$sql .= "', inventory='" . floatval($yeast->INVENTORY);
		} else if ($yeast->FORM == 'Dry') {
			$sql .= "', cells='15000000000";	// 6..15 billion per gram
			if ($yeast->INVENTORY)
				$sql .= "', inventory='" . floatval($yeast->INVENTORY) / 1000.0; // To kg
			if ($yeast->COST)
				$sql .= "', cost='" . floatval($yeast->COST) * 1000.0;  // to Euro/kg
		} else {
			$sql .= "', cells='1700000000";		// 1.7 billion cells per ml.
			if ($yeast->INVENTORY)
				$sql .= "', inventory='" . floatval($yeast->INVENTORY) / 1000.0; // To liter
			if ($yeast->COST)
				$sql .= "', cost='" . floatval($yeast->COST) * 1000.0; 	// to Euro/liter
		}
		if ($yeast->CULTURE_DATE) {
			$date = substr($yeast->CULTURE_DATE, 6, 4) . '-' . substr($yeast->CULTURE_DATE, 3, 2) . '-' . substr($yeast->CULTURE_DATE, 0, 2);
			$sql .= "', production_date='" . $date;
		}
		$sql .= "';";
		if (! $result = mysqli_query($db, $sql)) {
			printf("Error: %s\n", mysqli_error($db));
		}
	}
}



function do_waters()
{
	global $brouwhulp, $db;

	echo "  Start adding waters to the database\n";
	$sql = "TRUNCATE TABLE profile_water;";
	if (! $result = mysqli_query($db, $sql)) {
		printf("Error: %s\n", mysqli_error($db));
	}
	$sql = "TRUNCATE TABLE inventory_waters;";
	if (! $result = mysqli_query($db, $sql)) {
		printf("Error: %s\n", mysqli_error($db));
	}

	$waters = simplexml_load_file($brouwhulp . '/waters.xml');

	foreach ($waters->WATER as $water) {

		if (($water->NAME == "Gedemineraliseerd water") || ($water->NAME == "Cristalline") || ($water->NAME == "Montille (Delhaize)") ||
		    ($water->NAME == "Spa Reine") || ($water->NAME == "Velsen") || ($water->NAME == "Zutphen") || 
		    ($water->NAME == "Aurele Bronwater (Colruyt)")) {
		    $sql  = "INSERT INTO inventory_waters SET name='" . mysqli_real_escape_string($db, $water->NAME);
		} else {
			$sql  = "INSERT INTO profile_water SET name='" . mysqli_real_escape_string($db, $water->NAME);
		}

		if ($water->NOTES)
			$sql .= "', notes='" . mysqli_real_escape_string($db, $water->NOTES);
		$sql .= "', calcium='" . floatval($water->CALCIUM);
		$sql .= "', bicarbonate='" . floatval($water->BICARBONATE);
		$sql .= "', sulfate='" . floatval($water->SULFATE);
		$sql .= "', chloride='" . floatval($water->CHLORIDE);
		$sql .= "', sodium='" . floatval($water->SODIUM);
		$sql .= "', magnesium='" . floatval($water->MAGNESIUM);
		$sql .= "', ph='" . floatval($water->PH);
		if ($water->TOTAL_ALKALINITY)
			$sql .= "', total_alkalinity='" . floatval($water->TOTAL_ALKALINITY);
		$sql .= "';";
		if (! $result = mysqli_query($db, $sql)) {
			printf("Error: %s\n", mysqli_error($db));
		}
	}
}



function do_miscs()
{
	global $brouwhulp, $db;

	echo "  Start adding miscs to the database\n";
	$sql = "TRUNCATE TABLE inventory_miscs;";
	if (! $result = mysqli_query($db, $sql)) {
		printf("Error: %s\n", mysqli_error($db));
	}

	$miscs = simplexml_load_file($brouwhulp . '/miscs.xml');

	foreach ($miscs->MISC as $misc) {

		$sql  = "INSERT INTO inventory_miscs SET name='" . mysqli_real_escape_string($db, $misc->NAME);
		if ($misc->NOTES)
			$sql .= "', notes='" . mysqli_real_escape_string($db, $misc->NOTES);

		if ($misc->TYPE == 'Spice')
			$sql .= "', type='0";
		else if ($misc->TYPE == 'Herb')
			$sql .= "', type='1";
		else if ($misc->TYPE == 'Flavor')
			$sql .= "', type='2";
		else if ($misc->TYPE == 'Fining')
			$sql .= "', type='3";
		else if ($misc->TYPE == 'Water agent')
			$sql .= "', type='4";
		else if ($misc->TYPE == 'Yeast nutrient')
			$sql .= "', type='5";
		else if ($misc->TYPE == 'Other')
			$sql .= "', type='6";
		else
			echo "Unknown TYPE " . $misc->TYPE . PHP_EOL;

		if ($misc->USE == 'Starter')
			$sql .= "', use_use='0";
		else if ($misc->USE == 'Mash')
			$sql .= "', use_use='1";
		else if ($misc->USE == 'Boil')
			$sql .= "', use_use='2";
		else if ($misc->USE == 'Primary')
			$sql .= "', use_use='3";
		else if ($misc->USE == 'Secondary')
			$sql .= "', use_use='4";
		else if ($misc->USE == 'Bottling')
			$sql .= "', use_use='5";
		else
			echo "Unknown USE " . $misc->USE . PHP_EOL;

		$sql .= "', time='" . $misc->TIME;
		($misc->AMOUNT_IS_WEIGHT == 'TRUE') ? $sql .= "', amount_is_weight='1" : $sql .= "', amount_is_weight='0";
		if ($misc->USE_FOR)
			$sql .= "', use_for='" . mysqli_real_escape_string($db, $misc->USE_FOR);
		if ($misc->ALWAYS_ON_STOCK)
			($misc->ALWAYS_ON_STOCK == 'TRUE') ? $sql .= "', always_on_stock='1" : $sql .= "', always_on_stock='0";
		if ($misc->INVENTORY)
			$sql .= "', inventory='" . floatval($misc->INVENTORY) / 1000.0;
		if ($misc->COST)
			$sql .= "', cost='" . floatval($misc->COST);
		$sql .= "';";
		if (! $result = mysqli_query($db, $sql)) {
			printf("Error: %s\n", mysqli_error($db));
		}
	}
}



function do_equipments()
{
	global $brouwhulp, $db;

	echo "  Start adding equipments to the database\n";
	$sql = "TRUNCATE TABLE inventory_equipments;";
	if (! $result = mysqli_query($db, $sql)) {
		printf("Error: %s\n", mysqli_error($db));
	}

	$equipments = simplexml_load_file($brouwhulp . '/equipments.xml');

	foreach ($equipments->EQUIPMENT as $equipment) {

		$sql  = "INSERT INTO inventory_equipments SET name='" . mysqli_real_escape_string($db, $equipment->NAME);
		$sql .= "', boil_size='" . floatval($equipment->BOIL_SIZE);
		$sql .= "', batch_size='" . floatval($equipment->BATCH_SIZE);
		$sql .= "', tun_volume='" . floatval($equipment->TUN_VOLUME);
		$sql .= "', tun_weight='" . floatval($equipment->TUN_WEIGHT);
		$sql .= "', tun_specific_heat='" . floatval($equipment->TUN_SPECIFIC_HEAT);
		if (floatval($equipment->TUN_SPECIFIC_HEAT) == 0.11)
			$sql .= "', tun_material='0";
		else if (floatval($equipment->TUN_SPECIFIC_HEAT) == 0.22)
			$sql .= "', tun_material='1";
		else if (floatval($equipment->TUN_SPECIFIC_HEAT) == 0.46)
			$sql .= "', tun_material='2";
		else if (floatval($equipment->TUN_SPECIFIC_HEAT) == 0.092)
			$sql .= "', tun_material='3";
		else
			echo "Unknown TUN_SPECIFIC_HEAT" . $equipment->TUN_SPECIFIC_HEAT . PHP_EOL;
		$sql .= "', tun_height='" . floatval($equipment->TUN_HEIGHT);
		$sql .= "', top_up_water='" . floatval($equipment->TOP_UP_WATER);
		$sql .= "', trub_chiller_loss='" . floatval($equipment->TRUB_CHILLER_LOSS);
		/*
		 * Brouwhulp uses a percentage for the evaporation rate. This is wrong
		 * but was made so because the beerxml standard requires this. What we
		 * do is calculate the actual evaporation and store that.
		 * This is what we use. Brouwhulp calculates this on the fly.
		 */
		$sql .= "', evap_rate='" . (floatval($equipment->EVAP_RATE) * floatval($equipment->BOIL_SIZE)) / 100.0;
		$sql .= "', boil_time='" . floatval($equipment->BOIL_TIME);
		($equipment->CALC_BOIL_VOLUME == 'TRUE') ? $sql .= "', calc_boil_volume='1" : $sql .= "', calc_boil_volume='0";
		$sql .= "', top_up_kettle='" . floatval($equipment->TOP_UP_KETTLE);
		$sql .= "', hop_utilization='" . floatval($equipment->HOP_UTILIZATION);
		if ($equipment->NOTES)
			$sql .= "', notes='" . mysqli_real_escape_string($db, $equipment->NOTES);
		$sql .= "', lauter_volume='" . floatval($equipment->LAUTER_VOLUME);
		$sql .= "', lauter_height='" . floatval($equipment->LAUTER_HEIGHT);
		$sql .= "', lauter_deadspace='" . floatval($equipment->LAUTER_DEADSPACE);
		$sql .= "', kettle_volume='" . floatval($equipment->KETTLE_VOLUME);
		$sql .= "', kettle_height='" . floatval($equipment->KETTLE_HEIGHT);
		$sql .= "', mash_volume='" . floatval($equipment->MASH_VOLUME);
		$sql .= "', mash_max='" . round((floatval($equipment->MASH_VOLUME) / 3) * 10) / 10;	// Not in beerxml/brouwhulp. For RIMS systems.
		$sql .= "', efficiency='" . floatval($equipment->EFFICIENCY);
		$sql .= "';";
		if (! $result = mysqli_query($db, $sql)) {
			printf("Error: %s\n", mysqli_error($db));
		}
	}
}



function do_styles()
{
	global $brouwhulp, $db;

	echo "  Start adding styles to the database\n";
	$sql = "TRUNCATE TABLE profile_styles;";
	if (! $result = mysqli_query($db, $sql)) {
		printf("Error: %s\n", mysqli_error($db));
	}

	$styles = simplexml_load_file($brouwhulp . '/styles.xml');

	foreach ($styles->STYLE as $style) {

		$sql  = "INSERT INTO profile_styles SET name='" . mysqli_real_escape_string($db, $style->NAME);
		if ($style->NOTES)
			$sql .= "', notes='" . mysqli_real_escape_string($db, $style->NOTES);
		if ($style->CATEGORY)
			$sql .= "', category='" . mysqli_real_escape_string($db, $style->CATEGORY);
		if ($style->CATEGORY_NUMBER)
			$sql .= "', category_number='" . $style->CATEGORY_NUMBER;
		if ($style->STYLE_LETTER)
			$sql .= "', style_letter='" . mysqli_real_escape_string($db, $style->STYLE_LETTER);
		if ($style->STYLE_GUIDE)
			$sql .= "', style_guide='" . mysqli_real_escape_string($db, $style->STYLE_GUIDE);

		if ($style->TYPE == 'Lager')
			$sql .= "', type='0";
		else if ($style->TYPE == 'Ale')
			$sql .= "', type='1";
		else if ($style->TYPE == 'Mead')
			$sql .= "', type='2";
		else if ($style->TYPE == 'Wheat')
			$sql .= "', type='3";
		else if ($style->TYPE == 'Mixed')
			$sql .= "', type='4";
		else if ($style->TYPE == 'Cider')
			$sql .= "', type='5";
		else
			echo "Unknown TYPE " . $style->TYPE . PHP_EOL;

		$sql .= "', og_min='" . floatval($style->OG_MIN);
		$sql .= "', og_max='" . floatval($style->OG_MAX);
		$sql .= "', fg_min='" . floatval($style->FG_MIN);
		$sql .= "', fg_max='" . floatval($style->FG_MAX);
		$sql .= "', ibu_min='" . floatval($style->IBU_MIN);
		$sql .= "', ibu_max='" . floatval($style->IBU_MAX);
		$sql .= "', color_min='" . srm_to_ebc(floatval($style->COLOR_MIN));
		$sql .= "', color_max='" . srm_to_ebc(floatval($style->COLOR_MAX));
		$sql .= "', carb_min='" . floatval($style->CARB_MIN);
		$sql .= "', carb_max='" . floatval($style->CARB_MAX);
		$sql .= "', abv_min='" . floatval($style->ABV_MIN);
		$sql .= "', abv_max='" . floatval($style->ABV_MAX);
		if ($style->PROFILE)
			$sql .= "', profile='" . mysqli_real_escape_string($db, $style->PROFILE);
		if ($style->INGREDIENTS)
			$sql .= "', ingredients='" . mysqli_real_escape_string($db, $style->INGREDIENTS);
		if ($style->EXAMPLES)
			$sql .= "', examples='" . mysqli_real_escape_string($db, $style->EXAMPLES);

		$sql .= "';";
		if (! $result = mysqli_query($db, $sql)) {
			printf("Error: %s\n", mysqli_error($db));
		}
	}
}



function do_mash()
{
	global $brouwhulp, $db;

	echo "  Start adding mash profiles to the database\n";
	$sql = "TRUNCATE TABLE profile_mash;";
	if (! $result = mysqli_query($db, $sql)) {
		printf("Error: %s\n", mysqli_error($db));
	}

	$mashes = simplexml_load_file($brouwhulp . '/mashs.xml');

	foreach ($mashes->MASH as $mash) {
		$sql  = "INSERT INTO profile_mash SET name='" . mysqli_real_escape_string($db, $mash->NAME);
		if ($mash->NOTES)
			$sql .= "', notes='" . mysqli_real_escape_string($db, $mash->NOTES);

		/*
		 * Put the steps in a json array
		 */
		if ($mash->MASH_STEPS) {
			$steps = "[";
			$comma = FALSE;
			foreach ($mash->MASH_STEPS->MASH_STEP as $step) {

				if ($comma)
					$steps .= ',';
				$comma = TRUE;
				$steps .= '{"step_name":"' . mysqli_real_escape_string($db, $step->NAME) . '"';
				if ($step->TYPE == 'Infusion')
					$steps .= ',"step_type":"0"';
				else if ($step->TYPE == 'Temperature')
					$steps .= ',"step_type":"1"';
				else if ($step->TYPE == 'Decoction')
					$steps .= ',"step_type":"2"';
				else
					echo "Unknown step TYPE " . $step->TYPE . PHP_EOL;
				if ($step->STEP_TEMP) {
					$steps .= ',"step_temp":"' . floatval($step->STEP_TEMP) . '"';
				}
				if ($step->STEP_TIME) {
					$steps .= ',"step_time":"' . floatval($step->STEP_TIME) . '"';
				}
				if ($step->RAMP_TIME) {
					$steps .= ',"ramp_time":"' . floatval($step->RAMP_TIME) . '"';
				}
				if ($step->END_TEMP) {
					$steps .= ',"end_temp":"' . floatval($step->END_TEMP) . '"';
				}
				$steps .= "}";
			}
			$steps .= ']';
			$sql .= "', steps='" . $steps;
		}
		$sql .= "';";
		if (! $result = mysqli_query($db, $sql)) {
			printf("Error: %s\n", mysqli_error($db));
		}
	}
}



/*
 * Return recipe ingredients as json functions.
 */
function recipe_style($recipe)
{
	global	$db;

	if ($recipe->STYLE->NAME)
		$sql  = "', st_name='" . mysqli_real_escape_string($db, $recipe->STYLE->NAME);
	if ($recipe->STYLE->STYLE_LETTER)
		$sql .= "', st_letter='" . mysqli_real_escape_string($db, $recipe->STYLE->STYLE_LETTER);
	if ($recipe->STYLE->STYLE_GUIDE) {
		if ($recipe->STYLE->STYLE_GUIDE == "Biertypengids Derek Walsh") {
			$sql .= "', st_guide='BKG 2015";
		} else if ($recipe->STYLE->STYLE_GUIDE == "BKG Biertypen") {
			$sql .= "', st_guide='BKG 2015";
		} else {
			$sql .= "', st_guide='" . mysqli_real_escape_string($db, $recipe->STYLE->STYLE_GUIDE);
		}
	}
	if ($recipe->STYLE->CATEGORY)
		$sql .= "', st_category='" . mysqli_real_escape_string($db, $recipe->STYLE->CATEGORY);
	if ($recipe->STYLE->CATEGORY_NUMBER)
		$sql .= "', st_category_number='" . floatval($recipe->STYLE->CATEGORY_NUMBER);
	if ($recipe->STYLE->TYPE == 'Lager')
		$sql .= "', st_type='0";
	else if ($recipe->STYLE->TYPE == 'Ale')
		$sql .= "', st_type='1";
	else if ($recipe->STYLE->TYPE == 'Mead')
		$sql .= "', st_type='2";
	else if ($recipe->STYLE->TYPE == 'Wheat')
		$sql .= "', st_type='3";
	else if ($recipe->STYLE->TYPE == 'Mixed')
		$sql .= "', st_type='4";
	else if ($recipe->STYLE->TYPE == 'Cider')
		$sql .= "', st_type='5";
	else
		echo "Unknown TYPE " . $recipe->STYLE->TYPE . PHP_EOL;

	if ($recipe->STYLE->OG_MIN)
		$sql .= "', st_og_min='" . floatval($recipe->STYLE->OG_MIN);
	if ($recipe->STYLE->OG_MAX)
		$sql .= "', st_og_max='" . floatval($recipe->STYLE->OG_MAX);
	if ($recipe->STYLE->FG_MIN)
		$sql .= "', st_fg_min='" . floatval($recipe->STYLE->FG_MIN);
	if ($recipe->STYLE->FG_MAX)
		$sql .= "', st_fg_max='" . floatval($recipe->STYLE->FG_MAX);
	if ($recipe->STYLE->IBU_MIN)
		$sql .= "', st_ibu_min='" . floatval($recipe->STYLE->IBU_MIN);
	if ($recipe->STYLE->IBU_MAX)
		$sql .= "', st_ibu_max='" . floatval($recipe->STYLE->IBU_MAX);
	if ($recipe->STYLE->COLOR_MIN) {
		$srm = floatval($recipe->STYLE->COLOR_MIN);
		$sql .= "', st_color_min='" . srm_to_ebc($srm);
	}
	if ($recipe->STYLE->COLOR_MAX) {
		$srm = floatval($recipe->STYLE->COLOR_MAX);
		$sql .= "', st_color_max='" . srm_to_ebc($srm);
	}
	if ($recipe->STYLE->CARB_MIN)
		$sql .= "', st_carb_min='" . floatval($recipe->STYLE->CARB_MIN);
	if ($recipe->STYLE->CARB_MAX)
		$sql .= "', st_carb_max='" . floatval($recipe->STYLE->CARB_MAX);
	if ($recipe->STYLE->ABV_MIN)
		$sql .= "', st_abv_min='" . floatval($recipe->STYLE->ABV_MIN);
	if ($recipe->STYLE->ABV_MAX)
		$sql .= "', st_abv_max='" . floatval($recipe->STYLE->ABV_MAX);
	return $sql;
}

function recipe_fermentables($recipe)
{
	global	$db;
	global	$pCara;
	global	$pSugar;
	global	$batch_size;
	global	$efficiency;
	global	$colorw;
	global	$f_sugars;

	$fermentables = "[";
	$comma = FALSE;
	foreach ($recipe->FERMENTABLES->FERMENTABLE as $fermentable) {
		if ($comma)
			$fermentables .= ',';
		$comma = TRUE;
		$fermentables .= '{"f_name":"' . mysqli_real_escape_string($db, $fermentable->NAME) . '"';
		$fermentables .= ',"f_origin":"' . mysqli_real_escape_string($db, $fermentable->ORIGIN) . '"';
		$fermentables .= ',"f_supplier":"' . mysqli_real_escape_string($db, $fermentable->SUPPLIER) . '"';
		$famount = floatval($fermentable->AMOUNT);
		$fermentables .= ',"f_amount":' . $famount;
		$fermentables .= ',"f_cost":' . floatval($fermentable->COST);

		if ($fermentable->TYPE == 'Grain')
			$fermentables .= ',"f_type":0';
		else if ($fermentable->TYPE == 'Sugar')
			$fermentables .= ',"f_type":1';
		else if ($fermentable->TYPE == 'Extract')
			$fermentables .= ',"f_type":2';
		else if ($fermentable->TYPE == 'Dry extract')
			$fermentables .= ',"f_type":3';
		else if ($fermentable->TYPE == 'Adjunct')
			$fermentables .= ',"f_type":4';
		else
			echo "Unknown TYPE " . $fermentable->TYPE . PHP_EOL;

		$fyield = floatval($fermentable->YIELD);
		$fermentables .= ',"f_yield":' . $fyield;
		if ($fermentable->COLOR) {
			$srm = floatval($fermentable->COLOR);
			$ebc = srm_to_ebc($srm);
		} else {
			$srm = 0;
			$ebc = 0;
		}
		$colorw += ($famount * $srm / $batch_size) * 8.34436;   /* Kleurwerking */
		$fermentables .= ',"f_color":' . $ebc;
		if ($fermentable->COARSE_FINE_DIFF)
			$fermentables .= ',"f_coarse_fine_diff":' . floatval($fermentable->COARSE_FINE_DIFF);
		else
			$fermentables .= ',"f_coarse_fine_diff":0';
		if ($fermentable->MOISTURE)
			$fmoisture = floatval($fermentable->MOISTURE);
		else
			$fmoisture = 0;
		$fermentables .= ',"f_moisture":' . $fmoisture;
		if ($fermentable->DIASTATIC_POWER)
			$fermentables .= ',"f_diastatic_power":' . floatval($fermentable->DIASTATIC_POWER);
		else
			$fermentables .= ',"f_diastatic_power":0';
		if ($fermentable->PROTEIN)
			$fermentables .= ',"f_protein":' . floatval($fermentable->PROTEIN);
		else
			$fermentables .= ',"f_protein":0';
		if ($fermentable->MAX_IN_BATCH)
			$fermentables .= ',"f_max_in_batch":' . floatval($fermentable->MAX_IN_BATCH);
		else
			$fermentables .= ',"f_max_in_batch":100.0';

		if ($fermentable->GRAINTYPE == 'Base')
			$fermentables .= ',"f_graintype":0';
		else if ($fermentable->GRAINTYPE == 'Roast')
			$fermentables .= ',"f_graintype":1';
		else if ($fermentable->GRAINTYPE == 'Crystal')
			$fermentables .= ',"f_graintype":2';
		else if ($fermentable->GRAINTYPE == 'Kilned')
			$fermentables .= ',"f_graintype":3';
		else if ($fermentable->GRAINTYPE == 'Sour malt')
			$fermentables .= ',"f_graintype":4';
		else if ($fermentable->GRAINTYPE == 'Special')
			$fermentables .= ',"f_graintype":5';
		else if ($fermentable->GRAINTYPE == 'No malt')
			$fermentables .= ',"f_graintype":6';
		else
			echo "Unknown GRAINTYPE " . $fermentable->GRAINTYPE . PHP_EOL;

		if ($fermentable->ADDED == 'Mash')
			$fermentables .= ',"f_added":0';
		else if ($fermentable->ADDED == 'Boil')
			$fermentables .= ',"f_added":1';
		else if ($fermentable->ADDED == 'Fermentation')
			$fermentables .= ',"f_added":2';
		else if ($fermentable->ADDED == 'Lagering')
			$fermentables .= ',"f_added":3';
		else if ($fermentable->ADDED == 'Bottle')
			$fermentables .= ',"f_added":4';
		else
			echo "Unknown ADDED " . $fermentable->ADDED . PHP_EOL;

		($fermentable->ADD_AFTER_BOIL== "TRUE") ? $fermentables .= ',"f_add_after_boil":1' : $fermentables .= ',"f_add_after_boil":0';
		($fermentable->RECOMMEND_MASH== "TRUE") ? $fermentables .= ',"f_recommend_mash":1' : $fermentables .= ',"f_recommend_mash":0';
		if ($fermentable->DISSOLVED_PROTEIN)
			$fermentables .= ',"f_dissolved_protein":' . floatval($fermentable->DISSOLVED_PROTEIN);
		else
			$fermentables .= ',"f_dissolved_protein":0';
		($fermentable->ADJUST_TO_TOTAL_100 == "TRUE") ? $fermentables .= ',"f_adjust_to_total_100":1' : $fermentables .= ',"f_adjust_to_total_100":0';
		$percent = floatval($fermentable->PERCENTAGE);
		$fermentables .= ',"f_percentage":' . round($percent * 10) / 10.0;
		if ($fermentable->DI_pH)
			$fermentables .= ',"f_di_ph":' . floatval($fermentable->DI_pH);
		else
			$fermentables .= ',"f_di_ph":0.0';
		if ($fermentable->{'ACID_TO_pH_5.7'})
			$fermentables .= ',"f_acid_to_ph_57":' . floatval($fermentable->{'ACID_TO_pH_5.7'});
		else
			$fermentables .= ',"f_acid_to_ph_57":0.0';
		$fermentables .= "}";
		/* Sugars */
		$d = $famount * ($fyield / 100) * (1 - $fmoisture / 100);
		if ($fermentable->ADDED == 'Mash')
			$d = floatval($efficiency) / 100 * $d;
		$f_sugars += $d;
		if ($fermentable->GRAINTYPE == 'Crystal')
			$pCara += $percent;
		if ($fermentable->TYPE == 'Sugar')
			$pSugar += $percent;
	}
	$fermentables .= ']';
	return $fermentables;
}

function recipe_hops($recipe)
{
	global	$db;

	$hops = "[";
	$comma = FALSE;
	foreach ($recipe->HOPS->HOP as $hop) {
		if ($comma)
			$hops .= ',';
		$comma = TRUE;
		$hops .= '{"h_name":"' . mysqli_real_escape_string($db, $hop->NAME) . '"';
		$hops .= ',"h_amount":' . floatval($hop->AMOUNT);
		$hops .= ',"h_cost":' . floatval($hop->COST);

		if ($hop->TYPE == 'Bittering')
			$hops .= ',"h_type":0';
		else if ($hop->TYPE == 'Aroma')
			$hops .= ',"h_type":1';
		else if ($hop->TYPE == 'Both')
			$hops .= ',"h_type":2';
		else
			echo "Unknown TYPE " . $hop->TYPE . PHP_EOL;

		if ($hop->FORM == 'Pellet')
			$hops .= ',"h_form":0';
		else if ($hop->FORM == 'Plug')
			$hops .= ',"h_form":1';
		else if ($hop->FORM == 'Leaf')
			$hops .= ',"h_form":2';
		else
			echo "Unknown FORM " . $hop->FORM . PHP_EOL;

		if ($hop->USE == 'Mash')
			$hops .= ',"h_useat":0';
		else if ($hop->USE == 'First wort')
			$hops .= ',"h_useat":1';
		else if ($hop->USE == 'Boil')
			$hops .= ',"h_useat":2';
		else if ($hop->USE == 'Aroma')
			$hops .= ',"h_useat":3';
		else if ($hop->USE == 'Whirlpool')
			$hops .= ',"h_useat":4';
		else if ($hop->USE == 'Dry hop')
			$hops .= ',"h_useat":5';
		else
			echo "Unknown USE " . $hop->USE . PHP_EOL;
		if ($hop->TIME)
			$hops .= ',"h_time":' . floatval($hop->TIME);
		else
			$hops .= ',"h_time":0';
		$hops .= ',"h_alpha":' . floatval($hop->ALPHA);
		$hops .= ',"h_beta":' . floatval($hop->BETA);
		$hops .= ',"h_hsi":' . floatval($hop->HSI);
		$hops .= ',"h_humulene":' . floatval($hop->HUMULENE);
		$hops .= ',"h_caryophyllene":' . floatval($hop->CAROPHYLLENE);
		$hops .= ',"h_cohumulone":' . floatval($hop->COHUMULONE);
		$hops .= ',"h_myrcene":' . floatval($hop->MYRCENE);
		if ($hop->TOTAL_OIL)
			$hops .= ',"h_total_oil":' . floatval($hop->TOTAL_OIL);
		else
			$hops .= ',"h_total_oil":0';
		if ($hop->ORIGIN)
			$hops .= ',"h_origin":"' . mysqli_real_escape_string($db, $hop->ORIGIN) . '"';
		else
			$hops .= ',"h_origin":""';
		$hops .= "}";
	}
	$hops .= ']';
	return $hops;
}

function recipe_miscs($recipe)
{
	global	$db;

	$miscs = "[";
	$comma = FALSE;
	foreach ($recipe->MISCS->MISC as $misc) {
		if ($comma)
			$miscs .= ',';
		$comma = TRUE;
		$mname = mysqli_real_escape_string($db, $misc->NAME);
		$miscs .= '{"m_name":"' . $mname . '"';
		$miscs .= ',"m_amount":' . floatval($misc->AMOUNT);
		if ($misc->COST) {
			$miscs .= ',"m_cost":' . floatval($misc->COST);
		} else {
			/* Brouwhulp bug, added water agents have no cost field. */
			if ($misc->TYPE == "Water agent") {
				$miscs .= ',"m_cost":'. get_miscs_cost($mname);
			} else {
				$miscs .= ',"m_cost":0';
			}
		}

		if ($misc->TYPE == 'Spice')
			$miscs .= ',"m_type":0';
		else if ($misc->TYPE == 'Herb')
			$miscs .= ',"m_type":1';
		else if ($misc->TYPE == 'Flavor')
			$miscs .= ',"m_type":2';
		else if ($misc->TYPE == 'Fining')
			$miscs .= ',"m_type":3';
		else if ($misc->TYPE == 'Water agent')
			$miscs .= ',"m_type":4';
		else if ($misc->TYPE == 'Yeast nutrient')
			$miscs .= ',"m_type":5';
		else if ($misc->TYPE == 'Other')
			$miscs .= ',"m_type":6';
		else
			echo "Unknown TYPE " . $misc->TYPE . PHP_EOL;

		if ($misc->USE == 'Starter')
			$miscs .= ',"m_use_use":0';
		else if ($misc->USE == 'Mash')
			$miscs .= ',"m_use_use":1';
		else if ($misc->USE == 'Boil')
			$miscs .= ',"m_use_use":2';
		else if ($misc->USE == 'Primary')
			$miscs .= ',"m_use_use":3';
		else if ($misc->USE == 'Secondary')
			$miscs .= ',"m_use_use":4';
		else if ($misc->USE == 'Bottling')
			$miscs .= ',"m_use_use":5';
		else
			echo "Unknown USE " . $misc->USE . PHP_EOL;

		($misc->AMOUNT_IS_WEIGHT== "TRUE") ? $miscs .= ',"m_amount_is_weight":1' : $miscs.= ',"m_amount_is_weight":0';
		if ($misc->TIME) {
			$miscs .= ',"m_time":' . floatval($misc->TIME);
		} else
			$miscs .= ',"m_time":0';
		$miscs .= "}";
	}
	$miscs .= ']';
	return $miscs;
}

function recipe_yeasts($recipe)
{
	global	$db;
	global	$svg;

	$yeasts = "[";
	$comma = FALSE;
	foreach ($recipe->YEASTS->YEAST as $yeast) {
		if ($comma)
			$yeasts .= ',';
		$comma = TRUE;
		$yeasts .= '{"y_name":"' . mysqli_real_escape_string($db, $yeast->NAME) . '"';
		if ($yeast->FORM == "Liquid") {
			$paks = floatval($yeast->AMOUNT) / 0.0588;
			$yeasts .= ',"y_amount":' . $paks;
			$yeasts .= ',"y_cost":' . floatval($yeast->COST);
		} else {
			$yeasts .= ',"y_amount":' . floatval($yeast->AMOUNT);
			$yeasts .= ',"y_cost":' . floatval($yeast->COST) * 1000;
		}

		$yeasts .= ',"y_laboratory":"' . mysqli_real_escape_string($db, $yeast->LABORATORY) . '"';
		$yeasts .= ',"y_product_id":"' . mysqli_real_escape_string($db, $yeast->PRODUCT_ID) . '"';

		if ($yeast->TYPE == 'Lager')
			$yeasts .= ',"y_type":0';
		else if ($yeast->TYPE == 'Ale')
			$yeasts .= ',"y_type":1';
		else if ($yeast->TYPE == 'Wheat')
			$yeasts .= ',"y_type":2';
		else if ($yeast->TYPE == 'Wine')
			$yeasts .= ',"y_type":3';
		else if ($yeast->TYPE == 'Champagne')
			$yeasts .= ',"y_type":4';
		else
			echo "Unknown TYPE " . $yeast->TYPE . PHP_EOL;

		if ($yeast->FORM == 'Liquid') {
			if ($yeast->LABORATORY == 'Imperial Yeast')
				$yeasts .= ',"y_form":0,"y_cells":200000000000';
			else
				$yeasts .= ',"y_form":0,"y_cells":100000000000';
		} else if ($yeast->FORM == 'Dry')
			$yeasts .= ',"y_form":1,"y_cells":15000000000';
		else if ($yeast->FORM == 'Slant')
			$yeasts .= ',"y_form":2,"y_cells":1700000000';
		else if ($yeast->FORM == 'Culture')
			$yeasts .= ',"y_form":3,"y_cells":1700000000';
		else if ($yeast->FORM == 'Frozen')
			$yeasts .= ',"y_form":4,"y_cells":1700000000';
		else if ($yeast->FORM == 'Bottle')
			$yeasts .= ',"y_form":5,"y_cells":1700000000';
		else
			echo "Unknown FORM " . $yeast->FORM . PHP_EOL;

		if ($yeast->FLOCCULATION == 'Low')
			$yeasts .= ',"y_flocculation":0';
		else if ($yeast->FLOCCULATION == 'Medium')
			$yeasts .= ',"y_flocculation":1';
		else if ($yeast->FLOCCULATION == 'High')
			$yeasts .= ',"y_flocculation":2';
		else if ($yeast->FLOCCULATION == 'Very high')
			$yeasts .= ',"y_flocculation":3';
		else
			echo "Unknown FLOCCULATION " . $yeast->FLOCCULATION . PHP_EOL;

		if ($yeast->PRODUCT_ID=="F2" || $yeast->PRODUCT_ID=="CBC-1") {
			$yeasts .= ',"y_use":3'; 	// Bottle
		} else if ($yeast->ADD_TO_SECONDARY=="TRUE") {
			$yeasts .= ',"y_use":1';	// Secondary
			$svg = floatval($yeast->ATTENUATION);
		} else {
			$yeasts .= ',"y_use":0';	// Primary
		}
		$yeasts .= ',"y_min_temperature":' . floatval($yeast->MIN_TEMPERATURE);
		$yeasts .= ',"y_max_temperature":' . floatval($yeast->MAX_TEMPERATURE);
		$yeasts .= ',"y_attenuation":' . floatval($yeast->ATTENUATION);
		$yeasts .= "}";
	}
	$yeasts .= ']';
	return $yeasts;
}

function recipe_waters($recipe, $db)
{
	$waters = "";
	$index = 0;
	foreach ($recipe->WATERS->WATER as $water) {
		$index++;
		$waters .= "', w" . $index . "_name='" . mysqli_real_escape_string($db, $water->NAME);
		$waters .= "', w" . $index . "_amount='" . floatval($water->AMOUNT);
		if ($water->CALCIUM)
		$waters .= "', w" . $index . "_calcium='" . floatval($water->CALCIUM);
		if ($water->SULFATE)
		$waters .= "', w" . $index . "_sulfate='" . floatval($water->SULFATE);
		if ($water->CHLORIDE)
		$waters .= "', w" . $index . "_chloride='" . floatval($water->CHLORIDE);
		if ($water->SODIUM)
		$waters .= "', w" . $index . "_sodium='" . floatval($water->SODIUM);
		if ($water->MAGNESIUM)
		$waters .= "', w" . $index . "_magnesium='" . floatval($water->MAGNESIUM);
		if ($water->PH)
		$waters .= "', w" . $index . "_ph='" . floatval($water->PH);
		if ($water->TOTAL_ALKALINITY)
		$waters .= "', w" . $index . "_total_alkalinity='" . floatval($water->TOTAL_ALKALINITY);
		if ($water->COST)
		$waters .= "', w" . $index . "_cost='" . floatval($water->COST);
		else
		$waters .= "', w" . $index . "_cost='0";
	}
	return $waters;
}



function recipe_mash_steps($recipe)
{
	global	$db;

	$steps = '[';
	$comma = FALSE;
	foreach ($recipe->MASH->MASH_STEPS->MASH_STEP as $step) {
		if ($comma)
			$steps .= ',';
		$comma = TRUE;
		$steps .= '{"step_name":"' . mysqli_real_escape_string($db, $step->NAME) . '"';

		if ($step->TYPE == 'Infusion')
			$steps .= ',"step_type":0';
		else if ($step->TYPE == 'Temperature')
			$steps .= ',"step_type":1';
		else if ($step->TYPE == 'Decoction')
			$steps .= ',"step_type":2';
		else
			echo "Unknown step TYPE " . $step->TYPE . PHP_EOL;

		if ($step->INFUSE_AMOUNT)
			$steps .= ',"step_infuse_amount":' . floatval($step->INFUSE_AMOUNT);
		else
			$steps .= ',"step_infuse_amount":0';
		if ($step->STEP_TEMP)
			$steps .= ',"step_temp":' . floatval($step->STEP_TEMP);
		if ($step->STEP_TIME)
			$steps .= ',"step_time":' . floatval($step->STEP_TIME);
		if ($step->RAMP_TIME)
			$steps .= ',"ramp_time":' . floatval($step->RAMP_TIME);
		if ($step->END_TEMP)
			$steps .= ',"end_temp":' . floatval($step->END_TEMP);
		$steps .= "}";
	}
	$steps .= ']';
	return $steps;
}



function do_recipes()
{
	global $brouwhulp, $db, $efficiency, $batch_size, $pCara, $pSugar, $svg, $colorw, $f_sugars;
	$len_fermentables = 0;
	$len_hops = 0;
	$len_miscs = 0;
	$len_yeasts = 0;
	$len_mash = 0;

	echo "  Start adding recipes to the database\n";
	$sql = "TRUNCATE TABLE recipes;";
	if (! $result = mysqli_query($db, $sql)) {
		printf("Error: %s\n", mysqli_error($db));
	}

	$recipes = simplexml_load_file($brouwhulp . '/recipes.xml');

	foreach ($recipes->RECIPE as $recipe) {
		$f_sugars = 0;
		$efficiency = 75;
		$batch_size = 20;
		$boil_size = 22;
		$pCara = 0;
		$pSugar = 0;
		$svg = 77;
		$colorw = 0;
		$uuid = str_replace("\n", "", file_get_contents('/proc/sys/kernel/random/uuid'));

		$sql  = "INSERT INTO recipes SET uuid='" . $uuid;
		$sql .= "', name='" . mysqli_real_escape_string($db, $recipe->NAME);
		$sql .= "', locked='0";
		if ($recipe->NOTES)
			$sql .= "', notes='" . mysqli_real_escape_string($db, $recipe->NOTES);
		else
			$sql .= "', notes='";

		if ($recipe->TYPE == 'Extract')
			$sql .= "', type='0";
		else if ($recipe->TYPE == 'Partial Mash')
			$sql .= "', type='1";
		else if ($recipe->TYPE == 'All Grain')
			$sql .= "', type='2";
		else
			echo "Unknown TYPE " . $recipe->TYPE . PHP_EOL;

		if ($recipe->BATCH_SIZE)
			$batch_size = floatval($recipe->BATCH_SIZE);
		$sql .= "', batch_size='" . $batch_size;
		if ($recipe->BOIL_SIZE)
			$boil_size = floatval($recipe->BOIL_SIZE);
		$sql .= "', boil_size='" . $boil_size;
		if ($recipe->BOIL_TIME)
			$sql .= "', boil_time='" . floatval($recipe->BOIL_TIME);
		else
			$sql .= "', boil_time='90";
		if ($recipe->EFFICIENCY)
			$efficiency = floatval($recipe->EFFICIENCY);
		$sql .= "', efficiency='" . $efficiency;
		/* Don't use $recipe->EST_OG but recalculate it */
		/* Don't use $recipe->EST_FG but recalculate it */
		/* Don't use $recipe->EST_COLOR but recalculate it */
		$color_method = 0;
		if ($recipe->COLOR_METHOD == 'Morey') {
			$color_method = 0;
			$sql .= "', color_method='0";
		} else if ($recipe->COLOR_METHOD == 'Mosher') {
			$color_method = 1;
			$sql .= "', color_method='1";
		} else if ($recipe->COLOR_METHOD == 'Daniels') {
			$color_method = 2;
			$sql .= "', color_method='2";
		} else
			echo "Unknown COLOR_METHO " . $recipe->COLOR_METHOD . PHP_EOL;

		if ($recipe->IBU)
			$sql .= "', est_ibu='" . floatval($recipe->IBU);
		if ($recipe->IBU_METHOD == 'Tinseth')
			$sql .= "', ibu_method='0";
		else if ($recipe->IBU_METHOD == 'Rager')
			$sql .= "', ibu_method='1";
		else if ($recipe->IBU_METHOD == 'Daniels')
			$sql .= "', ibu_method='2";
		else
			echo "Unknown IBU_METHOD " . $recipe->IBU_METHOD . PHP_EOL;

		if ($recipe->CARBONATION)
			$sql .= "', est_carb='" . floatval($recipe->CARBONATION);

		if ($recipe->STYLE) {
			$sql .= recipe_style($recipe);
		}
		if ($recipe->CALC_ACID) {
			($recipe->CALC_ACID == "TRUE") ? $sql .= "', calc_acid='1" : $sql .= "', calc_acid='0";
		}
		if ($recipe->TARGET_PH) {
			$sql .= "', mash_ph='" . floatval($recipe->TARGET_PH);
		}
		if ($recipe->SPARGE_ACID_TYPE && ($recipe->SPARGE_ACID_TYPE == "Lactic")) {
			$sql .= "', sparge_acid_type='0";
		} else if ($recipe->SPARGE_ACID_TYPE && ($recipe->SPARGE_ACID_TYPE == "Hydrochloric")) {
			$sql .= "', sparge_acid_type='1";
		} else if ($recipe->SPARGE_ACID_TYPE && ($recipe->SPARGE_ACID_TYPE == "Phosphoric")) {
			$sql .= "', sparge_acid_type='2";
		} else if ($recipe->SPARGE_ACID_TYPE && ($recipe->SPARGE_ACID_TYPE == "Sulfuric")) {
			$sql .= "', sparge_acid_type='3";
		}
		if ($recipe->ACID_SPARGE_PERC) {
			$sql .= "', sparge_acid_perc='" . floatval($recipe->ACID_SPARGE_PERC);
		}
		if ($recipe->LACTIC_SPARGE) {
			$sql .= "', sparge_acid_amount='" . floatval($recipe->LACTIC_SPARGE);
		}
		if ($recipe->VOLUME_HLT) {
			$sql .= "', sparge_volume='" . floatval($recipe->VOLUME_HLT);
		}
		$sql .= "', sparge_source='0";

		/*
		 * Put the fermentables in a json array
		 */
		if ($recipe->FERMENTABLES) {
			$fermentables = recipe_fermentables($recipe);
			$sql .= "', json_fermentables='" . $fermentables;
			if (strlen($fermentables) > $len_fermentables)
				$len_fermentables = strlen($fermentables);
		}

		/*
		 * Put the hops in a json array
		 */
		if ($recipe->HOPS) {
			$hops = recipe_hops($recipe);
			$sql .= "', json_hops='" . $hops;
			if (strlen($hops) > $len_hops)
				$len_hops = strlen($hops);
		}

		/*
		 * Put the miscs in a json array
		 */
		if ($recipe->MISCS) {
			$miscs = recipe_miscs($recipe);
			$sql .= "', json_miscs='" . $miscs;
			if (strlen($miscs) > $len_miscs)
				$len_miscs = strlen($miscs);
		}

		/*
		 * Put the yeasts in a json array
		 */
		if ($recipe->YEASTS) {
			$yeasts = recipe_yeasts($recipe);
			$sql .= "', json_yeasts='" . $yeasts;
			if (strlen($yeasts) > $len_yeasts)
				$len_yeasts = strlen($yeasts);
		}

		/*
		 * Get the waters
		 */
		if ($recipe->WATERS) {
			$sql .= recipe_waters($recipe, $db);
		}

		/*
		 * Put the mash in a json array
		 */
		if ($recipe->MASH) {
			$sql .= "',sparge_temp='" . floatval($recipe->MASH->SPARGE_TEMP);
			$sql .= "',sparge_ph='" . floatval($recipe->MASH->PH);
			if ($recipe->MASH->NAME)
				$sql .= "',mash_name='" . mysqli_real_escape_string($db, $recipe->MASH->NAME);

			if ($recipe->MASH->MASH_STEPS) {
				$steps = recipe_mash_steps($recipe);
				$sql .= "', json_mashs='" . $steps;
				if (strlen($steps) > $len_mash)
					$len_mash = strlen($steps);
			}
		}

		/*
		 * Added the calculated values
		 *  OG, FG, color, IBU
		 */
		$og = estimate_sg($f_sugars, $batch_size);
		$sql .= "', est_og='" . floatval($og);
		$fg = estimate_fg($pSugar, $pCara, 0, 0, 0, $svg, $og);
		$sql .= "', est_fg='" . floatval($fg);
		$abv = abvol($og, $fg);
		$sql .= "', est_abv='" . floatval($abv);
		$color = kw_to_ebc($color_method, $colorw);
		$sql .= "', est_color='" . floatval($color);
		$sql .= "';";
		if (! $result = mysqli_query($db, $sql)) {
			printf("Error: %s\n", mysqli_error($db));
		}
	}
//	echo "Fermentables: " . $len_fermentables . PHP_EOL;
//	echo "Hops:         " . $len_hops . PHP_EOL;
//	echo "Miscs:        " . $len_miscs . PHP_EOL;
//	echo "Yeasts:       " . $len_yeasts . PHP_EOL;
//	echo "Mash:         " . $len_mash . PHP_EOL;
}



function do_brews()
{
        global $brouwhulp, $db, $efficiency, $batch_size, $pCara, $pSugar, $colorw, $f_sugars;
        $len_fermentables = 0;
        $len_hops = 0;
        $len_miscs = 0;
        $len_yeasts = 0;
	$len_mash = 0;

        echo "  Start adding brews to the database\n";
        $sql = "TRUNCATE TABLE products;";
        if (! $presult = mysqli_query($db, $sql)) {
                printf("Error: %s\n", mysqli_error($db));
	}

	date_default_timezone_set('Europe/Amsterdam');
        $recipes = simplexml_load_file($brouwhulp . '/brews.xml');

        foreach ($recipes->RECIPE as $recipe) {
                $f_sugars = 0;
                $efficiency = 75;
                $batch_size = 20;
                $boil_size = 22;
                $pCara = 0;
                $pSugar = 0;
                $svg = 77;
		$colorw = 0;
		$stage = 0;
                $uuid = str_replace("\n", "", file_get_contents('/proc/sys/kernel/random/uuid'));

		$sql  = "INSERT INTO products SET uuid='" . $uuid;
		$sql .= "', name='" . mysqli_real_escape_string($db, $recipe->NAME);

                if ($recipe->NOTES) {
			$sql .= "', notes='" . mysqli_real_escape_string($db, $recipe->NOTES);
		} else {
			$sql .= "', notes='";
		}

		if ($recipe->TYPE == 'Extract')
			$sql .= "', type='0";
		else if ($recipe->TYPE == 'Partial Mash')
			$sql .= "', type='1";
		else if ($recipe->TYPE == 'All Grain')
			$sql .= "', type='2";

                if ($recipe->BATCH_SIZE)
                        $batch_size = floatval($recipe->BATCH_SIZE);
                $sql .= "', batch_size='" . $batch_size;
                if ($recipe->BOIL_SIZE)
                        $boil_size = floatval($recipe->BOIL_SIZE);
                $sql .= "', boil_size='" . $boil_size;
                if ($recipe->BOIL_TIME)
                        $sql .= "', boil_time='" . floatval($recipe->BOIL_TIME);
                else
                        $sql .= "', boil_time='90";
                if ($recipe->EFFICIENCY)
                        $efficiency = floatval($recipe->EFFICIENCY);
                $sql .= "', efficiency='" . $efficiency;
                /* Don't use $recipe->EST_OG but recalculate it */
                /* Don't use $recipe->EST_FG but recalculate it */
		/* Don't use $recipe->EST_COLOR but recalculate it */
		$color_method = 0;
		if ($recipe->COLOR_METHOD == 'Morey') {
			$color_method = 0;
			$sql .= "', color_method='0";
		} else if ($recipe->COLOR_METHOD == 'Mosher') {
			$color_method = 1;
			$sql .= "', color_method='1";
		} else if ($recipe->COLOR_METHOD == 'Daniels') {
			$color_method = 2;
			$sql .= "', color_method='2";
		} else
			echo "Unknown COLOR_METHO " . $recipe->COLOR_METHOD . PHP_EOL;

		if ($recipe->IBU)
			$sql .= "', est_ibu='" . floatval($recipe->IBU);
		if ($recipe->IBU_METHOD == 'Tinseth')
			$sql .= "', ibu_method='0";
		else if ($recipe->IBU_METHOD == 'Rager')
			$sql .= "', ibu_method='1";
		else if ($recipe->IBU_METHOD == 'Daniels')
			$sql .= "', ibu_method='2";
		else
			echo "Unknown IBU_METHOD " . $recipe->IBU_METHOD . PHP_EOL;

                if ($recipe->CARBONATION)
                        $sql .= "', est_carb='" . floatval($recipe->CARBONATION);

                if ($recipe->STYLE) {
                        $sql .= recipe_style($recipe);
                }

		if ($recipe->CALC_ACID) {
			($recipe->CALC_ACID == "TRUE") ? $sql .= "', calc_acid='1" : $sql .= "', calc_acid='0";
		}
		if ($recipe->TARGET_PH) {
			 $sql .= "', mash_ph='" . floatval($recipe->TARGET_PH);
		}
		if ($recipe->SPARGE_ACID_TYPE && ($recipe->SPARGE_ACID_TYPE == "Lactic")) {
			$sql .= "', sparge_acid_type='0";
		} else if ($recipe->SPARGE_ACID_TYPE && ($recipe->SPARGE_ACID_TYPE == "Hydrochloric")) {
			$sql .= "', sparge_acid_type='1";
		} else if ($recipe->SPARGE_ACID_TYPE && ($recipe->SPARGE_ACID_TYPE == "Phosphoric")) {
			$sql .= "', sparge_acid_type='2";
		} else if ($recipe->SPARGE_ACID_TYPE && ($recipe->SPARGE_ACID_TYPE == "Sulfuric")) {
			$sql .= "', sparge_acid_type='3";
		}
		if ($recipe->ACID_SPARGE_PERC) {
			$sql .= "', sparge_acid_perc='" . floatval($recipe->ACID_SPARGE_PERC);
		}
		if ($recipe->LACTIC_SPARGE) {
			$sql .= "', sparge_acid_amount='" . floatval($recipe->LACTIC_SPARGE);
		}
		if ($recipe->VOLUME_HLT) {
			$sql .= "', sparge_volume='" . floatval($recipe->VOLUME_HLT);
		}
		$sql .= "', sparge_source='0";

                /*
                 * Put the fermentables in a json array
                 */
                if ($recipe->FERMENTABLES) {
                        $fermentables = recipe_fermentables($recipe);
                        $sql .= "', json_fermentables='" . $fermentables;
                        if (strlen($fermentables) > $len_fermentables)
                                $len_fermentables = strlen($fermentables);
                }

                /*
                 * Put the hops in a json array
                 */
                if ($recipe->HOPS) {
                        $hops = recipe_hops($recipe);
                        $sql .= "', json_hops='" . $hops;
                        if (strlen($hops) > $len_hops)
                                $len_hops = strlen($hops);
                }

                /*
                 * Put the miscs in a json array
                 */
                if ($recipe->MISCS) {
                        $miscs = recipe_miscs($recipe);
                        $sql .= "', json_miscs='" . $miscs;
                        if (strlen($miscs) > $len_miscs)
                                $len_miscs = strlen($miscs);
                }

                /*
                 * Put the yeasts in a json array
                 */
                if ($recipe->YEASTS) {
                        $yeasts = recipe_yeasts($recipe);
                        $sql .= "', json_yeasts='" . $yeasts;
                        if (strlen($yeasts) > $len_yeasts)
                                $len_yeasts = strlen($yeasts);
                }

                /*
                 * Get the waters
                 */
                if ($recipe->WATERS) {
                        $sql .= recipe_waters($recipe, $db);
                }

                /*
                 * Put the mash in a json array
                 */
                if ($recipe->MASH) {
                        $sql .= "',sparge_temp='" . floatval($recipe->MASH->SPARGE_TEMP);
                        $sql .= "',sparge_ph='" . floatval($recipe->MASH->PH);
                        if ($recipe->MASH->NAME)
                                $sql .= "',mash_name='" . mysqli_real_escape_string($db, $recipe->MASH->NAME);

                        if ($recipe->MASH->MASH_STEPS) {
                                $steps = recipe_mash_steps($recipe);
                                $sql .= "', json_mashs='" . $steps;
                                if (strlen($steps) > $len_mash)
                                        $len_mash = strlen($steps);
                        }
                }

                /*
                 * Added the calculated values
                 *  OG, FG, color, IBU
                 */
                $og = estimate_sg($f_sugars, $batch_size);
                $sql .= "', est_og='" . floatval($og);
                $fg = estimate_fg($pSugar, $pCara, 0, 0, 0, $svg, $og);
                $sql .= "', est_fg='" . floatval($fg);
                $abv = abvol($og, $fg);
                $sql .= "', est_abv='" . floatval($abv);
                $color = kw_to_ebc($color_method, $colorw);
                $sql .= "', est_color='" . floatval($color);
		$sql .= "', code='" . mysqli_real_escape_string($db, $recipe->NR_RECIPE);

		/*
		 * Update external logfiles
		 */
		$lsql  = "UPDATE log_brews SET product_uuid='".$uuid."', product_name='".mysqli_real_escape_string($db, $recipe->NAME);
		$lsql .= "' WHERE product_code='".mysqli_real_escape_string($db, $recipe->NR_RECIPE)."';";
		if (! $result = mysqli_query($db, $lsql)) {
			printf("Error: %s\n", mysqli_error($db));
		}
		$count = mysqli_affected_rows($db);
		if ($count > 0) {
			$sql .= "', log_brew='1";
		}

		$filename = '../log/fermentation/'.$recipe->NR_RECIPE.' '.$recipe->NAME.'.log';
		if (file_exists($filename)) {
			$sql .= "', log_fermentation='1";
		} else {
			if ($recipe->FERM_MEASUREMENTS) {
				/*
				 * There is internal logdata in the xml, create a logfile
				 */
				$fp = fopen($filename, "w+");
				foreach ($recipe->FERM_MEASUREMENTS->FERM_MEASUREMENT as $measurement) {
					$dt = substr($measurement->DATE_TIME, 6, 4).substr($measurement->DATE_TIME,2,4).substr($measurement->DATE_TIME,0,2);
					$dt .= ' '.substr($measurement->DATE_TIME, 11,8);
					$line = $dt.',NONE,PRIMARY,';
					$line .= sprintf("%.1f",floatval($measurement->TEMP_SENSOR_1)) .',';
					$line .= sprintf("%.1f",floatval($measurement->TEMP_SENSOR_2)) .',';
					$line .= 'NA,NA,NA,NA,NA,NA,NA,NA,' . PHP_EOL;
					fwrite($fp, $line);
				}
				fclose($fp);
				$sql .= "', log_fermentation='1";
			} else {
				$sql .= "', log_fermentation='0";
			}
		}

		if ($recipe->EQUIPMENT) {
			$sql .= "', eq_name='" . mysqli_real_escape_string($db, $recipe->EQUIPMENT->NAME);
			$sql .= "', eq_notes='" . mysqli_real_escape_string($db, $recipe->EQUIPMENT->NOTES);
			$sql .= "', eq_boil_size='" . floatval($recipe->EQUIPMENT->BOIL_SIZE);
			$sql .= "', eq_batch_size='" . floatval($recipe->EQUIPMENT->BATCH_SIZE);
			$sql .= "', eq_tun_volume='" . floatval($recipe->EQUIPMENT->TUN_VOLUME);
			$sql .= "', eq_tun_weight='" . floatval($recipe->EQUIPMENT->TUN_WEIGHT);
			$sql .= "', eq_tun_specific_heat='" . floatval($recipe->EQUIPMENT->TUN_SPECIFIC_HEAT);
			$sql .= "', eq_tun_material='" . $recipe->EQUIPMENT->TUN_MATERIAL;
			$sql .= "', eq_tun_height='" . floatval($recipe->EQUIPMENT->TUN_HEIGHT);
			if ($recipe->EQUIPMENT->TOP_UP_WATER)
				$sql .= "', eq_top_up_water='" . floatval($recipe->EQUIPMENT->TOP_UP_WATER);
			$sql .= "', eq_trub_chiller_loss='" . floatval($recipe->EQUIPMENT->TRUB_CHILLER_LOSS);
			/*
			 * Brouwhulp uses a percentage for the evaporation rate. This is wrong
			 * but was made so because the beerxml standard requires this. What we
			 * do is calculate the actual evaporation and store that.
			 * This is what we use. Brouwhulp calculates this on the fly.
			 */
			$sql .= "', eq_evap_rate='" . (floatval($recipe->EQUIPMENT->EVAP_RATE) * floatval($recipe->EQUIPMENT->BOIL_SIZE)) / 100;
			$sql .= "', eq_boil_time='" . floatval($recipe->EQUIPMENT->BOIL_TIME);
			($recipe->EQUIPMENT->CALC_BOIL_VOLUME == 'TRUE') ? $sql .= "', eq_calc_boil_volume='1" : $sql .= "', eq_calc_boil_volume='0";
			if ($recipe->EQUIPMENT->TOP_UP_KETTLE)
				$sql .= "', eq_top_up_kettle='" . floatval($recipe->EQUIPMENT->TOP_UP_KETTLE);
			$sql .= "', eq_hop_utilization='" . floatval($recipe->EQUIPMENT->HOP_UTILIZATION);
			$sql .= "', eq_lauter_volume='" . floatval($recipe->EQUIPMENT->LAUTER_VOLUME);
			$sql .= "', eq_lauter_height='" . floatval($recipe->EQUIPMENT->LAUTER_HEIGHT);
			$sql .= "', eq_lauter_deadspace='" . floatval($recipe->EQUIPMENT->LAUTER_DEADSPACE);
			$sql .= "', eq_kettle_volume='" . floatval($recipe->EQUIPMENT->KETTLE_VOLUME);
			$sql .= "', eq_kettle_height='" . floatval($recipe->EQUIPMENT->KETTLE_HEIGHT);
			$sql .= "', eq_mash_volume='" . floatval($recipe->EQUIPMENT->MASH_VOLUME);
			$sql .= "', eq_mash_max='" . round((floatval($recipe->EQUIPMENT->MASH_VOLUME) / 3) * 10) / 10;     // Not in beerxml/brouwhulp. For RIMS systems.
			$sql .= "', eq_efficiency='" . floatval($recipe->EQUIPMENT->EFFICIENCY);
		}

		if (($recipe->DATE) && (! $recipe->TIME_STARTED) && (! $recipe->TIME_ENDED)) {
			/* We have a plan date but haven't brewed yet, use current date */
			$sql .= "', birth='" . date("Y-m-d");
			$stage = 1;
		}

		if (($recipe->DATE) && ($recipe->TIME_STARTED) && ($recipe->TIME_ENDED)) {
			/* We have brew data */
			$stage = 3;	// Need to think about during a brew...
			$brewdate = substr($recipe->DATE, 6, 4).substr($recipe->DATE,2,4).substr($recipe->DATE,0,2);
			$sql .= "', birth='" . $brewdate;
			$date_start = $brewdate.' '.$recipe->TIME_STARTED;
			$date_end   = $brewdate.' '.$recipe->TIME_ENDED;
			$sql .= "', brew_date_start='" . $date_start;

			if ($recipe->PH_ADJUSTED)
				$sql .= "', brew_mash_ph='" . floatval($recipe->PH_ADJUSTED);
			if (floatval($recipe->SG_END_MASH) != 1.0)
				$sql .= "', brew_mash_sg='" . floatval($recipe->SG_END_MASH);
			if ($recipe->MASH->PH)
				$sql .= "', brew_sparge_ph='" . floatval($recipe->MASH->PH);
			if ($recipe->VOLUME_HLT)
				$sql .= "', sparge_volume='" . floatval($recipe->VOLUME_HLT);
			if ($recipe->VOLUME_BEFORE_BOIL)
				$sql .= "', brew_preboil_volume='" . sprintf("%.5f",floatval($recipe->VOLUME_BEFORE_BOIL) * 1.04);
			if (floatval($recipe->OG_BEFORE_BOIL) != 1.0)
				$sql .= "', brew_preboil_sg='" . floatval($recipe->OG_BEFORE_BOIL);
			if ($recipe->PH_BEFORE_BOIL)
				$sql .= "', brew_preboil_ph='" . floatval($recipe->PH_BEFORE_BOIL);
			if ($recipe->VOLUME_AFTER_BOIL)
				$sql .= "', brew_aboil_volume='" . sprintf("%.5f",floatval($recipe->VOLUME_AFTER_BOIL) * 1.04);
			$sql .= "', brew_aboil_sg='" . floatval($recipe->OG);
			if ($recipe->PH_AFTER_BOIL)
				$sql .= "', brew_aboil_ph='" . floatval($recipe->PH_AFTER_BOIL);
			if ($recipe->ACTUAL_EFFICIENCY)
				$sql .= "', brew_aboil_efficiency='" . floatval($recipe->ACTUAL_EFFICIENCY);
			$sql .= "', brew_whirlpool2='" . floatval($recipe->WHIRLPOOL_TIME);

			if ($recipe->COOLING_METHOD == '-')
				$sql .= "', brew_cooling_method='0";
			else if ($recipe->COOLING_METHOD == 'Emersion chiller')
				$sql .= "', brew_cooling_method='1";
			else if ($recipe->COOLING_METHOD == 'Counterflow chiller')
				$sql .= "', brew_cooling_method='2";
			else if ($recipe->COOLING_METHOD == 'Au bain marie')
				$sql .= "', brew_cooling_method='3";
			else if ($recipe->COOLING_METHOD == 'Natural')
				$sql .= "', brew_cooling_method='4";
			else
				echo "Unknown COOLING_METHOD " . $recipe->COOLING_METHOD . PHP_EOL;
			$sql .= "', brew_cooling_time='" . floatval($recipe->COOLING_TIME);
			$sql .= "', brew_cooling_to='" . floatval($recipe->COOLING_TO);
			if ($recipe->VOLUME_FERMENTER)
				$sql .= "', brew_fermenter_volume='" . floatval($recipe->VOLUME_FERMENTER);
			if ($recipe->EQUIPMENT->TOP_UP_WATER_BREWDAY)
				$sql .= "', brew_fermenter_extrawater='" . floatval($recipe->EQUIPMENT->TOP_UP_WATER_BREWDAY);
			$sql .= "', brew_fermenter_sg='" . floatval($recipe->OG_FERMENTER);
			$sql .= "', brew_fermenter_ibu='" . floatval($recipe->IBU);

			if ($recipe->AERATION_TYPE == 'None')
				$sql .= "', brew_aeration_type='0";
			else if ($recipe->AERATION_TYPE == 'Air') {
				$sql .= "', brew_aeration_type='1";
				$sql .= "', brew_aeration_speed='" . floatval($recipe->AERATION_SPEED);
				$sql .= "', brew_aeration_time='" . floatval($recipe->AERATION_TIME);
			} else if ($recipe->AERATION_TYPE == 'Oxygen') {
				$sql .= "', brew_aeration_type='2";
				$sql .= "', brew_aeration_speed='" . floatval($recipe->AERATION_SPEED);
				$sql .= "', brew_aeration_time='" . floatval($recipe->AERATION_TIME);
			} else
				echo "Unknown AERATION_TYPE " . $recipe->AERATION_TYPE . PHP_EOL;

			$sql .= "', brew_date_end='" . $date_end;
		}

		$sql .= "', og='" . floatval($recipe->OG);
		$sql .= "', fg='" . floatval($recipe->FG);

		if ($recipe->PRIMARY_AGE && ($stage >= 3)) {
			/* PRIMARY_TEMP is the average of START_TEMP_PRIMARY MAX_TEMP_PRIMARY END_TEMP_PRIMARY */
			$pdate = new DateTime($brewdate);
			$pdate->modify("+".floatval($recipe->PRIMARY_AGE)." days");
			$sql .= "', primary_start_temp='" . floatval($recipe->START_TEMP_PRIMARY);
			$sql .= "', primary_max_temp='" . floatval($recipe->MAX_TEMP_PRIMARY);
			$sql .= "', primary_end_temp='" . floatval($recipe->END_TEMP_PRIMARY);
			$sql .= "', primary_end_sg='" . floatval($recipe->SG_END_PRIMARY);
			$sql .= "', primary_end_date='" . $pdate->format("Y-m-d");
			$stage = 4;	// Secondary

			if ($recipe->SECONDARY_AGE && ($stage >= 4)) {
				$sdate = new DateTime($brewdate);
				$sdate->modify("+".floatval($recipe->SECONDARY_AGE)." days");
				$sql .= "', secondary_temp='" . floatval($recipe->SECONDARY_TEMP);
				$sql .= "', secondary_end_sg='" . floatval($recipe->FG);
				$sql .= "', secondary_end_date='" . $sdate->format("Y-m-d");
				$stage = 5;	// Tertiary

				if ($recipe->TERTIARY_TEMP && ($stage >= 5)) {
					$sql .= "', tertiary_temp='" . floatval($recipe->TERTIARY_TEMP);
				}
			}
		}

		if ($recipe->DATE_BOTTLING && ($recipe->AMOUNT_BOTTLING || $recipe->AMOUNT_KEGGED) &&
		    ($recipe->AMOUNT_PRIMING || $recipe->AMOUNT_PRIMING_KEGS) && ($stage >= 5)) {
			$bdate = substr($recipe->DATE_BOTTLING, 6, 4).substr($recipe->DATE_BOTTLING,2,4).substr($recipe->DATE_BOTTLING,0,2);
			$sql .= "', package_date='" . $bdate;
			$stage = 6;	// Package
			$dStart = new DateTime($bdate);
			$dEnd  = new DateTime('');
			$dDiff = $dStart->diff($dEnd);
			$age = floatval($dDiff->days);
			if ($age == 0) {		// Package day
				$stage = 6;
			} else if ($age < 14) {		// Carbonation period
				$stage = 7;
			} else if ($age < 42) {		// Mature, fixed 6 weeks
				$stage = 8;
			} else {			// Ready for tasting.
				$stage = 9;
			}

			if ($recipe->AMOUNT_BOTTLING && $recipe->AMOUNT_PRIMING) {
				$sql .= "', bottle_amount='" . floatval($recipe->AMOUNT_BOTTLING);
				$sql .= "', bottle_carbonation='" . floatval($recipe->CARBONATION);

				if ($recipe->PRIMING_SUGAR_BOTTLES == "Saccharose")
					$sql .= "', bottle_priming_sugar='0";
				else if ($recipe->PRIMING_SUGAR_BOTTLES == "Glucose or dextrose")
					$sql .= "', bottle_priming_sugar='1";
				else if ($recipe->PRIMING_SUGAR_BOTTLES == "Honey")
					$sql .= "', bottle_priming_sugar='2";
				else if ($recipe->PRIMING_SUGAR_BOTTLES == "DME")
					$sql .= "', bottle_priming_sugar='3";
				else if ($recipe->PRIMING_SUGAR_BOTTLES == "Molassis")
					$sql .= "', bottle_priming_sugar='4";
				$sql .= "', bottle_priming_amount='" . floatval($recipe->AMOUNT_PRIMING);
				$sql .= "', bottle_carbonation_temp='" . floatval($recipe->CARBONATION_TEMP);
			}
			if ($recipe->AMOUNT_KEGGED && $recipe->AMOUNT_PRIMING_KEGS) {
				$sql .= "', keg_amount='" . floatval($recipe->AMOUNT_KEGGED);
				$sql .= "', keg_carbonation='" . floatval($recipe->CARBONATION); // Lijkt wel hetzelfde als bottles
				if ($recipe->PRIMING_SUGAR_BOTTLES == "Saccharose")
					$sql .= "', keg_priming_sugar='0";
				else if ($recipe->PRIMING_SUGAR_BOTTLES == "Glucose or dextrose")
					$sql .= "', keg_priming_sugar='1";
				else if ($recipe->PRIMING_SUGAR_BOTTLES == "Honey")
					$sql .= "', keg_priming_sugar='2";
				else if ($recipe->PRIMING_SUGAR_BOTTLES == "DME")
					$sql .= "', keg_priming_sugar='3";
				else if ($recipe->PRIMING_SUGAR_BOTTLES == "Molassis")
					$sql .= "', keg_priming_sugar='4";
				$sql .= "', keg_priming_amount='" . floatval($recipe->AMOUNT_PRIMING_KEGS);
				$sql .= "', keg_carbonation_temp='" . floatval($recipe->KEG_CARB_TEMP);
				($recipe->FORCED_CARB_KEGS == 'TRUE') ? $sql .= "', keg_forced_carb='1" : $sql .= "', keg_forced_carb='0";
				$sql .= "', keg_pressure='" . floatval($recipe->KEG_PRESSURE);
			}
		}

		if ($recipe->TASTE_NOTES && $recipe->TASTING_RATE && $recipe->TASTE_DATE && ($stage >= 9)) {
			$stage = 10;	// Ready
			$sql .= "', taste_notes='" . mysqli_real_escape_string($db, $recipe->TASTE_NOTES);
			$sql .= "', taste_rate='" . floatval($recipe->TASTING_RATE);
			$tdate = substr($recipe->TASTE_DATE, 6, 4).substr($recipe->TASTE_DATE,2,4).substr($recipe->TASTE_DATE,0,2);
			$sql .= "', taste_date='" . $tdate;
			$sql .= "', taste_color='" . mysqli_real_escape_string($db, $recipe->TASTE_COLOR);
			$sql .= "', taste_transparency='" . mysqli_real_escape_string($db, $recipe->TASTE_TRANSPARENCY);
			$sql .= "', taste_head='" . mysqli_real_escape_string($db, $recipe->TASTE_HEAD);
			$sql .= "', taste_aroma='" . mysqli_real_escape_string($db, $recipe->TASTE_AROMA);
			$sql .= "', taste_taste='" . mysqli_real_escape_string($db, $recipe->TASTE_TASTE);
			$sql .= "', taste_mouthfeel='" . mysqli_real_escape_string($db, $recipe->TASTE_MOUTHFEEL);
			$sql .= "', taste_aftertaste='" . mysqli_real_escape_string($db, $recipe->TASTE_AFTERTASTE);
		}

		($recipe->INVENTORY_REDUCED == 'TRUE') ? $sql .= "', inventory_reduced='1" : $sql .= "', inventory_reduced='0";
		if (($recipe->LOCKED == 'TRUE') && ($stage == 10)) {
			$sql .= "', locked='1";
			$stage = 11;
		} else {
			$sql .= "', locked='0";
		}

		$sql .= "', stage='" . $stage;
//		echo ' '.$brewdate.' '.$recipe->NR_RECIPE.' '.$stage . PHP_EOL;

		$sql .= "';";
		if (! $rresult = mysqli_query($db, $sql)) {
			printf("Error: %s\n", mysqli_error($db));
		}
        }
}



do_fermentables();
do_hops();
do_yeasts();
do_miscs();
do_waters();
do_equipments();
do_styles();
do_mash();
do_recipes();
do_brews();


mysqli_close($db);

echo "Finished adding data\n";


?>

mercurial