/*
 * getlength - a small tool to get the length of a VDR recording by the size
 * of the file index.vdr / index
 *
 * (c) by Martin Prochnow
 * Distributed under the terms of the GPL v2.0 (see COPYING at the root dir of
 * this archive).
 *
 * Compile with: gcc getlength.c -o getlength
 *
 * Usage: 'getlength' if index.vdr is in the current working directory or
          'getlength /PATH/TO/RECDIR/' else
 */

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdlib.h>


int getIndexFileSize(char *dirname) {
 int res=0;
 char *filename;
 int hasindex;
 struct stat status;

 asprintf(&filename,"%sindex",dirname);
 hasindex=!access(filename,R_OK);
 if(!hasindex) {
  free(filename);
  asprintf(&filename,"%sindex.vdr",dirname);
  hasindex=!access(filename,R_OK);
 }
 if(hasindex) {
  stat(filename,&status);
  res=status.st_size;
 } else {
  perror("Error while open index or index.vdr");
  free(filename);
  exit(-1);
 }
 free(filename);
 return res;
}


int getFramerate(char *dirname) {
 int res=25;
 char *filename;
 FILE *f;
 char *buffer=NULL;
 size_t size;
 int n, bFound=0;
 
 asprintf(&filename,"%sinfo",dirname);
 if((f=fopen(filename,"r"))==NULL) {
  free(filename);
  asprintf(&filename,"%sinfo.vdr",dirname);
  f=fopen(filename,"r");
 }
 
 if(f!=NULL) {
  do {
   n = getline(&buffer, &size, f);
   if( (n>-1) && !strncasecmp(buffer, "F ", 2)) {
    res=atoi(buffer+2);
	bFound=1;
   }
   free(buffer);
   buffer=NULL;
  } while ((n>-1) && (!bFound));
  
  fclose(f);
 }
  free(filename);
 return res;
}



int main(int argc,char **argv)
{
 char *dirname;
 char *filename;
 int size,framerate,length;
 FILE *out;

  switch(argc)
  {
  case 1: asprintf(&dirname,"./");break;
  case 2: asprintf(&dirname,"%s/",argv[1]);break;
  default: fprintf(stderr,"Usage:\ngetlength [PATH/TO/index[.vdr]]\n");exit(-1);
  }
 
 size=getIndexFileSize(dirname);
 framerate=getFramerate(dirname);
 length=( (size / 8 / framerate) + 30 ) / 60;
 
 asprintf(&filename,"%slength.vdr",dirname);
  if((out=fopen(filename,"w"))!=NULL)
  {
   fprintf(out,"%d\n",length);
   fclose(out);
  }
  else
  {
   perror("Error while open length.vdr");
   free(filename);
   exit(-1);
  }

 free(filename);
 return 0;
}
