<?php
// This is a PHP only file i.e. does not generate any HTML output
// This file is run with one argument only i.e. name of the DIDDB.args file
// All information to run this script is then obtained from that file

// Copy file read by entget to standard location in Inputs/$dbase/$source_name/$attribute
// Read this file in to database
require '../Common/openDB.php';
require '../Common/preferences.php';
global $glob_start;
global $glob_start;
$vv = true;
$vvv = true;
global $cmd_debug; // local debugging flag
$cmd_debug = true;
$cmd_debug = false;

// open arguments file to read information
$argsf = fopen($argv[1],"r");
if ($argsf) {
    while (($line = fgets($argsf)) !== false) {
        $argm = strtok($line," ");
		$argm = trim($argm);
		$remainder = substr($line, strpos($line, " ") + 1);

		//echo $argm . " is " . $remainder;
		if($argm == "dynamic_id"){
			$dynamic_id = trim($remainder);
		}else if($argm == "dbase"){
			$dbase = trim($remainder);
		}else if($argm == "source_name"){
			$source = trim($remainder);
		}else if($argm == "attribute"){
			$attribute = trim($remainder);
		}else if($argm == "input_method"){
			$input_method = trim($remainder);
		}else if($argm == "EG_source"){
			$input_submethod = trim($remainder);
		}else if($argm == "EG_user"){
			$username = trim($remainder);
		}else if($argm == "EG_password"){
			$password = trim($remainder);
		}else if($argm == "EG_destination"){
			$code = trim($remainder);
		}else if($argm == "EG_appdestinationLocal"){
			$localapp = trim($remainder);
		}else if($argm == "EG_IP"){
			$IP = trim($remainder);
		}else if($argm == "EG_fetchpath"){
			$FetchPath = trim($remainder);
		}else if($argm == "expected_items"){
			$expected_items = trim($remainder);
		// }else if($argm == ""){
		//  = trim($remainder);

		}
    }
    fclose($argsf);
    $error_opening_args_file = false;
} else {
    $error_opening_args_file = true;
}

// Connect to database
mysql_query("SET foreign_key_checks = 0",$con);
mysql_select_db($dbase, $con);
$res = mysql_query("SELECT fetcher_id,source_id FROM Dynamic WHERE dynamic_id = {$dynamic_id}",$con);
while ($row = mysql_fetch_array($res)){
	$fetcher_id = $row[0];
	$source_id = $row[1];
}

// Get time to add to file name
date_default_timezone_set($TimeZone);

// Start write of log file
$source_dir = preg_replace('/\s+/', '_', $source);
$att_dir = preg_replace('/\s+/', '_', $attribute);
$debugFName = "../../Inputs/{$dbase}/{$source_dir}_{$source_id}/{$att_dir}_{$dynamic_id}.log";
if(file_exists($debugFName)){
	$debugF = fopen($debugFName,"a");
}else{
	$debugF = fopen($debugFName,"w");
	fwrite($debugF,"ENTRAK Version {$Version} data input log file \n");
	fwrite($debugF,"website:      {$website}\n");
	fwrite($debugF,"userid:       {$userid}\n");
	fwrite($debugF,"entity name:  {$source}\n");
	fwrite($debugF,"attribute:    {$attribute}\n");
}

if($cmd_debug){
  echo("80 ENTRAK Version {$Version} data input log file \n");
  echo("81 website:      {$website}\n");
  echo("82 userid:       {$userid}\n");
  echo("83 entity name:  {$source}\n");
  echo("84 attribute:    {$attribute}\n");
}

// Setup flag file
$lock_file = $dynamic_id . $dbase . ".lock";

