#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <dirent.h>
#include <linux/input.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/select.h>
#include <sys/time.h>
#include <termios.h>
#include <signal.h>
 

void perror_exit(char *error)
{
    perror(error);
    printf("\nexiting...(%d)\n", 9);
    exit(0);
}
 
int main(int argc, char *argv[])
{
    uint32_t counter;
    struct input_event ev[64];
    int fd, rd, value;
    int size = sizeof(struct input_event);
    char name[256] = "Unknown";
    char *device = NULL;
    
    FILE *out_file; 
     
    // Make sure the user is root
    if ((getuid ()) != 0) 
    {
        printf ("\nYou must be root to display keypress counts.\n\n");
        exit(0);
    }
 
    // Setup check
    if (argv[1] == NULL)
    {
        printf("Please specify (on the command line) the path to the dev event interface device\n");
        exit(0);
    }

    if (argc > 1)
    {
        device = argv[1];   
    }
 
    if (argc > 2) 
    {
        out_file = fopen(argv[2], "w");
        if (out_file == NULL)
        {
            printf("Unable to open file %s", argv[2]);
            exit(0);
        }
    }
    
    // Open specified device
    if ((fd = open (device, O_RDONLY)) == -1) 
    {
        printf("%s is not a vaild device.\n", device);
        exit(0);
    }
    
    // Print device name
    //ioctl (fd, EVIOCGNAME(sizeof(name)), name);
    //printf ("Reading From : %s (%s)\n", device, name);
    
    // Main loop, read
    counter = 0;
    while(1)
    {
        if ((rd = read(fd, ev, size * 64)) < size) 
        {
            perror_exit("read()");
        }
    
        value = ev[0].value;
    
        // Only read the key press event
        if (value != ' ' && ev[1].value == 1 && ev[1].type == 1)
        { 
            counter++;
            
            // If a filename was given, output to that file
            if (argc > 2)
            {
                // Seek to beginning of file, output and flush to file
                fseek(out_file, 0, SEEK_SET);
                fprintf(out_file, "%10u", counter);
                fflush(out_file);
            } 
            else
            {
                // Otherwise print to stdout
                // Print count, fixed width of 10 spaces, over of the same line                
                printf("\r%10u", counter);
                fflush(stdout);
            }
            
            // Check for (hopefully rare) overflow condition
            if (counter == UINT32_MAX)
            {
                printf("\nGADZOOKS BATMAN!!! You overflowed a 32 bit unsigned integer with all your keystrokes!\n\n");
                counter = 0;
            }
        }
    }
    
    fclose(out_file);
    return 0;
}
