<?php
	$page_title = 'Run temp analysis';
	require('../directoryinfo.php');
	include('../connect.php');
	include('functions.php');
	require_once('../header.html');
?>

<!-- Form For Executing Code -->
<form action="map_figure.php" method="post" name="file_select">
	<fieldset>
	
	<table align="left" cellspacing=15>
		<tr><td colspan="2"><input type="checkbox" checked name="go" value="yes"><STRONG>draw map</STRONG></td></tr>
		<tr><td colspan=2><input type="submit" name="submit" value="Submit"></td></tr>
	</table>
	</fieldset>
</form>

<?php
	error_reporting(E_ALL);	
	if(isset($_POST['go'])) {
		$t0 = microtime(true);
		
		$q_time_scale = "SELECT interval_name, age_bottom, age_top, intervals.id FROM intervals 
		WHERE interval_name IN ('Whiterock', 'Chazyan', 'Blackriverian', 'Shermanian', 'Richmondian', 'Hirnantian', 'Rhuddanian', 'Aeronian', 'Telychian', 'Wenlock')
		ORDER BY age_bottom";
		$time_scale = mysqli_query($connect_macrostrat, $q_time_scale);         
		$n_bin = mysqli_num_rows($time_scale);
		
		while($row = mysqli_fetch_assoc($time_scale)) {			
			if($row['interval_name'] == 'Blackriverian') {
				$int_name[] = 'Blackriveran-Kirkfield';
				$int_bottom[] = $row['age_bottom'];
				$int_top[] = 457.0000;
			} else if($row['interval_name'] == 'Shermanian') {
				$int_name[] = 'Shermanian-Maysvillian';
				$int_bottom[] = $row['age_bottom'];
				$int_top[] = 450.0000;
			} else {
				$int_name[] = $row['interval_name'];
				$int_bottom[] = $row['age_bottom'];
				$int_top[] = $row['age_top'];
			}
			$int_id[] = $row['id'];
		}
		mysqli_free_result($time_scale);
		$n_int = count($int_name);
		
		$base_ordovician = 488.3;
		$study_max = max($int_bottom);
		$study_min = min($int_top);
		
		
		//////////////
		//
		// Column data saved as columns.csv
		//
		//////////////
		$q = "SELECT cols.id FROM cols 
		INNER JOIN col_groups ON col_groups.id=col_group_id 
		INNER JOIN projects ON projects.id=project_id
		WHERE project LIKE 'North America' AND col_group NOT LIKE 'Mexico' AND cols.id NOT IN (34, 111, 139, 218, 586, 587) AND status_code='active'";
		$columns = mysqli_query($connect_macrostrat, $q);       		
		while($row = mysqli_fetch_assoc($columns)) $my_cols[] = $row['id'];
		mysqli_free_result($columns);
		
		
		//////////////
		//
		// get packages	
		//
		//////////////		
		$temp_pkg = split_packages('marine');	
		for($i=0; $i<count($temp_pkg); ++$i) {
			$q = "SELECT col_id, max(b.age_bottom) bottom, min(t.age_top) top, count(distinct units.id) n_unit FROM units
			INNER JOIN intervals b ON b.id=FO
			INNER JOIN intervals t ON t.id=LO
			WHERE units.id IN ($temp_pkg[$i])";
			$result=mysqli_query($connect_macrostrat, $q);
			$row=mysqli_fetch_assoc($result);
			if(in_array($row['col_id'], $my_cols)===TRUE && $row['bottom']>$study_min && $row['top']<$study_max) $my_pkg[] = $temp_pkg[$i];	
			mysqli_free_result($result);
		}
		$all_units = implode(",",$my_pkg);
		
		
		//////////////
		//
		// units saved as O_S_units.csv
		//
		//////////////
		$units_file = "O_S_units.csv";
		$fh = fopen($units_file, 'w') or die("can't open file");
		chmod($units_file, 0777);
		$file_row = "unit_id, col_id, age_bottom, age_top, color\n";
		fwrite($fh, $file_row);
		$q = "SELECT units.id, col_id, b.age_bottom, t.age_top, color FROM units
		INNER JOIN intervals b ON b.id=FO
		INNER JOIN intervals t ON t.id=LO
		WHERE units.id IN (".$all_units.") and b.age_bottom>$study_min AND t.age_top<$study_max"; //echo $q."<br>";
		$result=mysqli_query($connect_macrostrat, $q);
		while($row=mysqli_fetch_assoc($result)) {
			$file_row = $row['id'].",".$row['col_id'].",".$row['age_bottom'].",".$row['age_top'].",".$row['color']."\n";
			fwrite($fh, $file_row);
		}
		fclose($fh);
		mysqli_free_result($result);
		echo 'File <a href="'.$units_file.'">'.$units_file.'</a> saved<BR>';
		
		
		//////////////
		//
		// pbdb_collections saved as O_S_collections.csv
		//
		//////////////
		$fh = fopen("collections.csv", "r");
		$my_collections = fgetcsv($fh, 100000, ",")
		echo "There are ".count($data)." collections<br>";
		fclose($fh); 
		
		$pbdb_file = "O_S_collections.csv";
		$fh = fopen($pbdb_file, 'w') or die("can't open file");
		chmod($pbdb_file, 0777);
		$file_row = "collection_no, unit_id, lat, lng\n";
		fwrite($fh, $file_row);
		$q = "SELECT collection_no, unit_id, lat, lng FROM pbdb_matches
		WHERE collection_no IN (".implode(",",$my_collections).")";
		$result=mysqli_query($connect_macrostrat, $q);
		while($row=mysqli_fetch_assoc($result)) {
			$file_row = $row['collection_no'].",".$row['unit_id'].",".$row['lat'].",".$row['lng']."\n";
			fwrite($fh, $file_row);
		}
		fclose($fh);
		mysqli_free_result($result);
		echo 'File <a href="'.$pbdb_file.'">'.$pbdb_file.'</a> saved<BR>';

		
		//////////////
		//
		// draw map in R
		//
		//////////////
		
		$r_file = "temp.r";
		$fh = fopen($r_file, 'w') or die("can't open file");
		chmod($r_file, 0777);
		
		$r_script = "
			source('myFunctions.r')
			library(maps)
			library(mapproj)
			
			time.scale <- read.csv(file='time_scale.csv', header=TRUE); n.bins <- nrow(time.scale)
			units <- read.csv(file='O_S_units.csv', header=TRUE)
			polygons <- read.csv(file='column_polygons.csv', header=TRUE)
			pbdb <- read.csv(file='O_S_collections.csv', header=TRUE)
			
			## make maps
			lon.limit <- c(-172,-50)
			lat.limit <- c(25,83)
			
			map.orient <- c(54,-103,0)
			
			map.data <- map('world', c('USA', 'Canada'), xlim=lon.limit, ylim=lat.limit, proj='azequalarea',orient=map.orient, plot=FALSE, interior=FALSE)
			
			map.color <- 'gray25'  # solid dark gray
			pbdb.color <- rgb(1,0,0,0.3)  # transparent red
			
			rock.colors <- matrix(NA, nrow=15, ncol=3)
			rock.colors[,1] <- c('blue','gray light','tan','orange','yellow','blue green','pink','brown dark','green dark','brown','green light','brown light','blue dark','gray','green')
			rock.colors[,2] <- c('#6BA1FF','#7C7C7C','#9A9469','#FF8400','#FFFF00','#00FFFF','#FF80A8','#55432F','#008800','#55432F','#008800','#55432F','#3838FF','#7C7C7C','#008800')
			rock.colors[,3] <- c('carbonate','fine clastics','mixed clastics','coarse clastics','sands','chert','evaporite','metamorphic','plutonic','metamorphic','volcanic','metamorphic','mixed carb/clast','fine clastics','volcanics')
			rock.colors <- rock.colors[order(rock.colors[,1]),]
			
			top.units <- vector(mode='numeric', length=nrow(units)); counter <- 1
			pdf(file='map_figure.pdf', height=20, width=50)
			par(mfrow=c(2,5), mar=c(0,0,10,0)+0.1, pch=16, cex.main=7)		
			
			for(i in n.bins:1) {
				unit.temp <- units[units[,3]>time.scale[i,3] & units[,4]<time.scale[i,2],]
				cols.temp <- unique(unit.temp\$col_id)
				pbdb.temp <- unique(pbdb[is.element(pbdb\$unit_id, unit.temp\$unit_id),3:4])
				
				plot(map.data, main=time.scale[i,1], axes=FALSE, frame.plot=TRUE, type='n', xlab='', ylab='')
				
				# plot macrostrat units
				for(j in 1:length(cols.temp)) {
					top.units[counter] <- unit.temp[unit.temp\$col_id==cols.temp[j],1][1]
					color.temp <- rock.colors[match(unit.temp[unit.temp\$col_id==cols.temp[j],5][1], rock.colors[,1]),2]
					
					poly.temp <- polygons[polygons[,1]==cols.temp[j],2:3]
					poly.proj <- mapproject(list(x=poly.temp[,1], y=poly.temp[,2]))
					polygon(poly.proj\$x, poly.proj\$y, col=paste(color.temp), border=paste(color.temp), lwd=0.5)
					counter <- counter + 1
				}
				
				# plot pbdb
				if(nrow(pbdb.temp) > 0) {
					pbdb.proj <- mapproject(list(x=pbdb.temp[,2], y=pbdb.temp[,1]))
					points(pbdb.proj\$x, pbdb.proj\$y, cex=3, col=pbdb.color)
				}
				lines(map.data\$x, map.data\$y, col=map.color)
			}
			dev.off()
			
			top.units <- top.units[top.units>0]
			rock.colors2 <- rock.colors[match(unique(units[is.element(units[,1], top.units), 5]),rock.colors[,1]),]
			
			## make legend
			pdf(file='map_legend.pdf', height=6, width=10)
			layout(matrix(1:15, nrow=3, ncol=5, byrow=TRUE))
			for(i in 1:nrow(rock.colors2)) {
				par(mar=c(0.1,0.1,0.1,0.1))
				plot(1:10, xlim=c(0,10), ylim=c(0,10), type='n', axes=FALSE, frame.plot=TRUE, xlab='', ylab='')
				rect(1,1,9,4, col=paste(rock.colors2[i,2]))
				text(5,8, labels=rock.colors2[i,1], cex=1.5)
				text(5,6, labels=rock.colors2[i,3], cex=1.5)
			} 
			dev.off()
			";
		
		fwrite($fh, $r_script);
		
		$cmd = "echo 'rscript <- \"$r_file\"; source(rscript)' | " . "/usr/bin/R --slave 2>&1";
		exec($cmd, $r_ran); 
		if(count($r_ran)>0) {
			print_r($r_ran); echo "<br>";
		}
		
		echo 'File <a href="map_figure.pdf" target="blank">map_figure.pdf</a> saved<BR>';
		echo 'File <a href="map_legend.pdf" target="blank">map_legend.pdf</a> saved<BR>';

	}


	//////////////
	//
	// stuff at the end
	//
	//////////////
	if(isset($_POST['submit'])) {
		$t1 = microtime(true);
		$time_diff = $t1 - $t0;
		if ($time_diff/60 < 1) {
			$diff_seconds = round($time_diff, 3);
			echo "<br>This process took ".$diff_seconds." seconds";
		} else if ($time_diff>=1 & $time_diff<3600) {
			$diff_min = round($time_diff/60, 3);
			echo "<br>This process took ".$diff_min." minutes";
		} else {
			$diff_hour = round($time_diff/3600, 3);
			echo "<br>This process took ".$diff_hour." hours";
		}
	}
?>



<?php 
	require_once('../footer.html');
	exit();
?>