if(file_exists($lock_file)){
	// have not returned from previous wget request do not do anything
	$new_time = date('Y-m-d H:i:s');
	if($vv || $vvv)fwrite($debugF, "WARNING: Trying to fetch data at {$new_time} unsuccessful as previous fetch has not finished\n");
	if($cmd_debug)echo("102 WARNING: Trying to fetch data at {$new_time} unsuccessful as previous fetch has not finished\n");

}else{
	$current_time = date('Y-m-d H:i:s');
	$timeStr = str_replace(" ","_",$current_time);
	$timeStr = str_replace(":",".",$timeStr);

	// Get data fetch frequency
	$res = mysql_query("SELECT frequency_id FROM Fetcher WHERE fetcher_id = {$fetcher_id}",$con);
	while ($row = mysql_fetch_array($res))$frequency_id = $row[0];
	$res = mysql_query("SELECT period,times_per_period FROM Frequency WHERE frequency_id = {$frequency_id}",$con);
	while ($row = mysql_fetch_array($res)){
		//>>>>>>>>> CHANGE NEXT LINE TO CALL NEWER FUNCTION in openDB
		$period_from_db = GetTimePeriod($row[0],$row[1]);
	}

	// Online input method
	touch($lock_file);
	if($input_method == "Online"){
		if($input_submethod == "LRS"){

			// Get start time which data is to be captured from
			//					 	now minus period corresponding to associated frequency or
			//						most recent database entry or
			//  					start time in frequency table

			// Get start time from most recent db timestamp entry
			$res = mysql_query("SELECT count(timestamp) FROM DynamicValue WHERE dynamic_id = {$dynamic_id}",$con);
			while ($row = mysql_fetch_array($res))$count = $row[0];
			if($count > 0){
				$res = mysql_query("SELECT MAX(timestamp) FROM DynamicValue WHERE dynamic_id = {$dynamic_id}",$con);
				while ($row = mysql_fetch_array($res))$timestamp_to_read_data_from = $row[0];
			}else{ // Get start time from start defined in frequency table
				$res = mysql_query("SELECT fetcher_id FROM Dynamic WHERE dynamic_id = {$dynamic_id}",$con);
				while ($row = mysql_fetch_array($res))$fetcher_id = $row[0];
				$res = mysql_query("SELECT frequency_id FROM Fetcher WHERE fetcher_id = {$fetcher_id}",$con);
				while ($row = mysql_fetch_array($res))$frequency_id = $row[0];
				$res = mysql_query("SELECT start FROM Frequency WHERE frequency_id = {$frequency_id}",$con);
				while ($row = mysql_fetch_array($res))$timestamp_to_read_data_from = $row[0];
			}

			// If most recent time stamp in database has not been set then set it to current time minus period corresponding to associated frequency
			// Do this also if preferences are set to $FetchFromNow
			if($timestamp_to_read_data_from == "" || $timestamp_to_read_data_from == NULL){
				$timestamp_to_read_data_from = strtotime($current_time) - $period_from_db; 			 // convert to seconds from UNIX epoch
				$timestamp_to_read_data_from = date('Y-m-d H:i:s',$timestamp_to_read_data_from);	 // convert to human readable time
			}

			fwrite($debugF, "START FETCH: Time now {$current_time}. Input method Online - LRS for source = {$source}; SID = {$source_id}; dynamic = {$attribute}; DID = {$dynamic_id} \n");
			if($cmd_debug)echo("151 START FETCH: Time now {$current_time}. Input method Online - LRS for source = {$source}; SID = {$source_id}; dynamic = {$attribute}; DID = {$dynamic_id} \n");
			$timestamp_to_read_data_from = strtotime($timestamp_to_read_data_from); // convert to seconds from UNIX Epoch

			// Start and end times are most recent timestamp in db and now() but adjust to LRS time and global_data_fetch_timestamp_delay
			// Adjust if LRS in different timezone
			$timestamp = time();
			$dt = new DateTime("now", new DateTimeZone($TimeZone)); //first argument "must" be a string
			$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
			//echo $dt->format('d.m.Y, H:i:s') . "<br/>";
			$LRS_time_now = $dt->format('U');
			$LRS_time_shift = 946684800;

			$TENDADJ   = $LRS_time_now - $LRS_time_shift - $global_data_fetch_timestamp_delay;
			$TSTARTADJ = $timestamp_to_read_data_from - $LRS_time_shift + 1 - $global_data_fetch_timestamp_delay; // 1 second after most recent db timestamp
			$glob_stop = $TENDADJ;
			$CopiedFileName = $dynamic_id . $dbase;
			$tmpFile = $CopiedFileName;
      $csv_file_name = $CopiedFileName . ".csv";

			// Get cookies file note that 2>&1 transmits all consol messages to $output which is wget default of some sort as for most programs
			// consol output is written by default to $output within PHP
			$cookies_file = "cookies_" . $dynamic_id . $dbase . ".txt";
			if(file_exists($cookies_file))unlink($cookies_file);
            if($oper_sys == "windows"){
              if(file_exists("C:\\Program Files (x86)\\Ampps\\www\\EnTrak\\EnTrak\\2_Projects")){
                $wget = "wget64.exe";
              }elseif(file_exists("C:\\Program Files\\Ampps\\www\\EnTrak\\EnTrak\\2_Projects")){
                $wget = "wget.exe";
              }else{
                echo "<h1> Error: FetchDataCron.php WAMP server not found";
                exit;
              }
            }elseif($oper_sys == "linux"){
                $wget = "wget";
            }
			$command = "{$wget} --keep-session-cookies --save-cookies {$cookies_file} --post-data \"user={$username}&pass={$password}\" http://{$IP}/WWW/login.htm 2>&1 --delete-after";
			if($vv || $vvv)fwrite($debugF, "  Calling wget to get cookies with command: {$command}\n");
			if($cmd_debug)echo("181  Calling wget to get cookies with command: {$command}\n");
			$output = shell_exec($command);

			$tmp_str = $TSTARTADJ + $LRS_time_shift;
			$debug_start = date('Y-m-d H:i:s',$tmp_str);
			$tmp_str = $TENDADJ + $LRS_time_shift;
			$debug_stop = date('Y-m-d H:i:s',$tmp_str);
			fwrite($debugF, "  Getting information from {$debug_start} to {$debug_stop} for dynamic attribute \n");
			if($vvv)fwrite($debugF, " Verbose output (command line output from individual commands) follows\n");
			if($vvv)fwrite($debugF, "  {$output}");
			if($cmd_debug)echo("191  Getting information from {$debug_start} to {$debug_stop} for dynamic attribute \n");
			if($cmd_debug)echo("192 Verbose output (command line output from individual commands) follows\n");
			if($cmd_debug)echo("193  {$output}");

			// Get data
			if(file_exists($cookies_file)){
				$entget_args = GetEntGetArgs($fetcher_id,$username,$password,$IP,$code,NULL,"last x lines");
				shell_execute($entget_args);
				if($FetchFromNow){ // call entget with number of items to fetch
					$lines_to_get = 100;
					$UNLT = 0;
					$niter = 0;
					$max_iter = 10;
					iter:
						$niter ++;
						if($niter > $max_iter){
							fwrite($debugF, "  ERROR: Could not load even 1 value for this entity after {$max_iter} tries, aborting. Check expected number of items and frequency for this attribute\n ");
							if($cmd_debug)echo("208  ERROR: Could not load even 1 value for this entity after {$max_iter} tries, aborting. Check expected number of items and frequency for this attribute\n ");
							unlink($lock_file);
              unlink($cookies_file);
              unlink($csv_file_name);
							exit;
						}
						$command = "{$wget} --load-cookies {$cookies_file} -O {$tmpFile} --tries=1 --read-timeout=5 --no-http-keep-alive --content-disposition http://{$IP}/fetch?type=LS\"\\&\"start={$lines_to_get}\"\\&\"end= 2>&1";
						if($vv || $vvv)fwrite($debugF, "  Calling wget to get data with command: \n  {$command}\n");
						if($cmd_debug)echo("214  Calling wget to get data with command: \n  {$command}\n");
						$output = shell_exec($command);
						if($vvv)fwrite($debugF, "  {$output}");
						if($cmd_debug)echo("217  {$output}");
						if($cmd_debug)echo("218 OS is  {$oper_sys} \n");
						$command = GetLocalAppCommand($localapp,$CopiedFileName,$code,$oper_sys);
            if($cmd_debug)echo("219 Running local app with command {$command}\n");
						RunLocalApp($debugF,$command,$vvv,$vv,$input_method,$CopiedFileName);
            if($cmd_debug)echo("222 csv file name is {$csv_file_name}\n");
            if($cmd_debug)echo("");
            if($cmd_debug)echo("");
            if($cmd_debug)echo("");
            if($cmd_debug)echo("");

            $UNLT = get_lines_in_file($csv_file_name);
						if($UNLT >= $expected_items){
							goto read_data;
						}elseif($UNLT >= 1){
							$lines_to_get = intval($lines_to_get * $expected_items / $UNLT);
						}elseif($UNLT <= 0){
							$lines_to_get = intval($lines_to_get * $niter);
						}
            sleep(5); // sleep for at least read-timeout number of seconds given in wget command above
						goto iter;

					read_data:
						$result3 = mysql_query("SELECT MAX(timestamp) FROM DynamicValue WHERE dynamic_id = {$dynamic_id}",$con);
						while ($row = mysql_fetch_array($result3))$timestamp_to_read_data_from = $row[0];
						WriteDataDB($csv_file_name, $con, $dynamic_id, $timestamp_to_read_data_from, $debugF);
						unlink($cookies_file);

            //make folders if not present
            if(!file_exists("../../Inputs/{$dbase}"))mkdir("../../Inputs/{$dbase}");
            if(!file_exists("../../Inputs/{$dbase}/{$source_dir}_{$source_id}"))mkdir("../../Inputs/{$dbase}/{$source_dir}_{$source_id}");
            if(!file_exists("../../Inputs/{$dbase}/{$source_dir}_{$source_id}/{$att_dir}_{$dynamic_id}"))mkdir("../../Inputs/{$dbase}/{$source_dir}_{$source_id}/{$att_dir}_{$dynamic_id}");
						$NewCopiedFileName = "../../Inputs/{$dbase}/{$source_dir}_{$source_id}/{$att_dir}_{$dynamic_id}/DataReadAt{$timeStr}.csv";
						rename($csv_file_name,$NewCopiedFileName);

				}else{ // call entget with start and stop fetch timestamps
					$entget_args = GetEntGetArgs($fetcher_id,$username,$password,$IP,$code,$tmpFile,"time");
					shell_execute($entget_args);
					$command = "{$wget} --load-cookies {$cookies_file} -O {$tmpFile} --tries=1 --read-timeout=5 --no-http-keep-alive --content-disposition http://{$IP}/fetch?type=BT\"\\&\"start={$TSTARTADJ}\"\\&\"end={$TENDADJ} 2>&1";
					if($vv || $vvv)fwrite($debugF, "  Calling wget to get data with command: \n  {$command}\n");
					if($cmd_debug)echo("244  Calling wget to get data with command: \n  {$command}\n");
					$output = shell_exec($command);
					if($vvv)fwrite($debugF, "  {$output}");
					if($cmd_debug)echo("247  {$output}");
					unlink($cookies_file);
					$NewCopiedFileName = "../../Inputs/{$dbase}/{$source_dir}_{$source_id}/{$att_dir}_{$dynamic_id}/DataReadAt{$timeStr}.csv";
					GetData2DB($CopiedFileName,$localapp,$debugF,$command,$vvv,$input_method,$con,$dynamic_id, $timestamp_to_read_data_from,$NewCopiedFileName,$code);
				}
			}
		}else{ // code supporting ftp to go here


		}

	// File exchange input method
	}else{
		fwrite($debugF, "START FETCH: Time now {$current_time}. Input method fileX for source = {$source}; SID = {$source_id}; dynamic = {$attribute}; DID = {$dynamic_id} ");
		fwrite($debugF,"  Input method: File Exchange, Accessing folder {$FetchPath} \n");
		if($cmd_debug)("262 START FETCH: Time now {$current_time}. Input method fileX for source = {$source}; SID = {$source_id}; dynamic = {$attribute}; DID = {$dynamic_id} ");
		if($cmd_debug)("263 Input method: File Exchange, Accessing folder {$FetchPath} \n");

		// For all files in the directory
		//		1. run local app on each file
		//		2. read resulting file into database
		//		3. copy resulting file into std loc
		//		4. delete original file
		$dir = "../../Inputs/FileX/{$dbase}/{$source_dir}_{$source_id}/{$att_dir}_{$dynamic_id}";
    if($vv || $vvv)fwrite($debugF,"setting dir to {$dir}\n");
		if (is_dir($dir)){
			if ($dh = opendir($dir)){
				while (($FileName = readdir($dh)) !== false){
					if($FileName == "." || $FileName == "..")continue;
					$CopiedFileName = $dir ."/".$FileName;
					$NewCopiedFileName = "../../Inputs/{$dbase}/{$source_dir}_{$source_id}/{$att_dir}_{$dynamic_id}/DataReadAt{$timeStr}.csv";
          if($vv || $vvv)fwrite($debugF,"Setting new copied file name to {$NewCopiedFileName}\n");
					GetData2DB($CopiedFileName,$localapp,$debugF,$command,$vvv,$input_method,$con,$dynamic_id, $timestamp_to_read_data_from,$NewCopiedFileName,$code);
				}
				closedir($dh);
			}
		}
	}
	unlink($lock_file);
	$new_time = date('Y-m-d H:i:s');
	fwrite($debugF, "STOP LOG WRITE STARTED AT {$current_time} THE TIME NOW {$new_time}\n");
	if($cmd_debug)echo("286 STOP LOG WRITE STARTED AT {$current_time} THE TIME NOW {$new_time}\n");
}
fclose($debugF);

