/*--------------------------paramgen.c----------------------------
  This program is a utility to generate the text file which tells
  ppmtompeg what to do. This utility is used in mkmpeg.sh. This
  software was written by Stephen Jordan.
  ----------------------------------------------------------------*/

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

//changes the extension of a filename
void ext_change(char *name, char *ext) {
  int i, max;
  char *out_ext;
  char msg[256];
  out_ext = strrchr(name, '.');
  if(out_ext == NULL) {
    printf("Error, filename with no extension: %s\n", name);
    return;
  } //otherwise:
  i = 0;
  max = strlen(ext);
  for(i = 0; i < max; i++) out_ext[i+1] = ext[i];
  out_ext[i+1] = '\0';
}


char *bname(char *string) {
  char *filename;
  filename = strrchr(string, '/') + 1;
  printf("filename = %s\n", filename);
  return strchr(filename, '_') + 1;
}

int main(int argc, char *argv[]) {
  FILE *fp;
  char basename[256];
  char rawnum[8];
  char paddednum[8];
  int zeros, i;
  fp = fopen("movie.param", "w");
  if(fp == NULL) {
    printf("Unable to create movie.param\n");
    return EXIT_FAILURE;
  }
  sprintf(rawnum, "%i", argc-2);
  zeros = 4 - strlen(rawnum);
  paddednum[0] = '\0';
  for(i = 0; i < zeros; i++) strcat(paddednum, "0");
  strcat(paddednum, rawnum);
  strcpy(basename, bname(argv[1]));
  printf("basename = %s\n", basename);
  ext_change(basename, "mpg");
  fprintf(fp, "PATTERN IBBPBBPBBPBBPBB\n");
  fprintf(fp, "FORCE_ENCODE_LAST_FRAME\n");
  fprintf(fp, "OUTPUT ./%s\n", basename);
  fprintf(fp, "INPUT\n");
  ext_change(basename, "ppm");
  fprintf(fp, "*_%s [0000-%s]\n", basename, paddednum);
  fprintf(fp, "END_INPUT\n");
  fprintf(fp, "BASE_FILE_FORMAT PPM\n");
  fprintf(fp, "INPUT_DIR .\n");
  fprintf(fp, "INPUT_CONVERT *\n");
  fprintf(fp, "GOP_SIZE 100\n");
  fprintf(fp, "SLICES_PER_FRAME 1\n");
  fprintf(fp, "PIXEL HALF\n");
  fprintf(fp, "RANGE 32\n");
  fprintf(fp, "PSEARCH_ALG SUBSAMPLE\n");
  fprintf(fp, "BSEARCH_ALG CROSS2\n");
  fprintf(fp, "IQSCALE 8\n");
  fprintf(fp, "PQSCALE 11\n");
  fprintf(fp, "BQSCALE 25\n");
  fprintf(fp, "REFERENCE_FRAME DECODED\n");
  fclose(fp);
  return EXIT_SUCCESS;
}
