#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <string.h>
#include <math.h>


unsigned char loadbar(const char *load)
{
float fload=0;
unsigned char tmpload;
static unsigned char blink=127;

  sscanf(load,"%f",&fload);
  if (fload>=1) {
    fload=1;
    if (blink==127)
      blink=255;
    else
      blink=127;
  }
  tmpload=pow(2,(unsigned int)(fload*8))-1;
  tmpload=tmpload & blink;
  return(tmpload);
}


int main(int argc, char **argv)
{
char buf[30],buf2[30];
char *bp;
unsigned char lload;
int fd,led,bla,wtime=1;

  if (argc>0 && argv[1]!=NULL) wtime=atoi(argv[1]);
  led=open("/dev/led",O_WRONLY);
  if (led==-1) {
    printf("Could not open LED device /dev/led\n");
    exit(-1);
  }
  while(1) {
    fd=open("/proc/loadavg",O_RDONLY);
    if (fd==-1) {
      fprintf(stderr,"Could not open /proc/loadavg\n");
      exit(-1);
    }
    bla=read(fd,buf,255);
    close(fd);
    buf[bla-1]='\0';
    if ((bp=strtok(buf," "))!=NULL) strcpy(buf2,bp);
    lload=loadbar(buf2);
    write(led,&lload,1);
    sleep(wtime);
  }
  close(led);
return(0);
}