// End of PHP session only support functions follow this line

// High level function to
// 		1.	run localapp on raw fetched data to convert to from BINARY to ASCII file (or ASCII to ASCII in the correct format to enable read in to DB)
//		2.	write data to database
//		3.	copy ASCII file to local temporary repository
function GetData2DB($CopiedFileName,$localapp,$debugF,$command,$vvv,$input_method,$con,$dynamic_id, $timestamp_to_read_data_from,$NewCopiedFileName,$code){

	if(file_exists($CopiedFileName)){
		if(is_string($localapp)) {
			$command = GetLocalAppCommand($localapp,$CopiedFileName,$code,$oper_sys);
			RunLocalApp($debugF,$command,$vvv,$vv,$input_method,$CopiedFileName);
		}else{
			rename($CopiedFileName, "{$CopiedFileName}.csv");
		}

		if($vv || $vvv)fwrite($debugF, "  Writing data to database ");
		if($cmd_debug)echo("307  Writing data to database ");
		WriteDataDB("{$CopiedFileName}.csv", $con, $dynamic_id, $timestamp_to_read_data_from, $debugF);
		if($vv || $vvv)fwrite($debugF, "  ... finished writing data to database \n");
		if($cmd_debug)echo("310  ... finished writing data to database \n");

		//move csv to std loc
		rename("{$CopiedFileName}.csv", $NewCopiedFileName);
    fwrite($debugF,"Copying {$CopiedFileName}.csv to {$NewCopiedFileName}\n");
		$filesize = filesize($NewCopiedFileName);
		if(!$filesize)fwrite($debugF, " WARNING file size of input file could not be determined, it was probably a zero size file! \n");
		if($cmd_debug)echo("316 WARNING file size of input file could not be determined, it was probably a zero size file! \n");
	}
}

