Example #1
0
function snowpilot_node_write_pitxml($node)
{
    $snowpilot_xmldoc = new DOMDocument('1.0', 'UTF-8');
    $snowpilot_PitCore = $snowpilot_xmldoc->createElement("Pit_Observation");
    $snowpilot_xmldoc->appendChild($snowpilot_PitCore);
    $snowpilot_User = $snowpilot_xmldoc->createElement("User");
    $snowpilot_PitCore->appendChild($snowpilot_User);
    $snowpilot_Location = $snowpilot_xmldoc->createElement("Location");
    $snowpilot_PitCore->appendChild($snowpilot_Location);
    // ...but we have multiple layers
    // Likewise, multiple shear test results
    $snowpilot_Density = $snowpilot_xmldoc->createElement("Density_Profile");
    $snowpilot_Temp = $snowpilot_xmldoc->createElement("Temperature_Profile");
    //PitCore Attributes: activities, aviLoc,iLayerNumber, bld, stability,avipit,incline,winDir,skiAreaPit ,bcPit, testPit,windspeed,aspect,skiBoot,measureFrom,sky,sufacePen, windloading,heightOfSnowpack,precip , serial, version,pitNotes,crownObs,timestamp,iDepth
    $activities = $snowpilot_xmldoc->createAttribute("activities");
    $activities->value = _generate_specifics_string($node);
    $snowpilot_PitCore->appendChild($activities);
    //aviLoc - or 'Pit is near avalanche at what point?'
    $aviLoc = $snowpilot_xmldoc->createAttribute("aviLoc");
    $aviLoc->value = isset($node->field_near_avalanche['und'][0]['value']) ? $node->field_near_avalanche['und'][0]['value'] : '';
    $snowpilot_PitCore->appendChild($aviLoc);
    // iLayerNumber
    // this implementation assumes that the layers are in numerical order from top down; item_id is a unique id in field collections, can't use it.
    $iLayerNumber = $snowpilot_xmldoc->createAttribute("iLayerNumber");
    $iDepth = $snowpilot_xmldoc->createAttribute("iDepth");
    $ids = array();
    foreach ($node->field_layer['und'] as $lay) {
        $ids[] = $lay['value'];
    }
    $all_layers = field_collection_item_load_multiple($ids);
    $iLayerNumber_value = 1;
    $iLayerNumber->value = '';
    foreach ($all_layers as $x => $layer) {
        if ($layer->field_this_is_my_layer_of_greate['und'][0]['value'] == '1') {
            $iLayerNumber->value = $iLayerNumber_value;
            $iDepth->value = $layer->field_concern['und'][0]['value'] == 'top' ? $layer->field_height['und'][0]['value'] : $node->field_bottom_depth['und'][0]['value'];
            break;
        } else {
            $iLayerNumber_value++;
        }
    }
    $snowpilot_PitCore->appendChild($iLayerNumber);
    $snowpilot_PitCore->appendChild($iDepth);
    //
    //bld is the build number from the snowpilot desktop app. for this case, we will use drupal version 7.xx
    $bld = $snowpilot_xmldoc->createAttribute("bld");
    $bld->value = VERSION;
    $snowpilot_PitCore->appendChild($bld);
    //
    // stability
    $stability = $snowpilot_xmldoc->createAttribute("stability");
    //dsm($node->field_stability_on_similar_slope['und'][0]['value']);
    $similar_stability = field_view_field('node', $node, 'field_stability_on_similar_slope');
    $stability->value = isset($node->field_stability_on_similar_slope['und'][0]['value']) ? $similar_stability[0]['#markup'] : '';
    $snowpilot_PitCore->appendChild($stability);
    //
    // aviPit
    //
    $aviPit = $snowpilot_xmldoc->createAttribute("aviPit");
    $crownObs = $snowpilot_xmldoc->createAttribute("crownObs");
    $aviPit->value = isset($node->field_adjacent_to_avy['und'][0]['value']) && $node->field_adjacent_to_avy['und'][0]['value'] == 1 ? 'true' : 'false';
    $snowpilot_PitCore->appendChild($aviPit);
    $crownObs->value = $aviPit->value;
    $snowpilot_PitCore->appendChild($crownObs);
    // CrownObs is a synonym for aviPit in the avscience_db
    //
    //
    //  aviLoc - location of pit relative to the Avalanche: crown, flank, none ( unlike desktop app, this will only be populated in the case of aviPit == true )
    //
    $aviLoc = $snowpilot_xmldoc->createAttribute("aviLoc");
    if (isset($node->field_adjacent_to_avy['und'][0]['value']) && $node->field_adjacent_to_avy['und'][0]['value'] == 1 && isset($node->field_near_avalanche['und'][0]['value'])) {
        $aviLoc->value = $node->field_near_avalanche['und'][0]['value'];
    } else {
        $aviLoc->value = '';
    }
    $snowpilot_PitCore->appendChild($aviLoc);
    // incline
    $incline = $snowpilot_xmldoc->createAttribute("incline");
    $incline->value = isset($node->field_slope_angle['und'][0]['value']) ? $node->field_slope_angle['und'][0]['value'] : '';
    $snowpilot_PitCore->appendChild($incline);
    //
    // winDir
    $winDir = $snowpilot_xmldoc->createAttribute("winDir");
    $winDir->value = isset($node->field_wind_direction['und'][0]['value']) ? snowpilot_cardinal_wind_dir($node->field_wind_direction['und'][0]['value']) : '';
    $snowpilot_PitCore->appendChild($winDir);
    //
    //skiAreaPit
    $skiAreaPit = $snowpilot_xmldoc->createAttribute("skiAreaPit");
    $skiAreaPit->value = isset($node->field_pit_dug_in_a_ski_area['und'][0]['value']) && $node->field_pit_dug_in_a_ski_area['und'][0]['value'] == 1 ? 'true' : 'false';
    $snowpilot_PitCore->appendChild($skiAreaPit);
    //
    //
    // bcPit        Trinary: true , false ,or '' unset
    // we leavre unset if the 'skiAreaPit' variable is unset, or false
    $bcPit = $snowpilot_xmldoc->createAttribute("bcPit");
    if (!isset($node->field_pit_is_representative_of_b['und'][0]['value']) || !isset($node->field_pit_dug_in_a_ski_area['und'][0]['value']) || $node->field_pit_dug_in_a_ski_area['und'][0]['value'] == 0) {
        $bcPit->value = '';
    } elseif ($node->field_pit_is_representative_of_b['und'][0]['value'] == '1') {
        $bcPit->value = 'true';
    } else {
        $bcPit->value = 'false';
    }
    $snowpilot_PitCore->appendChild($bcPit);
    //
    // testpit
    //
    $testPit = $snowpilot_xmldoc->createAttribute("testPit");
    $testPit->value = isset($node->field_pit_dug_in_a_ski_area['und'][0]['value']) && $node->field_pit_dug_in_a_ski_area['und'][0]['value'] == 1 ? 'true' : 'false';
    $snowpilot_PitCore->appendChild($testPit);
    //
    //windspeed
    $windspeed = $snowpilot_xmldoc->createAttribute("windspeed");
    $wind_speed = field_view_field('node', $node, 'field_wind_speed');
    $windspeed->value = isset($node->field_wind_speed['und'][0]['value']) ? $wind_speed[0]['#markup'] : '';
    $snowpilot_PitCore->appendChild($windspeed);
    //
    // aspect
    $aspect = $snowpilot_xmldoc->createAttribute("aspect");
    $aspect->value = isset($node->field_aspect['und'][0]['value']) ? $node->field_aspect['und'][0]['value'] : '';
    $snowpilot_PitCore->appendChild($aspect);
    //
    // skiBoot   - Surface Penetration
    // set whether dki or boot penetration is used; and identify the value of each
    $skiBoot = $snowpilot_xmldoc->createAttribute("skiBoot");
    $surfacePen = $snowpilot_xmldoc->createAttribute("surfacePen");
    if (!isset($node->field_surface_penetration['und'][0]['value'])) {
        $skiBoot->value = '';
    } elseif ($node->field_surface_penetration['und'][0]['value'] == 'boot') {
        $skiBoot->value = 'boot';
        $surfacePen->value = isset($node->field_boot_penetration_depth['und'][0]['value']) ? $node->field_boot_penetration_depth['und'][0]['value'] : '';
    } else {
        $skiBoot->value = 'ski';
        $surfacePen->value = isset($node->field_ski_penetration['und'][0]['value']) ? $node->field_ski_penetration['und'][0]['value'] : '';
    }
    $snowpilot_PitCore->appendChild($skiBoot);
    $snowpilot_PitCore->appendChild($surfacePen);
    //
    //  measureFrom
    $measureFrom = $snowpilot_xmldoc->createAttribute("measureFrom");
    $measureFrom->value = isset($node->field_depth_0_from['und'][0]['value']) && $node->field_depth_0_from['und'][0]['value'] == 'top' ? 'top' : 'bottom';
    $snowpilot_PitCore->appendChild($measureFrom);
    //
    // Sky coverage
    //
    $skyCoverage = $snowpilot_xmldoc->createAttribute('sky');
    if (isset($node->field_sky_cover['und'])) {
        $sky_cover = field_view_field('node', $node, 'field_sky_cover');
        $skyCoverage->value = $sky_cover[0]['#markup'];
    }
    $snowpilot_PitCore->appendChild($skyCoverage);
    //
    //  Wind Loading
    //
    $windLoading = $snowpilot_xmldoc->createAttribute('windLoading');
    if (isset($node->field_wind_loading['und'][0]['value'])) {
        $windLoading->value = $node->field_wind_loading['und'][0]['value'];
    }
    $snowpilot_PitCore->appendChild($windLoading);
    //
    //  heightof Snowpack
    //
    $HoSnowpack = $snowpilot_xmldoc->createAttribute('heightOfSnowpack');
    if (isset($node->field_total_height_of_snowpack['und'][0]['value'])) {
        $HoSnowpack->value = $node->field_total_height_of_snowpack['und'][0]['value'];
    }
    $snowpilot_PitCore->appendChild($HoSnowpack);
    //
    //  Precipitation
    //
    $precipitation = $snowpilot_xmldoc->createAttribute('precip');
    if (isset($node->field_precipitation['und'][0]['value'])) {
        $precipitation->value = $node->field_precipitation['und'][0]['value'];
    }
    $snowpilot_PitCore->appendChild($precipitation);
    //
    //  Serial number - must be unique to this pit
    //  To maintain continuity with the desktop app, it should be username + timestamp ( unix, w/ milliseconds) of posting the item
    //  php microtime won't work here; we jsut use a millisecond timestamp padded with 0
    //
    $serial_num = $snowpilot_xmldoc->createAttribute('serial');
    $account = user_load($node->uid);
    $serial_num->value = $account->name . $node->created . '000';
    $snowpilot_PitCore->appendChild($serial_num);
    //
    //  version - this will include drupal bld number ( starting at 7.5x ) and then also include the snowpilot.module version, and the browser type and version (similar to desktop app)
    //  I don't think browser type is directly supported within drupal, need browsecap module (?)
    //
    $web_version = $snowpilot_xmldoc->createAttribute('version');
    $snowpilot_version = '0.1';
    // this will need to be read from the module version eventually
    $web_version->value = VERSION . '-' . $snowpilot_version;
    // and then we'll need to append the browser and OS if we can.
    $snowpilot_PitCore->appendChild($web_version);
    //
    // Pit Notes- a potentially long text field, with wierd foregin characters and illegal characters
    //
    $pit_notes = $snowpilot_xmldoc->createAttribute('pitNotes');
    if (isset($node->body['und'])) {
        $pit_notes->value = $node->body['und'][0]['safe_value'];
    }
    $snowpilot_PitCore->appendChild($pit_notes);
    //
    //  timestamp
    //
    $timestamp = $snowpilot_xmldoc->createAttribute('timestamp');
    $timestamp->value = $node->created . '000';
    $snowpilot_PitCore->appendChild($timestamp);
    //
    // Snowpilot name: User; drupal object: account
    //
    $username = $snowpilot_xmldoc->createAttribute('username');
    // this doesn't actually exist in the snowpilot data model, but seems good to include
    $username->value = $account->name;
    $snowpilot_User->appendChild($username);
    $unit_prefs = snowpilot_unit_prefs_get($node, 'node');
    $preferences = array();
    foreach ($unit_prefs as $key => $pref) {
        if (substr($key, 0, 6) != 'field_') {
            $preferences[$key] = $snowpilot_xmldoc->createAttribute($key);
            $preferences[$key]->value = $pref;
            $snowpilot_User->appendChild($preferences[$key]);
        }
    }
    //$snowpilot_User->removeChild('range');
    //
    //  useSymbols (?)
    //
    $useSymbols = $snowpilot_xmldoc->createAttribute('useSymbols');
    $useSymbols->value = 'true';
    $snowpilot_User->appendChild($useSymbols);
    //
    // full name
    //
    $fullName = $snowpilot_xmldoc->createAttribute('name');
    $firstName = $snowpilot_xmldoc->createAttribute('first');
    $lastName = $snowpilot_xmldoc->createAttribute('last');
    $firstName->value = isset($account->field_first_name['und']) ? $account->field_first_name['und'][0]['safe_value'] : '';
    $lastName->value = isset($account->field_last_name['und']) ? $account->field_last_name['und'][0]['safe_value'] : '';
    $space = $firstName->value != '' && $lastName->value != '' ? ' ' : '';
    $fullName->value = $firstName->value . $space . $account->field_last_name['und'][0]['safe_value'];
    $snowpilot_User->appendChild($firstName);
    $snowpilot_User->appendChild($lastName);
    $snowpilot_User->appendChild($fullName);
    //
    //  share
    //   this needs to become trinary, not just boolean
    $pitShare = $snowpilot_xmldoc->createAttribute('share');
    $pitShare->value = $node->field_snowpit_visibility['und'][0]['value'] == 'public' ? 'true' : $node->field_snowpit_visibility['und'][0]['value'];
    $snowpilot_User->appendChild($pitShare);
    //
    //  phone of submitter
    //
    $userPhone = $snowpilot_xmldoc->createAttribute('phone');
    $userPhone->value = $account->field_phone['und'][0]['value'];
    $snowpilot_User->appendChild($userPhone);
    //
    // prof - professional checkbox
    //
    $userProf = $snowpilot_xmldoc->createAttribute('prof');
    $userProf->value = isset($account->field_professional['und'][0]['value']) && $account->field_professional['und'][0]['value'] == '1' ? 'true' : 'false';
    $snowpilot_User->appendChild($userProf);
    //
    // email
    //
    $userEmail = $snowpilot_xmldoc->createAttribute('email');
    $userEmail->value = $account->mail;
    $snowpilot_User->appendChild($userEmail);
    //
    // affil - Affilliation
    //
    $profAffil = $snowpilot_xmldoc->createAttribute('affil');
    $profAffil->value = isset($account->field_professional_affiliation['und'][0]['tid']) ? taxonomy_term_load($account->field_professional_affiliation['und'][0]['tid'])->name : '';
    $snowpilot_User->appendChild($profAffil);
    //
    //  Location Element
    //
    // Coordinate type: UTM or Lat / Long
    //
    $coordType = $snowpilot_xmldoc->createAttribute('type');
    $coordType->value = $unit_prefs['coordType'] == 'UTM' ? 'UTM' : 'LATLONG';
    $snowpilot_Location->appendChild($coordType);
    //zone
    $UTMzone = $snowpilot_xmldoc->createAttribute('zone');
    $UTMzone->value = $unit_prefs['zone'];
    $snowpilot_Location->appendChild($UTMzone);
    //
    // whether Lat long is measure N or S of equator; E or W of 0 degrees
    $nstype = $snowpilot_xmldoc->createAttribute('ns');
    $nstype->value = $unit_prefs['latType'];
    $snowpilot_Location->appendChild($nstype);
    $ewtype = $snowpilot_xmldoc->createAttribute('ew');
    $ewtype->value = $unit_prefs['longType'];
    $snowpilot_Location->appendChild($ewtype);
    //
    //  East and North values for utm coordtype
    //
    $location_east = $snowpilot_xmldoc->createAttribute('east');
    $location_east->value = $unit_prefs['field_east'];
    $snowpilot_Location->appendChild($location_east);
    $location_north = $snowpilot_xmldoc->createAttribute('north');
    $location_north->value = $unit_prefs['field_north'];
    $snowpilot_Location->appendChild($location_north);
    //
    // Latitude
    $latitude = $snowpilot_xmldoc->createAttribute('lat');
    $latitude->value = $unit_prefs['field_latitude'];
    $snowpilot_Location->appendChild($latitude);
    //
    // Longitude
    $longitude = $snowpilot_xmldoc->createAttribute('longitude');
    $longitude->value = $unit_prefs['field_longitude'];
    $snowpilot_Location->appendChild($longitude);
    //
    // Elevation
    $elevation = $snowpilot_xmldoc->createAttribute('elv');
    $elevation->value = isset($node->field_elevation['und'][0]['value']) ? $node->field_elevation['und'][0]['value'] : '';
    $snowpilot_Location->appendChild($elevation);
    //
    // State
    $location_state = $snowpilot_xmldoc->createAttribute('state');
    $location_state->value = $unit_prefs['state'];
    $snowpilot_Location->appendChild($location_state);
    //
    // Range
    $location_range = $snowpilot_xmldoc->createAttribute('range');
    $location_range->value = $unit_prefs['range'];
    $snowpilot_Location->appendChild($location_range);
    //
    // Name
    $location_name = $snowpilot_xmldoc->createAttribute('name');
    $location_name->value = $node->title;
    $snowpilot_Location->appendChild($location_name);
    //
    $counter = 1;
    foreach ($all_layers as $x => $layer) {
        $snowpilot_Layer = $snowpilot_xmldoc->createElement("Layer");
        // grain size units
        $gsu1 = $snowpilot_xmldoc->createAttribute('grainSizeUnits1');
        $gsu2 = $snowpilot_xmldoc->createAttribute('grainSizeUnits2');
        $gsu2->value = $gsu1->value = 'mm';
        $snowpilot_Layer->appendChild($gsu1);
        $snowpilot_Layer->appendChild($gsu2);
        //
        //  grain size
        $gs1 = $snowpilot_xmldoc->createAttribute('grainSize');
        $gs2 = $snowpilot_xmldoc->createAttribute('grainSize1');
        $gs1->value = isset($layer->field_grain_size['und'][0]['value']) ? $layer->field_grain_size['und'][0]['value'] : '';
        $gs2->value = isset($layer->field_grain_size_max['und'][0]['value']) ? $layer->field_grain_size_max['und'][0]['value'] : '';
        $snowpilot_Layer->appendChild($gs1);
        $snowpilot_Layer->appendChild($gs2);
        //
        // grain type
        $gt1 = $snowpilot_xmldoc->createAttribute('grainType');
        $gt2 = $snowpilot_xmldoc->createAttribute('grainType1');
        $gt1->value = isset($layer->field_grain_type['und'][0]['tid']) ? htmlentities(taxonomy_term_load($layer->field_grain_type['und'][0]['tid'])->name) : '';
        $gt2->value = isset($layer->field_grain_type_secondary['und'][0]['tid']) ? htmlentities(taxonomy_term_load($layer->field_grain_type_secondary['und'][0]['tid'])->name) : '';
        $snowpilot_Layer->appendChild($gt1);
        $snowpilot_Layer->appendChild($gt2);
        //
        // hardness
        $hness1 = $snowpilot_xmldoc->createAttribute('hardness1');
        $hness2 = $snowpilot_xmldoc->createAttribute('hardness2');
        $hness1->value = isset($layer->field_hardness['und'][0]['value']) ? $layer->field_hardness['und'][0]['value'] : '';
        $hness2->value = isset($layer->field_hardness2['und'][0]['value']) ? $layer->field_hardness2['und'][0]['value'] : '';
        $snowpilot_Layer->appendChild($hness1);
        $snowpilot_Layer->appendChild($hness2);
        //
        // LayerNumber
        $layer_num = $snowpilot_xmldoc->createAttribute('layerNumber');
        $layer_num->value = $counter;
        $snowpilot_Layer->appendChild($layer_num);
        //
        // water content
        $waterContent = $snowpilot_xmldoc->createAttribute('waterContent');
        $waterContent->value = isset($layer->field_water_content['und'][0]['value']) ? $layer->field_water_content['und'][0]['value'] : '';
        $snowpilot_Layer->appendChild($waterContent);
        //
        //startDepth
        $startDepth = $snowpilot_xmldoc->createAttribute('startDepth');
        $startDepth->value = isset($layer->field_height['und'][0]['value']) ? $layer->field_height['und'][0]['value'] : '';
        $snowpilot_Layer->appendChild($startDepth);
        //
        //endDepth
        $endDepth = $snowpilot_xmldoc->createAttribute('endDepth');
        $endDepth->value = isset($layer->field_bottom_depth['und'][0]['value']) ? $layer->field_bottom_depth['und'][0]['value'] : '';
        $snowpilot_Layer->appendChild($endDepth);
        //
        // multiples ...
        // We make a little array and loop through it so this is easier.
        $multiples = array('multipleHardness' => 'field_use_multiple_hardnesses', 'multipleDensity' => 'field_use_multiple_density', 'multipleGrainType' => 'field_use_multiple_grain_type', 'multipleGrainSize' => 'field_use_multiple_grain_size');
        foreach ($multiples as $key => $multiple) {
            $multi_val[$multiple] = $snowpilot_xmldoc->createAttribute($key);
            $layer_multiple = $layer->{$multiple};
            //dsm($layer_multiple['und']);
            $multi_val[$multiple]->value = isset($layer_multiple['und'][0]['value']) && $layer_multiple['und'][0]['value'] == 1 ? 'true' : 'false';
            $snowpilot_Layer->appendChild($multi_val[$multiple]);
        }
        $snowpilot_PitCore->appendChild($snowpilot_Layer);
        //
        $counter++;
    }
    $ids = array();
    foreach ($node->field_test['und'] as $test) {
        $ids[] = $test['value'];
    }
    $shear_tests = field_collection_item_load_multiple($ids);
    foreach ($shear_tests as $shear_test) {
        $snowpilot_ShearTest = $snowpilot_xmldoc->createElement("Shear_Test_Result");
        //
        // code
        $test_code = $snowpilot_xmldoc->createAttribute('code');
        $test_code->value = $shear_test->field_stability_test_type['und'][0]['value'];
        $snowpilot_ShearTest->appendChild($test_code);
        //
        // sdepth
        $sdepth = $snowpilot_xmldoc->createAttribute('sdepth');
        $sdepth->value = isset($shear_test->field_depth['und'][0]['value']) ? $shear_test->field_depth['und'][0]['value'] : '';
        $snowpilot_ShearTest->appendChild($sdepth);
        //
        //
        //depthUnits
        $depthUnits = $snowpilot_xmldoc->createAttribute('depthUnits');
        $depthUnits->value = $unit_prefs['depthUnits'];
        $snowpilot_ShearTest->appendChild($depthUnits);
        //
        // score
        $test_score = $snowpilot_xmldoc->createAttribute('score');
        $test_score->value = isset($shear_test->field_stability_test_score['und'][0]['value']) ? $shear_test->field_stability_test_score['und'][0]['value'] : '';
        $snowpilot_ShearTest->appendChild($test_score);
        //
        // ecScore
        $ecScore = $snowpilot_xmldoc->createAttribute('ecScore');
        $ecScore->value = isset($shear_test->field_ec_score['und'][0]['value']) ? $shear_test->field_ec_score['und'][0]['value'] : '';
        $snowpilot_ShearTest->appendChild($ecScore);
        //
        // quality
        $shear_quality = $snowpilot_xmldoc->createAttribute('quality');
        $shear_quality->value = isset($shear_test->field_shear_quality['und'][0]['value']) ? $shear_test->field_shear_quality['und'][0]['value'] : '';
        $snowpilot_ShearTest->appendChild($shear_quality);
        //
        // dateSTring
        $dateString = $snowpilot_xmldoc->createAttribute('dateString');
        $dateString->value = isset($node->field_date_time['und'][0]['value']) ? date('m/d/Y', strtotime($node->field_date_time['und'][0]['value'])) : '';
        $snowpilot_ShearTest->appendChild($dateString);
        //
        // numberOfTaps
        $numTaps = $snowpilot_xmldoc->createAttribute('numberOfTaps');
        if ($shear_test->field_stability_test_type['und'][0]['value'] == 'ECT') {
            $numTaps->value = $ecScore->value;
        } elseif ($shear_test->field_stability_test_type['und'][0]['value'] == 'CT') {
            $numTaps->value = isset($shear_test->field_ct_score['und'][0]['value']) ? $shear_test->field_ct_score['und'][0]['value'] : '';
        } else {
            $numTaps->value = '';
        }
        $snowpilot_ShearTest->appendChild($numTaps);
        // fractureCat
        $fractureCat = $snowpilot_xmldoc->createAttribute('fractureCat');
        $fractureCat->value = $unit_prefs['fractureCat'];
        $snowpilot_ShearTest->appendChild($fractureCat);
        //
        // fractureCharacter
        $test_character = $snowpilot_xmldoc->createAttribute('character');
        $test_character->value = $unit_prefs['fractureCat'] == 'fracture_character' && isset($shear_test->field_fracture_character['und'][0]['value']) ? $shear_test->field_fracture_character['und'][0]['value'] : '';
        $snowpilot_ShearTest->appendChild($test_character);
        //
        // comments
        $comments = $snowpilot_xmldoc->createAttribute('comments');
        $comments->value = isset($shear_test->field_stability_comments['und'][0]['value']) ? $shear_test->field_stability_comments['und'][0]['value'] : '';
        // s="ECTP Q1 5 11/30/2014.15:39:6"
        //
        //s
        $date_part = date('m/d/Y.H:i:s:0', strtotime($node->field_date_time['und'][0]['value']));
        $test_s = $snowpilot_xmldoc->createAttribute('s');
        $test_s->value = $test_score->value . ' ' . $shear_quality->value . $test_character->value . ' ' . $sdepth->value . ' ' . $date_part;
        $snowpilot_ShearTest->appendChild($test_s);
        //
        // lengthOfCut
        $lengthOfCut = $snowpilot_xmldoc->createAttribute('lengthOfCut');
        $lengthOfCut->value = isset($shear_test->field_length_of_saw_cut['und'][0]['value']) ? $shear_test->field_length_of_saw_cut['und'][0]['value'] : '';
        $snowpilot_ShearTest->appendChild($lengthOfCut);
        //
        // lengthOfColumn
        $lengthOfColumn = $snowpilot_xmldoc->createAttribute('lengthOfColumn');
        $lengthOfColumn->value = isset($shear_test->field_length_of_isolated_col_pst['und'][0]['value']) ? $shear_test->field_length_of_isolated_col_pst['und'][0]['value'] : '';
        $snowpilot_ShearTest->appendChild($lengthOfColumn);
        //
        // releaseType
        $releaseType = $snowpilot_xmldoc->createAttribute('releaseType');
        $releaseType->value = $shear_test->field_stability_test_type['und'][0]['value'] == 'RB' && isset($shear_test->field_release_type['und'][0]['value']) ? $shear_test->field_release_type['und'][0]['value'] : '';
        $snowpilot_ShearTest->appendChild($releaseType);
        //
        // dataCode
        // this is not actually anywhere in the snowpilot data model specs, but needs to be.
        $dataCode = $snowpilot_xmldoc->createAttribute('dataCode');
        $dataCode->value = $shear_test->field_stability_test_type['und'][0]['value'] == 'PST' && isset($shear_test->field_data_code_pst['und'][0]['value']) ? $shear_test->field_data_code_pst['und'][0]['value'] : '';
        $snowpilot_ShearTest->appendChild($dataCode);
        $snowpilot_PitCore->appendChild($snowpilot_ShearTest);
    }
    $ids = array();
    $profile = array();
    //dsm($node->field_density_profile);
    if (isset($node->field_density_profile['und']) && count($node->field_density_profile['und']) > 0) {
        foreach ($node->field_density_profile['und'] as $density) {
            $ids[] = $density['value'];
        }
        $densitys = field_collection_item_load_multiple($ids);
        foreach ($densitys as $density) {
            $profile[] = $density->field_depth['und'][0]['value'] . '_' . $density->field_density_top['und'][0]['value'];
        }
    }
    $snowpilot_Density = $snowpilot_xmldoc->createElement('Density_Profile');
    //
    // profile
    $density_prof = $snowpilot_xmldoc->createAttribute('profile');
    $density_prof->value = implode('?', $profile);
    $snowpilot_Density->appendChild($density_prof);
    //
    // depthUnits
    $depthUnits = $snowpilot_xmldoc->createAttribute('depthUnits');
    $depthUnits->value = $unit_prefs['depthUnits'];
    $snowpilot_Density->appendChild($depthUnits);
    //
    //densityUnits
    $densityUnits = $snowpilot_xmldoc->createAttribute('densityUnits');
    $densityUnits->value = _density_unit_fix($unit_prefs['rhoUnits']);
    $snowpilot_Density->appendChild($densityUnits);
    $snowpilot_PitCore->appendChild($snowpilot_Density);
    $outXML = $snowpilot_xmldoc->saveXML();
    $formatted_xml = new DOMDocument('1.0', 'UTF-8');
    $formatted_xml->preserveWhiteSpace = false;
    $formatted_xml->formatOutput = true;
    $formatted_xml->loadXML($outXML);
    $final_xml = $formatted_xml->saveXML();
    //dsm($final_xml);
    return $final_xml;
}
function snowpilot_snowpit_graph_header_write($node, $format = 'jpg')
{
    // also add user account info to this:
    $user_account = user_load($node->uid);
    $snowpit_unit_prefs = snowpilot_unit_prefs_get($node, 'node');
    $pit_depth = _snowpilot_find_pit_depth($node);
    // Image Variables
    $width = 994;
    $height = 840;
    //imageloadfont()
    // Create GD Image
    $img = imagecreatetruecolor($width, $height);
    // Assign some colors
    $black = imagecolorallocate($img, 0, 0, 0);
    $white = imagecolorallocate($img, 255, 255, 255);
    $purple_layer = imagecolorallocate($img, 154, 153, 213);
    $red_layer = imagecolorallocate($img, 178, 36, 35);
    $blue_outline = imagecolorallocate($img, 15, 8, 166);
    $pink_problem = imagecolorallocate($img, 254, 240, 240);
    // Set background color to white
    imagefill($img, 0, 0, $white);
    $label_font = '/sites/all/libraries/fonts/Arial.ttf';
    $value_font = '/sites/all/libraries/fonts/Arial Bold.ttf';
    $snowsymbols_font = '/sites/all/libraries/fonts/ArialMT28.ttf';
    // Label Y axis and draw horizontal lines
    imagettftext($img, 11, 0, 14, 17, $black, $value_font, $node->title);
    // Location information
    if (isset($node->field_loaction['und'][0]['tid'])) {
        $term_obj_region = taxonomy_term_load($node->field_loaction['und'][0]['tid']);
        imagettftext($img, 11, 0, 14, 53, $black, $value_font, $term_obj_region->name);
        if (isset($node->field_loaction['und'][1]['tid'])) {
            $term_obj_region = taxonomy_term_load($node->field_loaction['und'][1]['tid']);
            imagettftext($img, 11, 0, 14, 35, $black, $value_font, $term_obj_region->name);
        }
    }
    $text_pos = imagettftext($img, 11, 0, 14, 71, $black, $label_font, 'Elevation: ');
    if (isset($node->field_elevation['und'])) {
        imagettftext($img, 11, 0, $text_pos[2], 71, $black, $value_font, $node->field_elevation['und'][0]['value'] . ' ' . $node->field_elevation_units['und'][0]['value']);
    }
    $text_pos = imagettftext($img, 11, 0, 14, 89, $black, $label_font, 'Aspect: ');
    if (isset($node->field_aspect['und'])) {
        $aspect = field_view_field('node', $node, 'field_aspect');
        imagettftext($img, 11, 0, $text_pos[2], 89, $black, $value_font, $aspect[0]['#markup']);
    }
    $text_pos = imagettftext($img, 11, 0, 14, 107, $black, $label_font, 'Specifics: ');
    $specifics = _generate_specifics_string($node);
    imagettftext($img, 9, 0, $text_pos[2], 107, $black, $value_font, $specifics);
    // Observer
    imagettftext($img, 11, 0, 183, 17, $black, $value_font, $user_account->field_first_name['und'][0]['value'] . " " . $user_account->field_last_name['und'][0]['value']);
    imagettftext($img, 11, 0, 183, 35, $black, $value_font, date('D M j H:i Y (T) ', strtotime($node->field_date_time['und'][0]['value'] . " " . $node->field_date_time['und'][0]['timezone_db'])));
    //Date / Time of observation
    $text_pos = imagettftext($img, 11, 0, 183, 53, $black, $label_font, "Co-ord: ");
    if ($snowpit_unit_prefs['field_coordinate_type'] != 'UTM') {
        if (isset($node->field_latitude['und']) && isset($node->field_longitude['und'])) {
            imagettftext($img, 11, 0, $text_pos[2], 53, $black, $value_font, number_format($node->field_latitude['und'][0]['value'], 5) . $node->field_latitude_type['und'][0]['value'] . ", " . number_format($node->field_longitude['und'][0]['value'], 5) . $node->field_longitude_type['und'][0]['value']);
        }
    } else {
        // Not Lat long, their preference is UTM
        if (isset($node->field_east['und']) && isset($node->field_north['und'])) {
            imagettftext($img, 11, 0, $text_pos[2], 53, $black, $value_font, $node->field_utm_zone['und'][0]['value'] . ' ' . $node->field_east['und'][0]['value'] . $node->field_longitude_type['und'][0]['value'] . ' ' . $node->field_north['und'][0]['value'] . $node->field_latitude_type['und'][0]['value']);
        }
    }
    $text_pos = imagettftext($img, 11, 0, 183, 71, $black, $label_font, "Slope Angle: ");
    if (isset($node->field_slope_angle['und'])) {
        $slope_angle = field_view_field('node', $node, 'field_slope_angle');
        imagettftext($img, 11, 0, $text_pos[2], 71, $black, $value_font, $slope_angle[0]['#markup']);
    }
    $text_pos = imagettftext($img, 11, 0, 183, 89, $black, $label_font, "Wind Loading: ");
    if (isset($node->field_wind_loading['und'])) {
        imagettftext($img, 11, 0, $text_pos[2], 89, $black, $value_font, $node->field_wind_loading['und'][0]['value']);
    }
    $text_pos = imagettftext($img, 11, 0, 429, 17, $black, $label_font, "Stability: ");
    if (isset($node->field_stability_on_similar_slope['und'])) {
        $similar_stability = field_view_field('node', $node, 'field_stability_on_similar_slope');
        imagettftext($img, 11, 0, $text_pos[2], 17, $black, $value_font, $similar_stability[0]['#markup']);
    }
    $text_pos = imagettftext($img, 11, 0, 429, 35, $black, $label_font, "Air Temperature: ");
    if (isset($node->field_air_temp['und'])) {
        $air_temp = field_view_field('node', $node, 'field_air_temp');
        imagettftext($img, 11, 0, $text_pos[2], 35, $black, $value_font, $air_temp[0]['#markup'] . "°" . $snowpit_unit_prefs['field_temp_units']);
    }
    $text_pos = imagettftext($img, 11, 0, 429, 53, $black, $label_font, "Sky Cover: ");
    if (isset($node->field_sky_cover['und'])) {
        $sky_cover = field_view_field('node', $node, 'field_sky_cover');
        imagettftext($img, 11, 0, $text_pos[2], 53, $black, $value_font, html_entity_decode($sky_cover[0]['#markup']));
    }
    $text_pos = imagettftext($img, 11, 0, 429, 71, $black, $label_font, "Precipitation: ");
    if (isset($node->field_precipitation['und'])) {
        $precipitation = field_view_field('node', $node, 'field_precipitation');
        imagettftext($img, 11, 0, $text_pos[2], 71, $black, $value_font, $precipitation[0]['#markup']);
    }
    $text_pos = imagettftext($img, 11, 0, 429, 89, $black, $label_font, "Wind: ");
    if (isset($node->field_wind_direction['und'][0]['value'])) {
        $text_pos = imagettftext($img, 11, 0, $text_pos[2] + 4, 89, $black, $value_font, snowpilot_cardinal_wind_dir($node->field_wind_direction['und'][0]['value']));
    }
    if (isset($node->field_wind_speed['und'][0]['value'])) {
        $wind_speed = field_view_field('node', $node, 'field_wind_speed');
        imagettftext($img, 11, 0, $text_pos[2], 89, $black, $value_font, " " . $wind_speed[0]['#markup']);
    }
    imagettftext($img, 11, 0, 805, 17, $black, $label_font, 'Layer Notes');
    $textpos = imagettftext($img, 11, 0, 14, 779, $black, $label_font, 'Notes: ');
    if (isset($node->body['und'][0]) && $node->body['und'][0]['safe_value'] != '') {
        $notes_lines = _output_formatted_notes($node->body['und'][0]['safe_value'], $value_font);
        foreach ($notes_lines as $x => $line) {
            if ($x <= 3) {
                imagettftext($img, 9, 0, $textpos[2], 779 + $x * 19, $black, $value_font, $line);
            } else {
                imagettftext($img, 9, 0, 870, 779 + 3 * 19, $red_layer, $value_font, "[ ... more notes ]");
                break;
            }
        }
    }
    //  write stability tests column and comments
    //  TODO : expand into its own function
    $comment_count = 0;
    $textpos = array();
    if (isset($node->field_total_height_of_snowpack['und'][0]['value'])) {
        $textpos = imagettftext($img, 9, 0, 645, 17, $black, $value_font, 'HS' . $node->field_total_height_of_snowpack['und'][0]['value']);
        $comment_count = 1;
    }
    if (isset($node->field_surface_penetration['und']) && $node->field_surface_penetration['und'][0]['value'] == 'boot' && isset($node->field_boot_penetration_depth['und']) && $node->field_boot_penetration_depth['und'][0]['value'] != '') {
        $xpos = count($textpos) ? $textpos[2] + 5 : 645;
        imagettftext($img, 9, 0, $xpos, 17, $black, $value_font, 'PF' . $node->field_boot_penetration_depth['und'][0]['value']);
        $comment_count = 1;
    } elseif (isset($node->field_surface_penetration['und']) && isset($node->field_ski_penetration['und'][0]['value']) && $node->field_surface_penetration['und'][0]['value'] == 'ski' && $node->field_ski_penetration['und'][0]['value'] != '') {
        $xpos = count($textpos) ? $textpos[2] + 5 : 645;
        imagettftext($img, 9, 0, $xpos, 17, $black, $value_font, 'SP' . $node->field_ski_penetration['und'][0]['value']);
        $comment_count = 1;
    }
    if (isset($node->field_test['und'])) {
        $ids = array();
        foreach ($node->field_test['und'] as $test) {
            $ids[] = $test['value'];
        }
        $test_results = field_collection_item_load_multiple($ids);
        // Here we go ahead and set a value for no-release type test results: ECTX, CTN, etc
        foreach ($test_results as $test) {
            if (!isset($test->field_depth['und'][0]['value'])) {
                $test->field_depth['und'][0]['value'] = $snowpit_unit_prefs['field_depth_0_from'] == 'top' ? $pit_depth : 0;
            }
        }
        uasort($test_results, 'depth_val');
        //
        // reversing the order of the test results makes it work when outputting the Stability test results on the graph when measuring from top
        if ($snowpit_unit_prefs['field_depth_0_from'] == 'top') {
            $test_results = array_reverse($test_results);
        }
        $bak = _set_stability_test_pixel_depths($test_results, $pit_depth, $snowpit_unit_prefs['field_depth_0_from']);
        // this sets a $test->y_position = integer which is where the line and text should go in the column on the right
        imagettftext($img, 11, 0, 645, $comment_count * 18 + 17, $black, $label_font, 'Stability Test Notes');
        foreach ($test_results as $x => $test) {
            if (isset($test->field_stability_test_type['und'][0]['value']) && isset($test->y_position)) {
                if (isset($test->y_position)) {
                    // if this has been 'multipled' with another stb test, the y_position won't be set
                    imageline($img, 707, $test->y_position, 941, $test->y_position, $black);
                    imagettftext($img, 9, 0, 712, $test->y_position - 5, $black, $label_font, stability_test_score_shorthand($test, $snowpit_unit_prefs));
                }
                if (count($test->field_stability_comments)) {
                    if ($comment_count < 5) {
                        $test_depth = isset($test->field_depth['und'][0]['value']) ? $test->field_depth['und'][0]['value'] + 0 : 0;
                        imagettftext($img, 9, 0, 645, $comment_count * 13 + 35, $black, $value_font, $test_depth . ': ' . $test->field_stability_comments['und'][0]['safe_value']);
                        $comment_count++;
                    } else {
                        imagettftext($img, 7, 0, 645, $comment_count * 13 + 31, $red_layer, $label_font, '[ More Stability Test Notes ... ]');
                    }
                }
            }
        }
    }
    // end stability test column
    // write rho column info
    //
    if (isset($node->field_density_profile['und'])) {
        foreach ($node->field_density_profile['und'] as $x => $density_item) {
            $density = field_collection_item_load($density_item['value']);
            // this use of imageline will need to be updated to include some kind of cluster management
            imageline($img, 667, snowpit_graph_pixel_depth($density->field_depth['und'][0]['value'], $pit_depth, $snowpit_unit_prefs['field_depth_0_from']), 707, snowpit_graph_pixel_depth($density->field_depth['und'][0]['value'], $pit_depth, $snowpit_unit_prefs['field_depth_0_from']), $black);
            imagettftext($img, 8, 0, 671, snowpit_graph_pixel_depth($density->field_depth['und'][0]['value'], $pit_depth, $snowpit_unit_prefs['field_depth_0_from']) + 12, $black, $label_font, $density->field_density_top['und'][0]['value']);
        }
    }
    //
    //  Prep for the 2 Cycles through layers
    //
    if (isset($node->field_layer['und'])) {
        $ids = array();
        foreach ($node->field_layer['und'] as $lay) {
            $ids[] = $lay['value'];
        }
        $all_layers = field_collection_item_load_multiple($ids);
        foreach ($all_layers as $x => $layer) {
            if ($snowpit_unit_prefs['field_depth_0_from'] == 'top') {
                $layer->y_val_top = $y_val_top = round(snowpit_graph_pixel_depth($layer->field_bottom_depth['und'][0]['value'], $pit_depth, $snowpit_unit_prefs['field_depth_0_from']));
                $layer->y_val = $y_val = round(snowpit_graph_pixel_depth($layer->field_height['und'][0]['value'], $pit_depth, $snowpit_unit_prefs['field_depth_0_from']));
            } else {
                $layer->y_val = $y_val = round(snowpit_graph_pixel_depth($layer->field_bottom_depth['und'][0]['value'], $pit_depth, $snowpit_unit_prefs['field_depth_0_from']));
                $layer->y_val_top = $y_val_top = round(snowpit_graph_pixel_depth($layer->field_height['und'][0]['value'], $pit_depth, $snowpit_unit_prefs['field_depth_0_from']));
            }
        }
        $keyed_all_layers = $all_layers;
        snowpilot_layers_density_xlate($keyed_all_layers, $snowpit_unit_prefs);
        // this solo line goes across the top of the top layer. Could be programmed later if we decide to include the 'headspace' above the top of the pit
        imageline($img, 483, $keyed_all_layers[0]->y_val_top, 667, $keyed_all_layers[0]->y_val_top, $black);
        ///
        // IN this loop, we set the items in the 'density managed' column - grain types, sizes, moisture, etc.
        //
        $comment_counter = 0;
        foreach ($keyed_all_layers as $x => $layer) {
            imageline($img, 511, $layer->y_val_xlate, 667, $layer->y_val_xlate, $black);
            // 'density managed' column - grain types, sizes, moisture, etc.
            imageline($img, 483, $layer->y_val, 491, $layer->y_val, $black);
            // a little tick to start outthe angle transferred stuff
            imageline($img, 491, $layer->y_val, 511, $layer->y_val_xlate, $black);
            // the diagonal line connect
            // Calculate grain type image(s) for this layer
            $grain_type_image = '';
            if (isset($layer->field_grain_type['und'])) {
                $grain_type_image = isset($layer->field_grain_type['und'][1]['tid']) ? _tid2snowsymbols($layer->field_grain_type['und'][1]['tid']) : _tid2snowsymbols($layer->field_grain_type['und'][0]['tid']);
            }
            $secondary_grain_type = '';
            if (isset($layer->field_grain_type_secondary['und'])) {
                $secondary_grain_type_image = isset($layer->field_grain_type_secondary['und'][1]['tid']) ? _tid2snowsymbols($layer->field_grain_type_secondary['und'][1]['tid']) : _tid2snowsymbols($layer->field_grain_type_secondary['und'][0]['tid']);
                $secondary_grain_type = ' (' . $secondary_grain_type_image . ')';
            }
            //output grain symbols
            imagettftext($img, 10, 0, 525, ($layer->y_val_xlate - $layer->y_val_top_xlate) / 2 + $layer->y_val_top_xlate + 5, $black, $snowsymbols_font, $grain_type_image . $secondary_grain_type);
            // calculate grain size string
            $grain_size_string = isset($layer->field_grain_size['und']) ? $layer->field_grain_size['und'][0]['value'] : '';
            if ($layer->field_use_multiple_grain_size['und'][0]['value'] == '1' && isset($layer->field_grain_size_max['und'][0]['value'])) {
                $grain_size_string .= ' - ' . $layer->field_grain_size_max['und'][0]['value'];
            }
            // Ouptut grain sizes
            $textpos = imagettftext($img, 10, 0, 584, ($layer->y_val_xlate - $layer->y_val_top_xlate) / 2 + $layer->y_val_top_xlate + 5, $black, $label_font, $grain_size_string);
            // calculate & output layer moisture
            if (isset($layer->field_water_content['und'])) {
                $moisture = $layer->field_water_content['und'][0]['value'];
                imagettftext($img, 10, 0, $textpos[2] + 5, ($layer->y_val_xlate - $layer->y_val_top_xlate) / 2 + $layer->y_val_top_xlate + 5, $black, $label_font, $moisture);
            }
            // Output Layer comments
            $layer_bottom = $layer->field_bottom_depth['und'][0]['value'] + 0;
            $layer_top = $layer->field_height['und'][0]['value'] + 0;
            if (isset($layer->field_comments['und'])) {
                if ($comment_counter < 5) {
                    imagettftext($img, 9, 0, 805, $comment_counter * 13 + 35, $black, $value_font, $layer_bottom . '-' . $layer_top . ': ' . $layer->field_comments['und'][0]['safe_value']);
                    $comment_counter++;
                } else {
                    imagettftext($img, 7, 0, 805, $comment_counter * 13 + 31, $red_layer, $label_font, '[ More Layer Comments ... ]');
                }
            }
            // write density measurements that are from the 'Layers' tab into the rho column ( in addition to Densities )
            if (isset($layer->field_density_top['und'][0]['value'])) {
                imageline($img, 667, snowpit_graph_pixel_depth($layer->field_height['und'][0]['value'], $pit_depth, $snowpit_unit_prefs['field_depth_0_from']), 707, snowpit_graph_pixel_depth($layer->field_height['und'][0]['value'], $pit_depth, $snowpit_unit_prefs['field_depth_0_from']), $black);
                imagettftext($img, 8, 0, 669, snowpit_graph_pixel_depth($layer->field_height['und'][0]['value'], $pit_depth, $snowpit_unit_prefs['field_depth_0_from']) - 5, $black, $label_font, $layer->field_density_top['und'][0]['value']);
            }
            snowpilot_draw_layer_polygon($img, $layer, $purple_layer, TRUE, $snowpit_unit_prefs['hardnessScaling']);
            // the fill
            snowpilot_draw_layer_polygon($img, $layer, $blue_outline, FALSE, $snowpit_unit_prefs['hardnessScaling']);
            // the outline
            // this mark the layer if its a critical layer, and save some
            if ($layer->field_this_is_my_layer_of_greate['und'][0]['value'] == '1') {
                $x_redline = _h2pix($layer->field_hardness['und'][0]['value'], FALSE, $snowpit_unit_prefs['hardnessScaling']);
                $x_redline_bottom = _h2pix($layer->field_hardness['und'][0]['value'], FALSE, $snowpit_unit_prefs['hardnessScaling']);
                if (isset($layer->field_hardness2['und'][0]['value'])) {
                    $x_redline_bottom = _h2pix($layer->field_hardness2['und'][0]['value'], FALSE, $snowpit_unit_prefs['hardnessScaling']);
                }
                $y_redline_top = $layer->y_val_top;
                $y_redline_bottom = $layer->y_val;
                ///
                $concern_delta = $layer->item_id;
                if ($comment_counter < 5) {
                    imagettftext($img, 9, 0, 805, $comment_counter * 13 + 35, $black, $value_font, $layer_bottom . '-' . $layer_top . ": Problematic layer");
                    $comment_counter++;
                } elseif ($comment_counter == 5) {
                    imagettftext($img, 7, 0, 805, $comment_counter * 13 + 31, $red_layer, $label_font, '[ More Layer Comments ... ]');
                }
                $comment_counter++;
            }
        }
    }
    // now that we are done drawing all the layers, we can overprint the red layer of concern
    if (isset($concern_delta)) {
        $layer_part = isset($all_layers[$concern_delta]->field_concern['und'][0]['value']) ? $all_layers[$concern_delta]->field_concern['und'][0]['value'] : 'entire layer';
        switch ($layer_part) {
            case 'entire layer':
                //full-on red layer was too much; withdrawn for now; in favor of perhaps diagonal lines of red indicating layer of concern ( all layer ) in future
                //
                break;
            case 'top':
                imageline($img, $x_redline, $y_redline_top + 2, 446, $y_redline_top + 2, $red_layer);
                imageline($img, $x_redline, $y_redline_top + 1, 446, $y_redline_top + 1, $red_layer);
                break;
            case 'bottom':
                imageline($img, $x_redline_bottom, $y_redline_bottom - 2, 446, $y_redline_bottom - 2, $red_layer);
                imageline($img, $x_redline_bottom, $y_redline_bottom - 1, 446, $y_redline_bottom - 1, $red_layer);
                break;
        }
    }
    // Temperature Profile:
    // If we have temp profile readings,then we'll make the tick marks
    if (isset($node->field_temp_collection['und'])) {
        $ids = array();
        foreach ($node->field_temp_collection['und'] as $temp) {
            $ids[] = $temp['value'];
        }
        $all_temps = field_collection_item_load_multiple($ids);
        uasort($all_temps, 'depth_val');
        $min_temp = $snowpit_unit_prefs['field_temp_units'] == 'F' ? 12 : -8;
        $min_temp = _temp_profile_find_min_temp($all_temps, $min_temp) - 2;
        if ($snowpit_unit_prefs['field_temp_units'] == 'C') {
            $pixels_per_degree = 433 / $min_temp;
            $increment = $min_temp < -14 ? 2 : 1;
            $x = 0;
            while ($x >= $min_temp) {
                //  tickmarks
                imageline($img, 447 - $pixels_per_degree * $x, 132, 447 - $pixels_per_degree * $x, 140, $black);
                imagettftext($img, 9, 0, 441 - $pixels_per_degree * $x, 130, $black, $label_font, $x);
                $x = $x - $increment;
            }
        } else {
            /// Temperature units = 'F'
            $pixels_per_degree = 433 / $min_temp;
            $increment = $min_temp < 5 ? 2 : 1;
            $x = 32;
            while ($x >= $min_temp) {
                // tickmarks
                imageline($img, 447 - $pixels_per_degree * ($x - 32), 132, 447 - $pixels_per_degree * ($x - 32), 140, $black);
                imagettftext($img, 9, 0, 441 - $pixels_per_degree * ($x - 32), 130, $black, $label_font, $x);
                $x = $x - $increment;
            }
        }
        // end temp units toggle
        // draw points, and line, different $cx calculations for F or C
        $prev_x = 0;
        $prev_y = 0;
        foreach ($all_temps as $x => $temp) {
            $cx = $snowpit_unit_prefs['field_temp_units'] == 'C' ? 447 - $pixels_per_degree * $temp->field_temp_temp['und'][0]['value'] : 447 - $pixels_per_degree * ($temp->field_temp_temp['und'][0]['value'] - 32);
            //dsm($cx);
            if ($cx >= 14 && $cx <= 447) {
                // draw point
                imagefilledellipse($img, $cx, snowpit_graph_pixel_depth($temp->field_depth['und'][0]['value'], $pit_depth, $snowpit_unit_prefs['field_depth_0_from']), 6, 6, $red_layer);
                // draw line
                if ($prev_x <= 447 && $prev_x >= 14 && $prev_y) {
                    imageline($img, $cx, snowpit_graph_pixel_depth($temp->field_depth['und'][0]['value'], $pit_depth, $snowpit_unit_prefs['field_depth_0_from']), $prev_x, $prev_y, $red_layer);
                }
            }
            // save this point location to use to draw the next line
            $prev_x = $cx;
            $prev_y = snowpit_graph_pixel_depth($temp->field_depth['und'][0]['value'], $pit_depth, $snowpit_unit_prefs['field_depth_0_from']);
        }
    }
    // end of drawing the temperature profile
    // cycle through and make depth tick marks
    $x = 0;
    while ($x <= $pit_depth) {
        $y_val = round(snowpit_graph_pixel_depth($x, $pit_depth, $snowpit_unit_prefs['field_depth_0_from']));
        imageline($img, 660, $y_val, 667, $y_val, $black);
        imageline($img, 511, $y_val, 518, $y_val, $black);
        imageline($img, 14, $y_val, 22, $y_val, $black);
        imageline($img, 440, $y_val, 447, $y_val, $black);
        imagettftext($img, 10, 0, 456, $y_val + 5, $black, $label_font, $x);
        $x += 10;
    }
    // Now we make the 5cm tick marks
    $x = 5;
    while ($x <= $pit_depth) {
        $y_val = round(snowpit_graph_pixel_depth($x, $pit_depth, $snowpit_unit_prefs['field_depth_0_from']));
        imageline($img, 664, $y_val, 667, $y_val, $black);
        imageline($img, 511, $y_val, 515, $y_val, $black);
        imageline($img, 14, $y_val, 18, $y_val, $black);
        imageline($img, 443, $y_val, 447, $y_val, $black);
        //imagettftext($img, 10, 0, 638, round(snowpit_graph_pixel_depth($x, $node, 'bottom'))+5, $black, $label_font, $x );
        $x += 10;
    }
    //
    imagettftext($img, 10, 0, 742, 122, $black, $label_font, "Stability tests");
    imagettftext($img, 10, 0, 681, 118, $black, $label_font, "&#x3c1;");
    // Rho symbol for density
    imagettftext($img, 10, 0, 675, 135, $black, $label_font, _density_unit_fix($snowpit_unit_prefs['field_density_units']));
    // the rectabngle around stability and density columns
    imagerectangle($img, 667, 140, 941, 751, $black);
    // the rectangle around the layers hardness profile
    imagerectangle($img, 14, 140, 447, 751, $black);
    //the tickmarks for hardness across the bottom and top, and labels
    foreach (_h2pix(NULL, TRUE, $snowpit_unit_prefs['hardnessScaling']) as $hardness => $pixels) {
        if (substr($hardness, -1) != '+' && substr($hardness, -1) != '-') {
            imageline($img, $pixels, 140, $pixels, 156, $black);
            imageline($img, $pixels, 734, $pixels, 751, $black);
            imagettftext($img, 10, 0, $pixels - 5, 765, $black, $label_font, $hardness);
            //imagettftext($img, 10, 0, $pixels- 5, 172, $black, $label_font, $hardness);
        } else {
            // it is a + or - declaration, shorter ticks and no label
            imageline($img, $pixels, 140, $pixels, 145, $black);
            imageline($img, $pixels, 746, $pixels, 751, $black);
        }
    }
    imageline($img, 707, 140, 707, 751, $black);
    imageline($img, 483, 140, 667, 140, $black);
    // finish line across top
    imageline($img, 483, 751, 667, 751, $black);
    // finish line across bottom
    imageline($img, 483, 140, 483, 751, $black);
    // left edge, first vert line
    imageline($img, 511, 140, 511, 751, $black);
    // beginning of crystal form column
    imageline($img, 575, 135, 575, 751, $black);
    //beginning of crystal size column
    imagettftext($img, 10, 0, 554, 122, $black, $label_font, "Crystal");
    imagettftext($img, 10, 0, 516, 137, $black, $label_font, "Form");
    imagettftext($img, 10, 0, 580, 137, $black, $label_font, "Size (mm)");
    // Snowpilot water mark logo _100
    $sp_watermark = imagecreatefrompng(DRUPAL_ROOT . '/sites/all/themes/sp_theme/images/SnowPilot_Watermark_BlueOrange_100.png');
    imagecopy($img, $sp_watermark, 35, 170, 0, 0, 160, 99);
    imagedestroy($sp_watermark);
    // Output the png image
    $filename = 'graph-' . $node->nid;
    imagejpeg($img, DRUPAL_ROOT . '/sites/default/files/snowpit-profiles/' . $filename . '.jpg', 100);
    imagepng($img, DRUPAL_ROOT . '/sites/default/files/snowpit-profiles/' . $filename . '.png');
    snowpilot_snowpit_crop_layers_write($img, $node->nid);
    // Destroy GD image
    //imagedestroy($img);
    if ($format == 'jpg') {
        return $img;
    } else {
        return $img;
    }
}