/*------------------------------------------------------------------------------
 src/lib/djImage/imageIoPpm.cxx
 
 Copyright (c) 2004-2006 Darby Johnston.
 All rights reserved.
 Use is subject to license terms.
------------------------------------------------------------------------------*/

//#define DJ_DBG
#include "djImageIoPpm.h"
#include <stdio.h>

namespace dj {
namespace ImageIoPpm {

bool getWord(FileIo * f, char * out, int maxStrLen)
{
  DJ_ASSERT(maxStrLen);
  
  //DJ_DBG_FNC("djImageIoPpm::getWord");
  //DJ_DBG_PRN("max string length = " << maxStrLen);
  
  bool r = true;
  
  out[0] = '\0';
  int parse = 1, i = 0;
  while (parse) {
    //DJ_DBG_PRN("parse = " << parse);
    //DJ_DBG_PRN("i = " << i);

    // Get next character.
    //
    uint8_t c;
    if (! f->get(&c, 1)) {
      r = false;
      break;
    }
    //DJ_DBG_PRN("c = \'" << QChar(c) << "\'");
    
    switch (c) {

      // Start comment.
      //
      case '#': parse = 2; break;

      // End comment or word.
      //
      case '\0':
      case '\n':
      case 15: parse = 1;
      case ' ':
      case '\t': if (out[0]) parse = 0; break;

      // Add character to word.
      //
      default:
        if (1 == parse && i < (maxStrLen - 1)) {
          out[i++] = c;
          //out[i] = '\0';
          //DJ_DBG_PRN("out = \"" << out << "\"");
        }
        break;
    }
  }
  out[i] = '\0';
  //DJ_DBG_PRN("out = \"" << out << "\"");
  
  return out[0] && r;
}

int atoi(const char * in, int maxStrLen)
{
  int out = 0;
  while (*in && maxStrLen--) {
    out *= 10;
    out += *in++ - '0';
  }
  return out;
}

}
}