// function to get arguments for entget
function GetEntGetArgs($fetcher_id,$username,$password,$IP,$FN,$mode){
	// Check if entget exists in folder
	if(file_exists("entget.bash")){
		if($mode == "last x lines"){
			return ("./entget.bash -u {$username} -p {$password} -ip {$IP} -last 100 -env {$code}");
		}elseif($mode == "time"){
			return (" ./entget.bash -u {$username} -p {$password} -ip {$IP} {$FN} -start \'{$glob_start}\' -end \'{$glob_stop}\'");
		}
	}
	return "ERROR: entget.bash not found in this folder";
}

// Write data read from csv file (FORMAT timestamp, value) into given dynamic ID
function WriteDataDB($inputFileName, $conn, $DID, $timestamp_to_read_data_from, $debugF){
	require "../Common/preferences.php";
/*	require "../Common/math_functions.php";

	// Get average frequency of data from previous DB entries
	$timesteps = array();
	$i = 0;
	$sumtim = 0;
	$laterTS = $timestamp_to_read_data_from;
	$res = mysql_query("SELECT timestamp FROM DynamicValue WHERE dynamic_id = {$DID} ORDER BY timestamp DESC LIMIT {$entries_to_read}",$conn);
	while ($row = mysql_fetch_array($res)){
		$earlierTS = strtotime($row[0]);
		$timesteps[$i] = $laterTS - $earlierTS;
		$i++;
		$laterTS = $earlierTS;
	}
	$time_period = get_time_period($timesteps);
	echo "time period is {$time_period}";
*/
	$handle = fopen($inputFileName, "r");
	while(!feof($handle)){
		$write2db = true;
		$str = fgets($handle);

    //remove duplicate commas in $str
    // remove this line as soon as Jon fixes bax2csv bug writing two commas
    $str = str_replace(",,",",",$str);

		$TS_Value = explode(",",$str);

		if($str == "" || $str == NULL || trim($str) == "")continue;

		$TS = $TS_Value[0];     // timestamp
		$value = $TS_Value[1];  // value

		$TSX = explode(" ",$TS);
		$Date = $TSX[0];
		$Time = $TSX[1];

		$DateX = explode("-",$Date);
		$TimeX = explode(":",$Time);

		$year = $DateX[0];
		$month = $DateX[1];
		$day = $DateX[2];
		$hour = $TimeX[0];
		$minute = $TimeX[1];
		$second = $TimeX[2];



		if(!checkdate($month,$day,$year)){
			$write2db = false;
			fwrite($debugF, "WARNING  Date month,day,year = {$month},{$day},{$year}is invalid, this value will not be written to database \n");
			if($cmd_debug)echo("380 WARNING  Date month,day,year = {$month},{$day},{$year}is invalid, this value will not be written to database \n");
		}

		if(!checktime($hour,$minute,$second)){
			$write2db = false;
			fwrite($debugF, "WARNING  Time hour,minute,second = {$hour},{$minute},{$second} is invalid, this value will not be written to database \n");
			if($cmd_debug)echo("386 WARNING  Time hour,minute,second = {$hour},{$minute},{$second} is invalid, this value will not be written to database \n");
		}

		if(substr($TS,0,4) == "0000"){
			$write2db = false;
			fwrite($debugF, "WARNING 0000 year number detected, this value will not be written to database \n");
			if($cmd_debug)echo("392 WARNING 0000 year number detected, this value will not be written to database \n");
		}

		$most_recent_TS_in_DB = strtotime($timestamp_to_read_data_from);
		$TS_to_write = strtotime($TS);
		if($most_recent_TS_in_DB >= $TS_to_write){
			$write2db = false;
			//fwrite($debugF, "WARNING database contains later timestamps, this value will not be written to database \n");
		}

		// All tests passed add data to data base
		if($write2db)mysql_query("INSERT INTO DynamicValue (dynamic_id,timestamp,value) VALUES ({$DID},\"{$TS}\",{$value}) ",$conn);

	}
}

