#ifndef __cmt_awk_h__
#define __cmt_awk_h__

#include "cmt_std.h"
#include "cmt_string.h"
#include "cmt_regexp.h"

//------------------------------------------------
//
//  Emulation of the awk program.
//
//  The run method reads the specified file, and applies the
// <filter> virtual method onto each selected line. It returns
// a condition (see below)
//
//  o empty lines are ignored
//  o when the optional pattern is specified, only lines matching it
//    are considered.
//
//  The virtual <begin> method is applied before any filter
//  The virtual <filter> method is applied onto each line
//  The virtual <end> method is applied after all filters
//
//  The condition (one of "ok", "stopped" or "failed") will be
//  generated if :
//    o everything run well (ok)
//    o the <stop> method is called (stopped)
//    o an error occurred or the <abort> method is called (failed)
//
//  State variables are maintained for derived awk filters
//
//    m_line_number  the current line number (empty lines
//                   are counted)
//
//    m_continuation_allowed when true, take into account the
//                           trailing backslashes, so as to
//                           first accumulate continued lines 
//                           into one
//
//  Derived classes:
//  ----------------
//
//  FAwk : scans a file
//
//    State variables:
//
//    m_dir_name     the path of the currently read file
//    m_file_name    the name of the currently read file
//
//  PAwk : execute a command and scans its output
//
//------------------------------------------------
class Awk
{
public:
  typedef enum {ok, stopped, failed} condition;
  Awk ();
  virtual ~Awk ();
  condition run (const cmt_string& text, const cmt_string& pattern = "");
  condition run (const cmt_string& text, const cmt_regexp& expression);
  void stop ();
  void abort ();
  void allow_continuation ();
  condition get_last_condition () const;

  virtual void begin ();
  virtual void filter (const cmt_string& line);
  virtual void end ();
protected:
  int m_line_number;
  condition m_condition;
  bool m_continuation_allowed;
};

class FAwk : public Awk
{
public:
  condition run (const cmt_string& file_name, const cmt_string& pattern = "");
  condition run (const cmt_string& text, const cmt_regexp& expression);
protected:
  cmt_string m_dir_name;
  cmt_string m_file_name;
};

class PAwk : public Awk
{
public:
  condition run (const cmt_string& command, const cmt_string& pattern = "");
  condition run (const cmt_string& text, const cmt_regexp& expression);
};

#endif
