#include <stdio.h>   /* required for file operations */
#include <stdlib.h>
#include <pthread.h> // compile with -lpthread 
#include <time.h>

FILE *fr;            /* declare the file pointer */
void *readlines();

main()
{
   pthread_t thread1;
   int  iret1;

   iret1 = pthread_create( &thread1, NULL, readlines,NULL);
   sleep(20);
   exit(0);
   
}

void *readlines()
{
   int n,cnt=0,number;
   char line[80];
   char *lch;
   float temp1,temp2,cputemp;
   
   FILE *output = NULL, *i2c = NULL;
   time_t now;
   struct tm *tm;
     
   fr = fopen ("/dev/ttyS0", "rt");  /* open the file for reading */
   /* "rt" means open the file for reading text */

   while ((fgets(line, 80, fr) != NULL) && cnt < 8)
   {
   	 /* get a line, up to 80 chars from fr.  done if NULL */
    	//  sscanf (line, "%s", &lch);
	 /* convert the string to a long int */
 	 //printf ("%s\n", lch);
	 
	  // remove trailing \n 
	  lch = line + strlen(line) - 1;
          while (*lch == '\r' || *lch == '\n') {
            *lch-- = '\0';
            if (lch < line) break;
          }

	  /* remove preceeding lf or cr */
	  lch = line;
	  while (*lch == '\r' || *lch == '\n') lch++;

          /* ignore any other packet header other than sensor reports */
          if (!isdigit(*lch)) continue;

	  /* decode the sensor number */
          number = atoi(lch)-1;
         if (number < 0 || number > 3) continue;
	 
         lch++; // skip space
         if (*lch != ' ') continue;
	 if (strlen(lch) > 9) lch += 11;
	 lch++;
	
	 //printf(lch);
	 //printf(" %d \n ",number);
	 // scan data
	 if (number == 0)
	 sscanf(lch, "%f", &temp1);
	 
	 if (number == 1)
	 sscanf(lch, "%f", &temp2);	 
		 
	 
	 cnt++;
   }
   
      /* establish timestamp for this sample */
      now = time(NULL);
      tm = localtime(&now);
   
   fclose(fr);  /* close the file prior to exiting the routine */
  
   i2c = fopen("/sys/bus/i2c/devices/0-002d/temp2_input", "r");
   if (i2c == NULL) { perror("i2c bus"); exit(1); }
   if (fgets(line,10,i2c) != NULL)
   {
     sscanf(line, "%f", &cputemp);
     if(cputemp > 1000)
	     cputemp = cputemp /1000;
   }
   fclose(i2c);
   
   output = fopen("xxx.log", "a");
   if (output == NULL) { perror("xxx.log"); exit(1); }
   fprintf(output,"%04d|%03d|%02d|%02d|%0.2f|%0.2f|%0.2f\n",  tm->tm_year+1900,tm->tm_yday+1,
                         tm->tm_hour, tm->tm_min, temp1 , temp2 , cputemp);
   fclose(output);
}