function checktime($hr, $min, $sec) {
     if ($hr < 0 || $hr > 23 || !is_numeric($hr)) {
         return false;
     }
     if ($min < 0 || $min > 59 || !is_numeric($min)) {
         return false;
     }
     if ($sec < 0 || $sec > 59 || !is_numeric($sec)) {
         return false;
     }
     return true;
}

// Get command to convert {$CopiedFileName} to {$CopiedFileName}.csv
function GetLocalAppCommand($localapp,$CopiedFileName,$code,$oper_sys){

    // different executables for different operating systems
    if($oper_sys == "windows"){
      if(file_exists("C:\\Program Files (x86)\\Ampps\\www\\EnTrak\\EnTrak\\2_Projects")){
        $bax2csv = "bax2csv.exe";
      }elseif(file_exists("C:\\Program Files\\Ampps\\www\\EnTrak\\EnTrak\\2_Projects")){
        $bax2csv = "bax2csv32.exe";
      }else{
        echo "<h1> Error: FetchDataCron.php WAMP server not found";
        exit;
      }

    }elseif($oper_sys == "linux"){
        $bax2csv = "./bax2csv";
    }

	// command line argument for bax2*
	if($localapp == "bax2battery"){
		$topic = "bat";
	}elseif($localapp == "bax2dbt"){
		$topic = "dbt";
	}elseif($localapp == "bax2lux"){
		$topic = "lux";
	}elseif($localapp == "bax2pirc"){
		$topic = "pirc";
	}elseif($localapp == "bax2rh"){
		$topic = "rh";
	}elseif($localapp == "bax2switch"){
		$topic = "sw";
	}else{
		$topic = "not defined";
	}

	// Get local app -- set variable command
	if(	$localapp == "bax2battery"  ||
		$localapp == "bax2dbt"		||
		$localapp == "bax2lux"		||
		$localapp == "bax2pirc"		||
		$localapp == "bax2rh"		||
		$localapp == "bax2switch"	){
		return "{$bax2csv} {$CopiedFileName} {$CopiedFileName}.csv -N {$code} -f {$topic}";
	}elseif($localapp == "not defined"){
		// put eltek processing here
	}else{
		// other local apps to go here
		return "No suitable local app found";
	}
}

