/*
 *  Copyright (C) 2008  Robert Millan
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <err.h>

int
main (int argc, char *argv[])
{
  unsigned int offset, prev_offset = 0;
  unsigned int native_value;
  int fd;
  uint8_t value[3];
  char type;
  char *line = NULL;
  size_t zero = 0;

  if (argc != 2)
    {
      fprintf (stderr, "Usage: %s output < input\n", argv[0]);
      exit (1);
    }

  fd = open (argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0644);

  while (getline (&line, &zero, stdin) != -1)
    {
      sscanf (line, "%c ", &type);

      if (type != 'P')
	continue;

      sscanf (line + 2, "%x %x\n", &offset, &native_value);

      value[0] = (native_value >> 16) & 0xff;
      value[1] = (native_value >> 8) & 0xff;
      value[2] = native_value & 0xff;

      /* FIXME: Needed for linux/drivers/char/dsp56k.c.  Is this correct?  */
      if (offset > 0x7000)
        offset = prev_offset + 1;
      
      if (pwrite (fd, value, 3, (off_t) (offset * 3)) < 0)
	err (1, "Failed to write %s", argv[1]);

      prev_offset = offset;
    }

  close (fd);

  exit (0);
}
