#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include <unistd.h>
#include <time.h>
#include <signal.h>


double fps;
FILE *f;

void readheader(void)
{
  char *item;
  char *a,*b,*c;
  int fpsn,fpsd;
  
  while(1) {
    if(fscanf(f,"%a[^\n]\n",&item) != 1) {
        break;
    }
    if(item[0]==0x1b) {
        free(item);
        break;
    }

    if(!strncmp(item,"VL rate is ",11)) {
      a = b = &item[11];
      while(*++b != '/');
      *b = 0;
      c = b++;
      while(*++c != ' ');
      *c = 0;
      fpsn = atoi(a);
      fpsd = atoi(b);
      fps = (double)fpsn/(double)fpsd;
      printf("Frame rate: %0.2f FPS\n",fps);
    }
    free(item);
  }
}

void usage(char *argv0)
{
   printf("ASCIIplay, ascii art video player\n");
   printf("Usage: %s file.ascii\n",argv0);
   exit(1);
}

void frame(void)
{
  char lc[3]={0,0,0};
  int lcp = 0;
  int c;
  char c2;
  while(1) {
    c = getc(f);
    if(c==EOF)
        return;
    
    c2 = (char)c;
    lc[lcp++] = c2;
    if(lcp >= 3) lcp = 0;
    putchar(c2);
    if(lc[0] == '\n' && lc[1] == '\n' && lc[2] == '\n') {
        return;
    }
  }
}

void inthandler (int signum) {
    printf("%s","\033c");
    fflush(stdout);
    exit(4);
}

int main(int argc, char **argv) {
    int nps;
    struct sigaction sa;
    
    struct timespec t;
    
    if(argc != 2) {
        usage(argv[0]);
    }
    printf("Playing file '%s'\n",argv[1]);
    f = fopen(argv[1],"r");
    readheader();
    rewind(f);
    while(fgetc(f) != 0x1b);
    fseek(f,-1,SEEK_CUR);
    
    nps = (int)(1000000000.0/fps);
    t.tv_nsec = nps;
    t.tv_sec = 0;
    
    sa.sa_handler = inthandler;
    sigemptyset (&sa.sa_mask);
    sa.sa_flags = 0;
    
    printf("Press enter to start movie\n");
    getchar();
    sigaction(SIGINT,&sa,NULL);
    fflush(stdout);
    
    while(!feof(f)) {
        frame();
        nanosleep(&t,NULL);
    }
    printf("\033cThat was all, folks\n");
    return 0;
}

