/* 
   C-Version of gdplaytimefilter.pl
   gdplaytimefilter: Giant Disc play time filter
   reads play time state from mpg123 (stdin) and writes it to tmp/gdplaytime.txt

   we need to read the mpg123 status char by char. \r must be interpreted
   as line end (translation \r -> \n in a pipe with 'tr' is not possible,
   because tr writes buffered to stdout. But we need undelayed response.)
   Better ideas?


   The program takes as parameter the path+name of the playtime file to 
   write to.

 */

#include <stdio.h>
#include <stdlib.h>


main (int argc, char **argv)
{
  char line[500], *pos2, *pos3;
  int  chr, chrcnt, linelen, lineok, frames, framesrem;
  FILE *ptfile;

  if(argc != 2){
    printf("gdplaytimefilter takes as parameter the path+name of the playtime file\n");
    exit (-1);
  }
  //printf ("Play Time Filter started\n");

  //*** Get mpg123 verbose output
  while(1){
    linelen = 0;
    lineok  = 0;
    chrcnt  = 0;
    while ((chr=getchar()) != EOF){
      if (chrcnt==0 && chr == 'F') lineok=1;  // lines start with keyw "Frame#"
      if (chr == '\r' || chr == '\n') break;
      if (isdigit(chr) || chr == ' '){
      	line[linelen++] = chr;
      }
      chrcnt++;
    }
    line[linelen++] = '\0';
    if (chr == EOF) break;

    //printf("line recieved: %s \n", line);
    frames = 0;
    framesrem = 0;

    if (lineok){
      frames    = strtol(line, &pos2, 10);
      framesrem = strtol(pos2, &pos3, 10);
    }
      
    if (!(ptfile = fopen(argv[1], "w"))) 
      printf("ERROR: can't open out file", argv[1]);
    fprintf(ptfile, "%i\n%i\n", frames, framesrem);
    fclose(ptfile);
  }

  //printf ("Terminated: Playtime filter\n");
}

