#include "sgml.hh"
#include "skip-t.hh"
#include "clone_ptr-t.hh"
#include "ctype.h"

#include <iostream>

namespace afilter {

  template <typename T>
  SgmlSkip<T>::SgmlSkip(ConfigData & opts) 
    : in_markup(false), in_quote(false), new_token(false), in_what(InOther) 
  {
    opts.retrieve_list("sgml-check", *noskip_tags);
  }

  template <typename T>
  bool SgmlSkip<T>::skip(char c, const Itr *) {
    if (!in_quote)
      if (c == '<') {
	in_markup = true;
	in_what = InKey;
	new_token = true;
	tag_name = "";
	return true;
      } else if (c == '>') {
	in_markup = false;
	return true;
      }

    if (!in_markup)
      return false;
  
    if (c == '"' || c == '\'') {

      if (!in_quote)
	in_quote = c;
      else if (in_quote == c)
	in_quote = 0;
    
    } else if (!in_quote && isspace(c)) {
    
      if (!new_token) {
	in_what = InKey;
	new_token = true;
      }
    
    } else if (!in_quote && c == '=') {

      if (noskip_tags->have(parm_name.c_str()))
	in_what = InValueNoSkip;
      else
	in_what = InValue;
      new_token = true;
      return true;
    
    } else if (!in_quote && c == '/') {
    
      in_what = InOther;
    
    } else if (in_what == InKey) {

      if (new_token) {
	if (tag_name.empty()) tag_name = parm_name;
	parm_name = "";
	new_token = false;
      }
      parm_name += tolower(c);

    } else if (in_what == InValue || in_what == InValueNoSkip) {
      
      new_token = false;
      
    }
  
    return in_what != InValueNoSkip;
  }
}
