/*
Copyright (c) 2001-2010, Dirk Krause
All rights reserved.

Redistribution and use in source and binary forms,
with or without modification, are permitted provided
that the following conditions are met:

* Redistributions of source code must retain the above
  copyright notice, this list of conditions and the
  following disclaimer.
* Redistributions in binary form must reproduce the above 
  opyright notice, this list of conditions and the following
  disclaimer in the documentation and/or other materials
  provided with the distribution.
* Neither the name of the Dirk Krause nor the names of
  contributors may be used to endorse or promote
  products derived from this software without specific
  prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/

#include <stdio.h>

#include <dk.h>
#include <dksf.h>

#if DK_HAVE_STDLIB_H
#include <stdlib.h>
#endif
#if DK_HAVE_STRING_H
#include <string.h>
#endif
#if DK_HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif

static char inbuffer[16384];
static char outbuffer[16384];

size_t outbuffer_used = 0;

static void flush_buffer(void)
{
  fwrite(outbuffer, sizeof(char), outbuffer_used, stdout);
  outbuffer_used = 0;
}

static void add_char(char c)
{
  if(outbuffer_used >= (sizeof(outbuffer) - 1)) {
    flush_buffer();
  }
  outbuffer[outbuffer_used++] = c;
}

static void add_string(char *str)
{
  char *ptr;
  ptr = str;
  while(*ptr) { add_char(*(ptr++)); }
}

static char keyword[] = { "/MediaBox" };

static char space_string[] = { " " };
static char open_string[] = { "[" };
static char close_string[] = { "]" };
static char null_string[] = { "0" };

static char version[] = { "1.13" };

static int need_to_run(int argc, char *argv[])
{
  int back = 1;
  int need_help = 0;
  int need_version = 0;
  if(argc > 1) {
    if(strcmp(argv[1], "-h") == 0) {
      need_help = 1;
    }
    if(strcmp(argv[1], "--help") == 0) {
      need_help = 1;
    }
    if(strcmp(argv[1], "-v") == 0) {
      need_version = 1;
    }
    if(strcmp(argv[1], "--version") == 0) {
      need_version = 1;
    }
  }
  if(need_help || need_version) {
    back = 0;
  }
  if(need_help) {
    printf("\n");
    printf("pdfcmb - Change PDF /MediaBox entry\n");
    printf("-----------------------------------\n");
    printf("pdfcmb <x1> <y1> <x2> <y2>\n");
    printf("pdfcmb <w> <h>\n");
    printf("\n");
    printf("The program expects a PDF file as standard input.\n");
    printf("The first /MediaBox entry in the file is replaced\n");
    printf("by the values specified as arguments.\n");
    printf("The resulting PDF file is written to standard output.\n");
    printf("The exit-value is always 0.\n");
    printf("\n");
  }
  if(need_version) {
    printf("pdfcmb %s\n", version);
  }
  return back;
}

int main(int argc, char *argv[])
{
  int exval = 0;
  int kwlgt; int ende;
  char *ptr;
  size_t number_read;
  size_t i;
  int state;
  int number_of_found;
  int old_stdin_binary = 0;
  int old_stdout_binary = 0;

  if(need_to_run(argc, argv)) {
    /*
    (void)dksf_set_file_binary(stdin);
    (void)dksf_set_file_binary(stdout);
    */
    old_stdin_binary = dksf_fdesk_binary(0, 1);
    old_stdout_binary = dksf_fdesk_binary(1, 1);
    kwlgt = strlen(keyword);
    ende = 0; state = 0; number_of_found = 0;
    while(ende == 0) {
      number_read = fread(inbuffer, sizeof(char), sizeof(inbuffer), stdin);
      if(number_read > 0) {
        ptr = inbuffer;
        for(i = 0; i < number_read; i++) {
	  switch(state) {
	    case 0: {
	      add_char(*ptr);
	      if(*ptr == keyword[number_of_found]) {
	        number_of_found++;
	        if(number_of_found == kwlgt) {
		  state = 1;
		  switch(argc) {
		    case 3: {
		      add_string(space_string);
		      add_string(open_string);
		      add_string(null_string);
		      add_string(space_string);
		      add_string(null_string);
		      add_string(space_string);
		      add_string(argv[1]);
		      add_string(space_string);
		      add_string(argv[2]);
		      add_string(close_string);
		    } break;
		    case 5: {
		      add_string(space_string);
		      add_string(open_string);
		      add_string(argv[1]);
		      add_string(space_string);
		      add_string(argv[2]);
		      add_string(space_string);
		      add_string(argv[3]);
		      add_string(space_string);
		      add_string(argv[4]);
		      add_string(close_string);
		    } break;
		    default: {
		      state = 2;
		    } break;
		  }
	        }
	      } else {
	        number_of_found = 0;
	        if(*ptr == keyword[number_of_found]) {
		  number_of_found = 1;
	        }
	      }
	    } break;
	    case 1: {
	      if(*ptr == ']') {
	        state = 2;
	      }
	    } break;
	    case 2: {
	      add_char(*ptr);
	    } break;
	  }
	  ptr++;
        }
      } else {
        ende = 1;
      }
    }
    flush_buffer();
    (void)dksf_fdesk_binary(0, old_stdin_binary);
    (void)dksf_fdesk_binary(1, old_stdout_binary);
  }
  exit(exval); return exval;
}

