use File::Copy;
#use strict;
#use warnings;
use LWP::Simple;

# get SQM-LE data
use IO::Socket;
$remote = IO::Socket::INET->new(PeerAddr => "192.168.2.140", PeerPort => 10001, Proto => 'tcp') || die("Cannot connect to port $sqm_le_port on $sqm_le_addr:$!");
$remote->autoflush(1);
$str="";
print $remote "rx";
$str .= <$remote>;
$remote->close;

# SQM file content:
#  r,-02.21m,0000000007Hz,0000059399c,0000000.129s, 037.0C
#            1         2         3         4         5
#  0123456789 123456789 123456789 123456789 123456789 1234
if ($str =~ /\n/) 
{
  ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);

  #SQM-LE data extraction
  $mpsas=substr($str,2,6) - '0.13';  # offset removed from reading due to acrylic dome
  $frequency=substr($str,10,10);
  $counts=substr($str,23,10);
  $period=substr($str,35,11);
  $temperature=substr($str,48,6);

  $HourOfDay = $hour + $min / 60 + $sec / 3600;

  # get skyclock data and search through file for local time data
  $_ = get("http://cleardarksky.com/txtc/WtchObQCcsp.txt");
  s/[\cI\"()]//g; split('\n'); # clean up file and split into lines
  $ind=5;
  while (@_[$ind])
  {
    ($sc_time, $sc_cloud_val, $sc_transparency,$sc_seeing,$sc_wind,$sc_humid,$sc_temp) = split(',',@_[$ind]);
    ($sc_date, $sc_hour)           = split(' ',$sc_time);
    ($sc_year, $sc_month, $sc_day) = split('-',$sc_date);
    ($sc_hour, $sc_min, $sc_sec)   = split(':',$sc_hour);
    $sc_cloud = (10 - $sc_cloud_val) * 10;  
    if (($sc_hour == $hour) && ($sc_day == $mday)) 
    {
      goto SQMcont;
    }
    $ind++;
  }

SQMcont:

  # Get sunrise and sunset time from 'Weather Display' custom text file
  open (FILE, "<".$Path."customtextout.txt");
  $_ = <FILE>;
  ($sunrise_hour, $sunrise_min, $sunset_hour, $sunset_min) = split(/[:,]/);
  $sunrise = $sunrise_hour + $sunrise_min / 60 - 0.75;  # 45 minutes before sunrise
  $sunset  = $sunset_hour  + $sunset_min  / 60 + 0.75;  # 45 minutes after  sunset
  close FILE;
  unlink $Path."customtextout.txt";

  # only log if sundown
  if (($HourOfDay < $sunrise) || ($HourOfDay > $sunset) || ($sunrise == 0) || ($sunset == 0))
  {
    # only log if few clouds, seeing and transparency acceptable
    if (($sc_cloud < 20)  && ($sc_seeing > 1) && ($sc_transparency > 1))
    {
      open (FILE, ">>".$Path."SQMData.csv") or die ("Could not open SQMData.csv\n");
      printf FILE "%04d, %02d, %02d, %02d:%02d:%02d, %d,%f,%s,%s,%s,%s,%s,(%s)\n",$year+1900,$mon+1,$mday,$hour,$min,$sec,$yday,$HourOfDay,$mpsas,$temperature,$sc_cloud,$sc_seeing,$sc_transparency,$sc_time;
      # Year,Month,Day,Local time,day of year,hour of day,Sky Quality (mag/arc sec **2),SQM temperature (Celsius)
      close FILE;
    }
  }
}