// Run command to convert {$CopiedFileName} to {$CopiedFileName}.csv
function RunLocalApp($debugF,$command,$vvv,$vv,$input_method,$CopiedFileName){
  if($cmd_debug)echo("466  Converting raw input file ({$file_size}) to csv with command: {$command}\n");
	$file_size = human_filesize(filesize($CopiedFileName));
  if($cmd_debug)echo("467  Converting raw input file ({$file_size}) to csv with command: {$command}\n");
	if($vv || $vvv)fwrite($debugF, "  Converting raw input file ({$file_size}) to csv with command: {$command}\n");
	if($cmd_debug)echo("468  Converting raw input file ({$file_size}) to csv with command: {$command}\n");
	$output = shell_exec($command);
	if($vvv)fwrite($debugF, "  {$output}");
	if($cmd_debug)echo("471  {$output}");

	// Delete raw input file (e.g. bin bax2csv file copied from LRS)
	if($vv || $vvv)fwrite($debugF, "  Deleting raw input file copied via input method: {$input_method} named {$CopiedFileName}\n");
	if($cmd_debug)echo("475  Deleting raw input file copied via input method: {$input_method} named {$CopiedFileName}\n");
	$command = "DEL {$CopiedFileName}";
	shell_exec($command);
}

function get_lines_in_file($file){
	$linecount = 0;
	$handle = fopen($file, "r") or die("file {$file} could not be found");
	while(!feof($handle)){
		$line = fgets($handle);
		$linecount++;
	}
	fclose($handle);
	return $linecount;
}

/*

Write time in UNIX epoch, LRS epoch and human readable format

$start = 509126941;
$end   = 509127000;

echo "As given in wget        start = {$start} end = {$end} <br/>";

$start += 946684800;
$end += 946684800;

echo "Unix seconds from epoch start = {$start} end = {$end} <br/>";

$start = date('Y-m-d H:i:s',$start);
$end = date('Y-m-d H:i:s',$end);

echo "Human readable          start = {$start} end = {$end} <br/>";

*/

?>
