#!/usr/bin/php -q
<?php
/* 	GMAG BAS group (Antarctica).
	Reads /disks/themisdata/thg/ascii_data/mag/lpm_list.txt
	Writes into db for gmag availability (similar to gmag_db_insert_txt.php)
*/
?>
<html>

<head>
	<meta charset="utf-8">
	<title>BAS availability</title>
	<style>
		body {
			background-color: #F0F0F0;
		}

		table {
			border-collapse: collapse;
		}

		h1 {
			color: maroon;
			margin-left: 40px;
		}

		td,
		th {
			border: 1px solid blue;
			padding: 3px 6px;
		}
	</style>
</head>

<body>
	<?php
	date_default_timezone_set('UTC');
	$timezone = new DateTimeZone('UTC');
	// Directory for GMAG text files.
	$dir = '/disks/themisdata/thg/ascii_data/mag/';
	// List of BAS files. thg_l2_mag_gjoa_20100303_v01
	$filename = $dir . 'lpm_list.txt';
	$file = fopen($filename, "r");
	// http://psddb.nerc-bas.ac.uk/data/psddata/atmos/space/lpm/M73-159//2008/data/proc/Revision1.0/ascii/daily/00000/M73-159-2008.lpm.dg4.08.072.txt
	$path = "http://psddb.nerc-bas.ac.uk/data/psddata/atmos/space/lpm/M73-159//2008/data/proc/Revision1.0/ascii/daily/00000/M73-159-2008.lpm.dg4.08.072.txt";

	//$count = 0;
	while (!feof($file)) {
		/*
		$count++;
		if ($count > 100) {
			break;
		}
		*/
		$line = trim(fgets($file));
		$words = preg_split("/[-\.]+/", $line);
		if (count($words) == 8) {
			$station = $words[0] . "-" . $words[1];
			$year = $words[2];
			if ($year < 2005){
				continue;
			}
			$day = $words[6];
			// Remote path.
			$path = "http://psddb.nerc-bas.ac.uk/data/psddata/atmos/space/lpm/$station//$year/data/proc/Revision1.0/ascii/daily/00000/$line";
			echo "<a href='$path'>$path</a><br>\n";

			// Find filename.
			// Example filename: thg_l2_mag_ccnv_20120624_v01
			$format = 'Y-z';    // DOY, day of year
			$date = $year . '-' . ($day - 1);         //formatting the strings to the above $format
			$fileDateStore = DateTime::createFromFormat($format, $date, $timezone); //, $timezone);  //create the DateTime object
			$fileDateString = "thg_l2_mag_" . strtolower($station) . "_" . date_format($fileDateStore, "Ymd") . "_v01.txt";  //format it so strtotime() can read it

			echo 'fileDateString = ' . $fileDateString . "<br>\n";

			// Create directories.
			$localdir0 = $dir . strtolower($station) . "/";
			$localdir = $localdir0 . "$year/";
			$localfile = $localdir . $fileDateString;
			if (!file_exists($localdir0)) {
				mkdir($localdir0, 0777, true);
				echo "$localdir0<br>\n";
			}
			if (!file_exists($localdir)) {
				mkdir($localdir, 0777, true);
				echo "$localdir<br>\n";
			}
			echo "$localfile<br>\n";


			// Write the file.
			$myfile = fopen($localfile, "w") or die("Unable to open file!");
			fwrite($myfile, $path);
			fclose($myfile);
		}
	}

	fclose($file);
	?>
</body>

</html>