/* Christopher Huyler */
/* long.c */
/* Solution for Project 1 Part D
   - Print Memory Information total/free
   		Open meminfo and find the line begining
   		with Mem: and retrieve first two numbers
   		The first is total memory and to get free
   		memory subtract it from the second number
   		which is used memory
   - Print List of Load averages
   		create a loop to repeat duration/interval
   		times.  Open the file loadavg and read
   		the first number then close it. Sleep for
   		interval seconds */


#include <stdio.h>
#include <string.h>

#define MAX_LEN 80

void printLong(int interval,int duration)
{
	FILE *fp;
	char lineBuf[MAX_LEN],		/* char array line buffer */
		 junk[16];				/* junk char array */
	int total,					/* total memory */
		used,					/* used memory */
		i;						/* counter */
	char load[16];				/* system load (really a float) */

/* print memory information */
	if ((fp = fopen("/proc/meminfo","r")) == NULL)
	{
		printf("read: can't open file\n");
		exit(1);
	}
	else
	{	/* read Mem line and print values */
		fgets(lineBuf,MAX_LEN,fp);
		while(strncmp("Mem:",lineBuf,4) != 0)
			fgets(lineBuf,MAX_LEN,fp);
		sscanf(lineBuf,"%s%d%d",junk,&total,&used);
		printf("Total Memory\t: %dK\n",total/1024);
		printf("Free Memory\t: %dK\n",(total-used)/1024);
		fclose(fp);
	}

/* Print a list of load averages */
	if ((fp = fopen("/proc/loadavg","r")) == NULL)
	{
		printf("read: can't open file\n");
		exit(1);
	}
	else
	{
		printf("Load Averages\t: ");
		for(i=0;i<duration;i+=interval)
		{
			fscanf(fp,"%s",load);
			printf("%s ",load);
			fclose(fp);
			sleep(interval);
			fp = fopen("/proc/loadavg","r");
		}
		printf("\n");
		fclose(fp);
	}
}
