Index: trunk/configure.ac
===================================================================
--- trunk/configure.ac	(revision 103)
+++ trunk/configure.ac	(revision 1)
@@ -1,9 +1,8 @@
-AC_INIT([DRMAA for PBS Pro], [1.0.19], [qcg@plgrid.pl], [pbs-drmaa])
+AC_INIT([DRMAA for PBS Pro], [1.0.4], [mamonski@man.poznan.pl], [pbs_drmaa])
 AC_PREREQ(2.59)
-AC_REVISION([$Id$])
+AC_REVISION([$Id: configure.ac 2694 2009-09-12 17:17:35Z mmamonski $])
 AC_COPYRIGHT([
-DRMAA for Torque/PBS Professional
+DRMAA for PBS Pro
 Copyright (C) 2006-2009  FedStage Systems
-Copyright (C) 2011-2013  Poznan Supercomputing and Networking Center
 
 This program is free software: you can redistribute it and/or modify
@@ -23,6 +22,6 @@
 PBS_DRMAA_MAJOR=1
 PBS_DRMAA_MINOR=0
-PBS_DRMAA_MICRO=19
-PBS_DRMAA_VERSION_INFO=1:19:0
+PBS_DRMAA_MICRO=4
+PBS_DRMAA_VERSION_INFO=1:4:0
 AC_SUBST([PBS_DRMAA_MAJOR])
 AC_SUBST([PBS_DRMAA_MINOR])
@@ -40,9 +39,8 @@
 			[produce code suiteable for debugging and print logs at runtime]))
 AC_ARG_ENABLE(development, AC_HELP_STRING([--enable-development],
-			[enable development mode: make additional checks (suiteable for developers)]))
+			[enable development mode: make additional checks (suiteable for FedStage DRMAA for PBS Pro developers)]))
 
 # programs:
 AC_PROG_CC
-AC_PROG_CXX
 AC_PROG_CPP
 AC_PROG_RANLIB
@@ -54,4 +52,13 @@
 # code generation tools:
 AX_GPERF
+
+# reStructuredText processing:
+AX_DOCUTILS()
+if test x$RST2HTML = x; then
+	RST2HTML="sh m4/missing-dev-prog.sh docutils"
+fi
+if test x$RST2LATEX = x; then
+	RST2LATEX="sh m4/missing-dev-prog.sh docutils"
+fi
 
 # check compiler / set basic flags:
@@ -116,4 +123,8 @@
 PBS libraries/headers not found;
 add --with-pbs to set PBS installation root.]) ])
+if test ${sysconfdir} == '${prefix}/etc' -a "$prefix" == 'NONE'; then
+	sysconfdir='/etc'
+	ac_configure_args="${ac_configure_args} --sysconfdir=${sysconfdir}"
+fi
 CPPFLAGS="${CPPFLAGS} -DCONFDIR=${sysconfdir}"
 
@@ -144,4 +155,5 @@
 	localtime_r \
 	memset \
+	mkstemp \
 	setenv \
 	strcasecmp \
@@ -169,4 +181,5 @@
 	Makefile
 	pbs_drmaa/Makefile
+	doc/Makefile
 ])
 AC_CONFIG_HEADERS([config.h])
Index: trunk/drmaa_utils/COPYING
===================================================================
--- trunk/drmaa_utils/COPYING	(revision 1)
+++ trunk/drmaa_utils/COPYING	(revision 1)
@@ -0,0 +1,674 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    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/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
Index: trunk/drmaa_utils/Doxyfile.in
===================================================================
--- trunk/drmaa_utils/Doxyfile.in	(revision 1)
+++ trunk/drmaa_utils/Doxyfile.in	(revision 1)
@@ -0,0 +1,30 @@
+PROJECT_NAME           = "@PACKAGE_NAME@"
+PROJECT_NUMBER         = @PACKAGE_VERSION@
+INPUT                  = @top_srcdir@/drmaa_utils
+EXCLUDE                = \
+ @top_srcdir@/drmaa_utils/datetime_tab.c \
+ @top_srcdir@/drmaa_utils/datetime_tab.h \
+ @top_srcdir@/drmaa_utils/conf_tab.c \
+ @top_srcdir@/drmaa_utils/conf_tab.h \
+ @top_srcdir@/drmaa_utils/drmaa_attrib.c
+OUTPUT_DIRECTORY       = apidoc
+
+ENABLE_PREPROCESSING   = YES
+PREDEFINED             = __GNUC__
+
+JAVADOC_AUTOBRIEF      = YES
+EXTRACT_ALL            = NO
+HIDE_UNDOC_MEMBERS     = NO
+SORT_BRIEF_DOCS        = NO
+SORT_MEMBER_DOCS       = NO
+DETAILS_AT_TOP         = YES
+OPTIMIZE_OUTPUT_FOR_C  = YES
+TAB_SIZE               = 2
+GENERATE_TODOLIST      = YES
+SHOW_DIRECTORIES       = NO
+
+HAVE_DOT               = @HAVE_DOT@
+CALL_GRAPH             = YES
+
+GENERATE_HTML          = YES
+GENERATE_LATEX         = NO
Index: trunk/drmaa_utils/Makefile.am
===================================================================
--- trunk/drmaa_utils/Makefile.am	(revision 1)
+++ trunk/drmaa_utils/Makefile.am	(revision 1)
@@ -0,0 +1,28 @@
+# $Id: Makefile.am 2248 2009-03-20 14:20:56Z lukasz $
+#
+# FedStage DRMAA utilities library
+# Copyright (C) 2006-2008  FedStage Systems
+#
+# 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/>.
+#
+
+ACLOCAL_AMFLAGS = -I m4
+EXTRA_DIST = \
+ autoclean.sh \
+ autogen.sh \
+ m4/bison_ylwrap.sh \
+ m4/missing-dev-prog.sh
+
+SUBDIRS = drmaa_utils test
+
Index: trunk/drmaa_utils/autogen.sh
===================================================================
--- trunk/drmaa_utils/autogen.sh	(revision 1)
+++ trunk/drmaa_utils/autogen.sh	(revision 1)
@@ -0,0 +1,48 @@
+#!/bin/sh
+# $Id: autogen.sh 1656 2008-11-18 17:11:58Z lukasz $
+
+run() {
+	echo "running $@ ($PWD)"
+	eval "$@"
+}
+
+check()
+{
+	printf "checking for $1... "
+	if ($1 --version < /dev/null > /dev/null 2>&1); then
+		echo "yes"
+	else
+		echo "no"
+		exit 1
+	fi
+}
+
+ACLOCAL=${ACLOCAL:=aclocal}
+AUTOHEADER=${AUTOHEADER:=autoheader}
+AUTOCONF=${AUTOCONF:=autoconf}
+LIBTOOLIZE=${LIBTOOLIZE:=libtoolize}
+AUTOMAKE=${AUTOMAKE:=automake}
+
+check $ACLOCAL
+check $AUTOHEADER
+check $AUTOCONF
+check $LIBTOOLIZE
+check $AUTOMAKE
+
+mkdir -p scripts
+
+run ${ACLOCAL} -I m4 | grep -v ^/usr/share/aclocal || exit 1
+run ${LIBTOOLIZE} --automake --copy --force || exit 1
+run ${AUTOHEADER} --warnings=all || exit 1
+run ${AUTOMAKE} --foreign --add-missing --copy --warnings=all || exit 1
+run ${AUTOCONF} --warnings=all -Wno-obsolete || exit 1
+
+if [ -n "$*" ]; then
+	args="$*"
+elif [ -f config.log ]; then
+	args=`grep '\$ *\./configure ' config.log \
+			 | sed 's:^ *\$ *\./configure ::;s:--no-create::;s:--no-recursion::' \
+			 2>/dev/null`
+fi
+
+run ./configure ${args}
Index: trunk/drmaa_utils/.boring
===================================================================
--- trunk/drmaa_utils/.boring	(revision 1)
+++ trunk/drmaa_utils/.boring	(revision 1)
@@ -0,0 +1,49 @@
+# Project specific:
+^drmaa_utils/conf_tab.c$
+^drmaa_utils/conf_tab.h$
+^drmaa_utils/datetime_tab.c$
+^drmaa_utils/datetime_tab.h$
+^drmaa_utils/drmaa_attrib.c$
+^test/test_exception$
+
+# Autotools:
+^configure$
+(^|/)config\.(log|status)$
+^scripts$
+^aclocal\.m4$
+(^|/)autom4te\.cache($|/)
+^config\.h(\.in)?$
+^stamp-h1$
+(^|/)Makefile(\.in)?$
+(^|/)\.(deps|libs)$
+^libtool$
+
+# Boring file regexps:
+^project/project.py$
+^test-results($|/)
+\.(o|obj|a|exe|so|lo|loT|la)$
+\.py[co]$
+\.class$
+(^|/)RCS($|/)
+,v$
+(^|/)CVS($|/)
+\.cvsignore$
+^\.#
+(^|/)\.svn($|/)
+(^|/)\.hg($|/)
+(^|/)\.git($|/)
+(^|/)\.bzr($|/)
+(^|/)BitKeeper($|/)
+(^|/)_darcs($|/)
+^\.darcs-temp-mail$
+-darcs-backup[[:digit:]]+$
+^\.darcs-temp-mail$
+^darcs-amend-record-[0-9]+$
+\.bak$
+\.BAK$
+\.orig$
+\.swp$
+(^|/|\.)core$
+(^|/)(tags|TAGS)$
+(^|/)Thumbs\.db$
+
Index: trunk/drmaa_utils/test/Makefile.am
===================================================================
--- trunk/drmaa_utils/test/Makefile.am	(revision 1)
+++ trunk/drmaa_utils/test/Makefile.am	(revision 1)
@@ -0,0 +1,26 @@
+# $Id: Makefile.am 1509 2008-10-12 14:21:23Z mmamonski $
+#
+# FedStage DRMAA utilities library
+# Copyright (C) 2006-2008  FedStage Systems
+#
+# 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/>.
+#
+
+
+LDADD = $(top_builddir)/drmaa_utils/libdrmaa_utils.la
+AM_CPPFLAGS = -DDEBUG
+
+TESTS = exception_test
+check_PROGRAMS = $(TESTS)
+
Index: trunk/drmaa_utils/test/run.py
===================================================================
--- trunk/drmaa_utils/test/run.py	(revision 1)
+++ trunk/drmaa_utils/test/run.py	(revision 1)
@@ -0,0 +1,53 @@
+
+import subprocess
+from os.path import join, dirname
+
+valid_outputs = [
+"""\
+try
+after try
+""",
+
+"""\
+try
+else
+finally
+""",
+
+"""\
+try
+except: Invalid argument value.
+finally
+""",
+
+"""\
+runner: before
+inner try
+inner finally
+except: Invalid argument value.
+finally
+runner: except: Invalid argument value.
+""",
+
+"""\
+runner: before
+except: Invalid argument value.
+finally
+runner: except: Unexpected or internal error.
+""",
+]
+
+
+def check_output(test_no):
+	executable = join(dirname(__file__), "test_exception")
+	p = subprocess.Popen(
+			args=[executable, str(test_no)],
+			stdout=subprocess.PIPE,
+			)
+	output = p.communicate()[0]
+	assert output == valid_outputs[test_no]
+
+def test_exception():
+	for i in range(5):
+		yield check_output, i
+
Index: trunk/drmaa_utils/test/exception_test.c
===================================================================
--- trunk/drmaa_utils/test/exception_test.c	(revision 1)
+++ trunk/drmaa_utils/test/exception_test.c	(revision 1)
@@ -0,0 +1,184 @@
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <assert.h>
+
+#include <drmaa_utils/common.h>
+
+
+void
+raise_ex( int err_code )
+{
+	fsd_exc_raise_code( err_code );
+	printf( "after raise\n" );
+	assert(0);
+}
+
+
+void
+runner( void (*function)(void) )
+{
+	int volatile in_except_default_block = 0;
+	TRY
+	 {
+		printf( "runner: before\n" );
+		function();
+		printf( "runner: after\n" );
+		assert(0);
+	 }
+	EXCEPT_DEFAULT
+	 {
+		printf( "runner: except: %s\n", fsd_exc_get()->_message );
+		in_except_default_block = 1;
+	 }
+	END_TRY
+	
+	assert(in_except_default_block);
+}
+
+
+void test_0(void)
+{
+	TRY
+	 { printf( "try\n" ); }
+	EXCEPT( FSD_ERRNO_INVALID_VALUE )
+	 { 
+	    printf( "except\n" ); 
+		assert(0);
+	 }
+	END_TRY
+	printf( "after try\n" );
+	printf( "test finished.\n" );
+}
+
+
+void test_1(void)
+{
+
+	int volatile in_else = 0;
+	int volatile in_finally = 0;
+	TRY
+	 { printf( "try\n" ); }
+	EXCEPT_DEFAULT
+	 { printf( "except\n" ); assert(0); }
+	ELSE
+	 { printf( "else\n" ); in_else = 1; }
+	FINALLY
+	 { printf( "finally\n" ); in_finally = 1; }
+	END_TRY
+			
+	assert(in_else);
+	assert(in_finally);
+	printf( "test finished.\n" );
+}
+
+
+void test_2(void)
+{
+	int volatile in_except = 0;
+	int volatile in_finally = 0;
+	TRY
+	 {
+		printf( "try\n" );
+		raise_ex( FSD_ERRNO_INVALID_VALUE );
+		assert(0);
+	 }
+	EXCEPT_DEFAULT
+	 {
+		printf( "except: %s\n", fsd_exc_get()->_message );
+		in_except = 1;
+	 }
+	FINALLY
+	 {
+		printf( "finally\n" );
+		in_finally = 1;
+	 }
+	END_TRY
+	
+	assert(in_except);
+	assert(in_finally);
+	printf("test finished\n");
+}
+
+
+void test_3(void)
+{
+	int volatile  blocks_counter = 0;
+	TRY
+	 {
+		TRY
+		 {
+			blocks_counter++;
+			printf( "inner try\n" );
+			raise_ex( FSD_ERRNO_INVALID_VALUE );
+			assert(0);
+		 }
+		FINALLY
+		 {
+			blocks_counter++;
+			printf( "inner finally\n" );
+		 }
+		END_TRY
+		printf( "after\n" );
+		assert(0);
+	 }
+	EXCEPT_DEFAULT
+	 {
+	    blocks_counter++;
+		printf( "except: %s\n", fsd_exc_get()->_message );
+		fsd_exc_reraise();
+	 }
+	ELSE
+	 { printf( "else\n" ); assert(0); }
+	FINALLY
+	 {
+		printf( "finally\n" );
+		blocks_counter++;
+		assert(blocks_counter == 4);
+	 }
+	END_TRY
+	
+	assert(0);
+}
+
+
+void test_4(void)
+{
+	TRY
+	 {
+		raise_ex( FSD_ERRNO_INVALID_VALUE );
+		assert(0);
+	 }
+	EXCEPT( FSD_ERRNO_INVALID_VALUE )
+	 { printf( "except: %s\n", fsd_exc_get()->_message ); }
+	EXCEPT_DEFAULT
+	 { printf( "except_default: %s\n", fsd_exc_get()->_message ); assert(0); }
+	FINALLY
+	 {
+		printf( "finally\n" );
+		raise_ex( FSD_ERRNO_INTERNAL_ERROR );
+	 }
+	END_TRY
+			
+	assert(0);
+}
+
+
+int
+main( int argc, char *argv[] )
+{
+	printf("Running Test 0\n");
+	test_0();  
+	printf("Running Test 1\n");
+	test_1();
+	printf("Running Test 2\n");
+	test_2();  
+	printf("Running Test 3\n");
+	runner( test_3 );
+	printf("Running Test 4\n");
+	runner( test_4 );
+	printf("All tests done.\n");
+
+	return 0;
+}
+
Index: trunk/drmaa_utils/m4/ax_gperf.m4
===================================================================
--- trunk/drmaa_utils/m4/ax_gperf.m4	(revision 1)
+++ trunk/drmaa_utils/m4/ax_gperf.m4	(revision 1)
@@ -0,0 +1,60 @@
+# $Id$
+#
+# SYNOPSIS
+#
+#   AX_GPERF([ACTION-IF-FOUND[, [ACTION-IF-NOT-FOUND]])
+#
+# DESCRIPTION
+#
+#   Test for Gperf perfect hash function generator binary.
+#   When not found GPERF is set with location of fallback
+#   script which prints error message and exits with non-zero
+#   error code.
+#
+#   This macro calls::
+#
+#     AC_SUBST(GPERF)
+#
+# LAST MODIFICATION
+#
+#   2007-12-14
+#
+# LICENSE
+#
+#   Written by Åukasz CieÅnik <lukasz.ciesnik@fedstage.com>
+#   and placed under Public Domain
+#
+
+AC_DEFUN([AX_GPERF], [
+	AC_MSG_CHECKING([for gperf])
+	if { echo a; echo b; echo c; } | gperf >/dev/null 2>&1; then
+		ax_prog_gperf_ok=yes
+		GPERF=gperf
+	else
+		if echo $srcdir | grep -q "^/"; then
+			abs_srcdir="$srcdir"
+		else
+			abs_srcdir="`pwd`/$srcdir"
+		fi
+		GPERF="${abs_builddir}/scripts/gperf-fallback.sh"
+		cat >$GPERF <<EOF
+#!/bin/sh
+cat >&2 <<MESSAGE
+ * ERROR: gperf was not found at configuration time while some sources are
+ * build by it.  Either install gperf <http://www.gnu.org/software/gperf/>
+ * or download tarball with generated sources included (than you will
+ * not be able to modify .gperf files).
+MESSAGE
+exit 1
+EOF
+		chmod +x $GPERF
+		ax_prog_gperf_ok=no
+	fi
+	AC_SUBST(GPERF)
+	AC_MSG_RESULT([$ax_prog_gperf_ok])
+	if test x$ax_prog_gperf_ok = xyes; then
+		ifelse([$1], , :, [$1])
+	else
+		ifelse([$2], , :, [$2])
+	fi
+])
Index: trunk/drmaa_utils/m4/ax_gcc_warnings.m4
===================================================================
--- trunk/drmaa_utils/m4/ax_gcc_warnings.m4	(revision 1)
+++ trunk/drmaa_utils/m4/ax_gcc_warnings.m4	(revision 1)
@@ -0,0 +1,50 @@
+# $Id: ax_gcc_warnings.m4 1542 2008-10-21 12:00:09Z lukasz $
+#
+# SYNOPSIS
+#
+#   AX_GCC_FLAGS()
+#
+# DESCRIPTION
+#
+#   Check for LSF libraries and headers.
+#
+#   This macro calls::
+#
+#			AC_SUBST(GCC_W_NO_MISSING_FIELD_INITIALIZERS)
+#			AC_SUBST(GCC_W_NO_FORMAT_ZERO_LENGTH)
+#
+# LAST MODIFICATION
+#
+#   2008-10-13
+#
+# LICENSE
+#
+#   Written by Åukasz CieÅnik <lukasz.ciesnik@fedstage.com>
+#   and placed under Public Domain.
+#
+AC_DEFUN([AX_GCC_WARNINGS], [
+if test x$GCC == xyes; then
+	AC_SUBST([GCC_W_NO_MISSING_FIELD_INITIALIZERS])
+	AC_SUBST([GCC_W_NO_FORMAT_ZERO_LENGTH])
+	CFLAGS_save="$CFLAGS"
+
+	AC_MSG_CHECKING([whether gcc accepts -Wno-missing-field-initializers])
+	CFLAGS="$CFLAGS_save -Wall -Wextra -Wno-missing-field-initializers"
+	ax_gcc_warnings_src="int main(){ return 0; }"
+	AC_COMPILE_IFELSE([$ax_gcc_warnings_src],
+		[GCC_W_NO_MISSING_FIELD_INITIALIZERS="-Wno-missing-field-initializers"
+		AC_MSG_RESULT([yes])],
+		[GCC_W_NO_MISSING_FIELD_INITIALIZERS="-Wno-extra"
+		AC_MSG_RESULT([no])])
+
+	AC_MSG_CHECKING([whether gcc accepts -Wno-format-zero-length])
+	CFLAGS="$CFLAGS_save -Wno-format-zero-length"
+	AC_COMPILE_IFELSE([$ax_gcc_warnings_src],
+		[GCC_W_NO_FORMAT_ZERO_LENGTH="-Wno-format-zero-length"
+		AC_MSG_RESULT([yes])],
+		[GCC_W_NO_FORMAT_ZERO_LENGTH="-Wno-format"
+		AC_MSG_RESULT([no])])
+
+	CFLAGS="$CFLAGS_save"
+fi
+])
Index: trunk/drmaa_utils/m4/ac_c_bigendian_cross.m4
===================================================================
--- trunk/drmaa_utils/m4/ac_c_bigendian_cross.m4	(revision 1)
+++ trunk/drmaa_utils/m4/ac_c_bigendian_cross.m4	(revision 1)
@@ -0,0 +1,86 @@
+dnl @synopsis AC_C_BIGENDIAN_CROSS
+dnl
+dnl Check endianess even when crosscompiling (partially based on the
+dnl original AC_C_BIGENDIAN).
+dnl
+dnl The implementation will create a binary, but instead of running the
+dnl binary it will be grep'ed for some symbols that differ for
+dnl different endianess of the binary.
+dnl
+dnl NOTE: The upcoming autoconf 2.53 does include the idea of this
+dnl macro, what makes it superfluous by then.
+dnl
+dnl @category CrossCompilation
+dnl @author Guido Draheim <guidod@gmx.de>
+dnl @version 2002-03-18
+dnl @license GPLWithACException
+
+AC_DEFUN([AC_C_BIGENDIAN_CROSS],
+[AC_CACHE_CHECK(whether byte ordering is bigendian, ac_cv_c_bigendian,
+[ac_cv_c_bigendian=unknown
+# See if sys/param.h defines the BYTE_ORDER macro.
+AC_TRY_COMPILE([#include <sys/types.h>
+#include <sys/param.h>], [
+#if !BYTE_ORDER || !BIG_ENDIAN || !LITTLE_ENDIAN
+ bogus endian macros
+#endif], [# It does; now see whether it defined to BIG_ENDIAN or not.
+AC_TRY_COMPILE([#include <sys/types.h>
+#include <sys/param.h>], [
+#if BYTE_ORDER != BIG_ENDIAN
+ not big endian
+#endif], ac_cv_c_bigendian=yes, ac_cv_c_bigendian=no)])
+if test $ac_cv_c_bigendian = unknown; then
+AC_TRY_RUN([main () {
+  /* Are we little or big endian?  From Harbison&Steele.  */
+  union
+  {
+    long l;
+    char c[sizeof (long)];
+  } u;
+  u.l = 1;
+  exit (u.c[sizeof (long) - 1] == 1);
+}], ac_cv_c_bigendian=no, ac_cv_c_bigendian=yes,
+[ echo $ac_n "cross-compiling... " 2>&AC_FD_MSG ])
+fi])
+if test $ac_cv_c_bigendian = unknown; then
+AC_MSG_CHECKING(to probe for byte ordering)
+[
+cat >conftest.c <<EOF
+short ascii_mm[] = { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 };
+short ascii_ii[] = { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 };
+void _ascii() { char* s = (char*) ascii_mm; s = (char*) ascii_ii; }
+short ebcdic_ii[] = { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 };
+short ebcdic_mm[] = { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 };
+void _ebcdic() { char* s = (char*) ebcdic_mm; s = (char*) ebcdic_ii; }
+int main() { _ascii (); _ebcdic (); return 0; }
+EOF
+] if test -f conftest.c ; then
+     if ${CC-cc} -c conftest.c -o conftest.o && test -f conftest.o ; then
+        if test `grep -l BIGenDianSyS conftest.o` ; then
+           echo $ac_n ' big endian probe OK, ' 1>&AC_FD_MSG
+	   ac_cv_c_bigendian=yes
+        fi
+        if test `grep -l LiTTleEnDian conftest.o` ; then
+           echo $ac_n ' little endian probe OK, ' 1>&AC_FD_MSG
+	   if test $ac_cv_c_bigendian = yes ; then
+	    ac_cv_c_bigendian=unknown;
+           else
+            ac_cv_c_bigendian=no
+           fi
+        fi
+	echo $ac_n 'guessing bigendian ...  ' >&AC_FD_MSG
+     fi
+  fi
+AC_MSG_RESULT($ac_cv_c_bigendian)
+fi
+if test $ac_cv_c_bigendian = yes; then
+  AC_DEFINE(WORDS_BIGENDIAN, 1, [whether byteorder is bigendian])
+  BYTEORDER=4321
+else
+  BYTEORDER=1234
+fi
+AC_DEFINE_UNQUOTED(BYTEORDER, $BYTEORDER, [1234 = LIL_ENDIAN, 4321 = BIGENDIAN])
+if test $ac_cv_c_bigendian = unknown; then
+  AC_MSG_ERROR(unknown endianess - sorry, please pre-set ac_cv_c_bigendian)
+fi
+])
Index: trunk/drmaa_utils/m4/ax_docutils.m4
===================================================================
--- trunk/drmaa_utils/m4/ax_docutils.m4	(revision 1)
+++ trunk/drmaa_utils/m4/ax_docutils.m4	(revision 1)
@@ -0,0 +1,33 @@
+# $Id$
+#
+# SYNOPSIS
+#
+#   AX_DOCUTILS([ACTION-IF-FOUND[, ACTION-IF-NOT-FOUND]])
+#
+# DESCRIPTION
+#
+#   Test for the Docutils -- Python driven reStructuredText processor.
+#   This macro calls (through AC_CHECK_PROGS)::
+#
+#     AC_SUBST(RST2HTML)
+#     AC_SUBST(RST2LATEX)
+#
+# LAST MODIFICATION
+#
+#   2007-12-14
+#
+# LICENSE
+#
+#   Written by Åukasz CieÅnik <lukasz.ciesnik@fedstage.com>
+#   and placed under Public Domain
+#
+
+AC_DEFUN([AX_DOCUTILS], [
+	AC_CHECK_PROGS([RST2HTML], [rst2html rst2html.py])
+	AC_CHECK_PROGS([RST2LATEX], [rst2latex rst2latex.py])
+	if test x$RST2HTML != x -a x$RST2LATEX != x; then
+		ifelse([$1], , :, [$1])
+	else
+		ifelse([$2], , :, [$2])
+	fi
+])
Index: trunk/drmaa_utils/m4/acx_pthread.m4
===================================================================
--- trunk/drmaa_utils/m4/acx_pthread.m4	(revision 1)
+++ trunk/drmaa_utils/m4/acx_pthread.m4	(revision 1)
@@ -0,0 +1,245 @@
+dnl $Id$
+
+dnl
+dnl Check for libs/cppflags needed for POSIX Threads
+dnl
+
+dnl @synopsis ACX_PTHREAD([ACTION-IF-FOUND[, ACTION-IF-NOT-FOUND]])
+dnl
+dnl Modified from the original version:
+dnl * Removed pthread-specific CC support
+dnl * Added FreeBSD specific -pthread/-lpthread flags
+dnl Notes:
+dnl * -D_THREAD_SAFE may not be necessary on FreeBSD
+dnl   and elsewhere.
+dnl - landonf March 25th, 2005
+dnl
+dnl This macro figures out how to build C programs using POSIX threads.
+dnl It sets the PTHREAD_LIBS output variable to the threads library and
+dnl linker flags, and the PTHREAD_CFLAGS output variable to any special
+dnl C compiler flags that are needed. (The user can also force certain
+dnl compiler flags/libs to be tested by setting these environment
+dnl variables.)
+dnl
+dnl NOTE: You are assumed to not only compile your program with these
+dnl flags, but also link it with them as well. e.g. you should link
+dnl with $CC $CFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS
+dnl $LIBS
+dnl
+dnl If you are only building threads programs, you may wish to use
+dnl these variables in your default LIBS, and CFLAGS:
+dnl
+dnl        LIBS="$PTHREAD_LIBS $LIBS"
+dnl        CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+dnl
+dnl In addition, if the PTHREAD_CREATE_JOINABLE thread-attribute
+dnl constant has a nonstandard name, defines PTHREAD_CREATE_JOINABLE to
+dnl that name (e.g. PTHREAD_CREATE_UNDETACHED on AIX).
+dnl
+dnl ACTION-IF-FOUND is a list of shell commands to run if a threads
+dnl library is found, and ACTION-IF-NOT-FOUND is a list of commands to
+dnl run it if it is not found. If ACTION-IF-FOUND is not specified, the
+dnl default action will define HAVE_PTHREAD.
+dnl
+dnl Please let the authors know if this macro fails on any platform, or
+dnl if you have any other suggestions or comments. This macro was based
+dnl on work by SGJ on autoconf scripts for FFTW (www.fftw.org) (with
+dnl help from M. Frigo), as well as ac_pthread and hb_pthread macros
+dnl posted by Alejandro Forero Cuervo to the autoconf macro repository.
+dnl We are also grateful for the helpful feedback of numerous users.
+dnl
+dnl @category InstalledPackages
+dnl @author Steven G. Johnson <stevenj@alum.mit.edu>
+dnl @version 2005-01-14
+dnl @license GPLWithACException
+
+AC_DEFUN([ACX_PTHREAD], [
+AC_REQUIRE([AC_CANONICAL_HOST])
+AC_LANG_SAVE
+AC_LANG_C
+acx_pthread_ok=no
+
+# We used to check for pthread.h first, but this fails if pthread.h
+# requires special compiler flags (e.g. on True64 or Sequent).
+# It gets checked for in the link test anyway.
+
+# First of all, check if the user has set any of the PTHREAD_LIBS,
+# etcetera environment variables, and if threads linking works using
+# them:
+if test x"$PTHREAD_LIBS$PTHREAD_CFLAGS" != x; then
+        save_CFLAGS="$CFLAGS"
+        CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+        save_LIBS="$LIBS"
+        LIBS="$PTHREAD_LIBS $LIBS"
+        AC_MSG_CHECKING([for pthread_join in LIBS=$PTHREAD_LIBS with CFLAGS=$PTHREAD_CFLAGS])
+        AC_TRY_LINK_FUNC(pthread_join, acx_pthread_ok=yes)
+        AC_MSG_RESULT($acx_pthread_ok)
+        if test x"$acx_pthread_ok" = xno; then
+                PTHREAD_LIBS=""
+                PTHREAD_CFLAGS=""
+        fi
+        LIBS="$save_LIBS"
+        CFLAGS="$save_CFLAGS"
+fi
+
+# We must check for the threads library under a number of different
+# names; the ordering is very important because some systems
+# (e.g. DEC) have both -lpthread and -lpthreads, where one of the
+# libraries is broken (non-POSIX).
+
+# Create a list of thread flags to try.  Items starting with a "-" are
+# C compiler flags, and other items are library names, except for "none"
+# which indicates that we try without any flags at all, and "pthread-config"
+# which is a program returning the flags for the Pth emulation library.
+
+acx_pthread_flags="pthreads none -Kthread -kthread lthread -pthread -pthreads -mthreads pthread --thread-safe -mt pthread-config"
+
+# The ordering *is* (sometimes) important.  Some notes on the
+# individual items follow:
+
+# pthreads: AIX (must check this before -lpthread)
+# none: in case threads are in libc; should be tried before -Kthread and
+#       other compiler flags to prevent continual compiler warnings
+# -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h)
+# -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able)
+# lthread: LinuxThreads port on FreeBSD (also preferred to -pthread)
+# -pthread: Linux/gcc (kernel threads), BSD/gcc (userland threads)
+# -pthreads: Solaris/gcc
+# -mthreads: Mingw32/gcc, Lynx/gcc
+# -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it
+#      doesn't hurt to check since this sometimes defines pthreads too;
+#      also defines -D_REENTRANT)
+# pthread: Linux, etcetera
+# --thread-safe: KAI C++
+# pthread-config: use pthread-config program (for GNU Pth library)
+
+case "${host_cpu}-${host_os}" in
+        *solaris*)
+
+        # On Solaris (at least, for some versions), libc contains stubbed
+        # (non-functional) versions of the pthreads routines, so link-based
+        # tests will erroneously succeed.  (We need to link with -pthread or
+        # -lpthread.)  (The stubs are missing pthread_cleanup_push, or rather
+        # a function called by this macro, so we could check for that, but
+        # who knows whether they'll stub that too in a future libc.)  So,
+        # we'll just look for -pthreads and -lpthread first:
+
+        acx_pthread_flags="-pthread -pthreads pthread -mt $acx_pthread_flags"
+        ;;
+
+	*freebsd*)
+	# freebsd 4 uses -pthread, freebsd 5 uses -lpthread
+	acx_pthread_flags="pthread -pthread"
+	;;
+esac
+
+if test x"$acx_pthread_ok" = xno; then
+for flag in $acx_pthread_flags; do
+
+        case $flag in
+                none)
+                AC_MSG_CHECKING([whether pthreads work without any flags])
+                ;;
+
+                -*)
+                AC_MSG_CHECKING([whether pthreads work with $flag])
+                PTHREAD_CFLAGS="$flag"
+                PTHREAD_LIBS="$flag"
+                ;;
+
+		pthread-config)
+		AC_CHECK_PROG(acx_pthread_config, pthread-config, yes, no)
+		if test x"$acx_pthread_config" = xno; then continue; fi
+		PTHREAD_CFLAGS="`pthread-config --cflags`"
+		PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`"
+		;;
+
+                *)
+                AC_MSG_CHECKING([for the pthreads library -l$flag])
+                PTHREAD_LIBS="-l$flag"
+                ;;
+        esac
+
+        save_LIBS="$LIBS"
+        save_CFLAGS="$CFLAGS"
+        LIBS="$PTHREAD_LIBS $LIBS"
+        CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+
+        # Check for various functions.  We must include pthread.h,
+        # since some functions may be macros.  (On the Sequent, we
+        # need a special flag -Kthread to make this header compile.)
+        # We check for pthread_join because it is in -lpthread on IRIX
+        # while pthread_create is in libc.  We check for pthread_attr_init
+        # due to DEC craziness with -lpthreads.  We check for
+        # pthread_cleanup_push because it is one of the few pthread
+        # functions on Solaris that doesn't have a non-functional libc stub.
+        # We try pthread_create on general principles.
+        AC_TRY_LINK([#include <pthread.h>],
+                    [pthread_t th; pthread_join(th, 0);
+                     pthread_attr_init(0); pthread_cleanup_push(0, 0);
+                     pthread_create(0,0,0,0); pthread_cleanup_pop(0); ],
+                    [acx_pthread_ok=yes])
+
+        LIBS="$save_LIBS"
+        CFLAGS="$save_CFLAGS"
+
+        AC_MSG_RESULT($acx_pthread_ok)
+        if test "x$acx_pthread_ok" = xyes; then
+                break;
+        fi
+
+        PTHREAD_LIBS=""
+        PTHREAD_CFLAGS=""
+done
+fi
+
+# Various other checks:
+if test "x$acx_pthread_ok" = xyes; then
+        save_LIBS="$LIBS"
+        LIBS="$PTHREAD_LIBS $LIBS"
+        save_CFLAGS="$CFLAGS"
+        CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+
+        # Detect AIX lossage: JOINABLE attribute is called UNDETACHED.
+	AC_MSG_CHECKING([for joinable pthread attribute])
+	attr_name=unknown
+	for attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do
+	    AC_TRY_LINK([#include <pthread.h>], [int attr=$attr;],
+                        [attr_name=$attr; break])
+	done
+        AC_MSG_RESULT($attr_name)
+        if test "$attr_name" != PTHREAD_CREATE_JOINABLE; then
+            AC_DEFINE_UNQUOTED(PTHREAD_CREATE_JOINABLE, $attr_name,
+                               [Define to necessary symbol if this constant
+                                uses a non-standard name on your system.])
+        fi
+
+        AC_MSG_CHECKING([if more special flags are required for pthreads])
+        flag=no
+        case "${host_cpu}-${host_os}" in
+            *-aix* | *-freebsd* | *-darwin*) flag="-D_THREAD_SAFE";;
+            *solaris* | *-osf* | *-hpux*) flag="-D_REENTRANT";;
+        esac
+        AC_MSG_RESULT(${flag})
+        if test "x$flag" != xno; then
+            PTHREAD_CFLAGS="$flag $PTHREAD_CFLAGS"
+        fi
+
+        LIBS="$save_LIBS"
+        CFLAGS="$save_CFLAGS"
+
+fi
+
+AC_SUBST(PTHREAD_LIBS)
+AC_SUBST(PTHREAD_CFLAGS)
+
+# Finally, execute ACTION-IF-FOUND/ACTION-IF-NOT-FOUND:
+if test x"$acx_pthread_ok" = xyes; then
+        ifelse([$1],,AC_DEFINE(HAVE_PTHREAD,1,[Define if you have POSIX threads libraries and header files.]),[$1])
+        :
+else
+        acx_pthread_ok=no
+        $2
+fi
+AC_LANG_RESTORE
+])dnl ACX_PTHREAD
Index: trunk/drmaa_utils/m4/bison_ylwrap.sh
===================================================================
--- trunk/drmaa_utils/m4/bison_ylwrap.sh	(revision 1)
+++ trunk/drmaa_utils/m4/bison_ylwrap.sh	(revision 1)
@@ -0,0 +1,37 @@
+#!/bin/sh
+# ylwrap script specially crafted for Bison
+
+input="$1"; shift
+
+while true; do
+	case "$1" in
+		"")  exit 1;;
+		--)  shift; break;;
+		*)   shift;;
+	esac
+done
+
+prog="$1"; shift; args=$@
+if [ ${prog} != "bison" ]; then
+	cat >&2 <<EOF
+ * ERROR: Bison was not found at configuration time while some sources are
+ * build by it.  Either install Bison <http://www.gnu.org/software/bison/>
+ * or download tarball with generated sources included (than you will
+ * not be able to modify .y files).
+EOF
+	exit 1
+fi
+
+real_args=""
+for i in $args; do
+	case "$i" in
+		-y)  ;;
+		--yacc)  ;;
+		*)  real_args="$real_args $i" ;;
+	esac
+done
+
+echo "${prog} --output=`basename ${input} .y`.c ${real_args[@]} ${input}"
+${prog} --output=`basename ${input} .y`.c ${real_args[@]} ${input}
+
+
Index: trunk/drmaa_utils/m4/ax_func_gettid.m4
===================================================================
--- trunk/drmaa_utils/m4/ax_func_gettid.m4	(revision 1)
+++ trunk/drmaa_utils/m4/ax_func_gettid.m4	(revision 1)
@@ -0,0 +1,50 @@
+# $Id$
+#
+# SYNOPSIS
+#
+#   AX_FUNC_GETTID([ACTION-IF-FOUND[, ACTION-IF-NOT-FOUND]])
+#
+# DESCRIPTION
+#
+#   Check for gettid system call.  When found this macro
+#   defines HAVE_GETTID.  It may be used after following
+#   definition (it is not defined in Linux headers)::
+#
+#     #include <sys/types.h>
+#     #include <sys/syscall.h>
+#     pid_t gettid(void) {  return (pid_t)syscall( __NR_gettid );  }
+#
+# LAST MODIFICATION
+#
+#   2008-06-13
+#
+# LICENSE
+#
+#   Written by Åukasz CieÅnik <lukasz.ciesnik@fedstage.com>
+#   and placed under Public Domain
+#
+
+AC_DEFUN([AX_FUNC_GETTID],[
+AC_MSG_CHECKING([for gettid])
+AC_REQUIRE([AC_PROG_CC])
+AH_TEMPLATE([HAVE_GETTID], [Define to 1 if you have the gettid() syscall.])
+
+AC_LANG_PUSH([C])
+AC_COMPILE_IFELSE(
+	AC_LANG_PROGRAM([[
+@%:@include <sys/types.h>
+@%:@include <sys/syscall.h>
+@%:@include <unistd.h>
+pid_t gettid(void) { return (pid_t)syscall(__NR_gettid); }]],
+	[[pid_t tid = gettid(); return 0;]]),
+[ax_func_gettid_ok=yes], [ax_func_gettid_ok=no])
+AC_LANG_POP([C])
+
+AC_MSG_RESULT([$ax_func_gettid_ok])
+if test x$ax_func_gettid_ok = xyes; then
+	AC_DEFINE([HAVE_GETTID], [1])
+	ifelse([$1], , :, [$1])
+else
+	ifelse([$2], , :, [$2])
+fi
+])
Index: trunk/drmaa_utils/m4/ax_func_va_copy.m4
===================================================================
--- trunk/drmaa_utils/m4/ax_func_va_copy.m4	(revision 1)
+++ trunk/drmaa_utils/m4/ax_func_va_copy.m4	(revision 1)
@@ -0,0 +1,66 @@
+# $Id$
+#
+# SYNOPSIS
+#
+#   AX_FUNC_VA_COPY([ACTION-IF-FOUND[, [ACTION-IF-NOT-FOUND]])
+#
+# DESCRIPTION
+#
+#   Test for va_copy function/macro.
+#   When found it defines ``HAVE_VA_COPY`` and/or ``HAVE___VA_COPY``
+#   when ``va_copy`` and/or ``__va_copy`` is found respectively.
+#
+# LAST MODIFICATION
+#
+#   2008-06-13
+#
+# LICENSE
+#
+#   Written by Åukasz CieÅnik <lukasz.ciesnik@fedstage.com>
+#   and placed under Public Domain.
+#
+
+AC_DEFUN([AX_FUNC_VA_COPY], [
+
+ax_func_va_copy_ok=no
+
+AH_TEMPLATE([HAVE_VA_COPY],
+		[Define to 1 if you have the va_copy function.])
+AC_MSG_CHECKING([for va_copy])
+AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include <stdarg.h>]],
+			[[va_list a, b; va_copy(a, b);]])],[
+	ax_func_va_copy_ok=yes
+  AC_MSG_RESULT([yes])
+  AC_DEFINE([HAVE_VA_COPY], [1])
+  ],[
+      AC_MSG_RESULT([no])
+  ],[
+      AC_MSG_RESULT([no])
+])
+
+AH_TEMPLATE([HAVE___VA_COPY],
+		[Define to 1 if you have the __va_copy function.])
+AC_MSG_CHECKING([for __va_copy])
+AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include <stdarg.h>]],
+			[[va_list a, b; __va_copy(a, b);]])],[
+	ax_func_va_copy_ok=yes
+  AC_MSG_RESULT([yes])
+  AC_DEFINE([HAVE___VA_COPY], [1])
+	AH_BOTTOM([
+#ifndef HAVE_VA_COPY
+#	define va_copy(a,b) __va_copy(a,b)
+#	define HAVE_VA_COPY 1
+#endif
+])
+  ], [
+  AC_MSG_RESULT([no])
+  ], [
+  AC_MSG_RESULT([no])
+])
+
+if test x$ax_func_va_copy_ok = xyes; then
+	ifelse([$1], , :, [$1])
+else
+	ifelse([$2], , :, [$2])
+fi
+])
Index: trunk/drmaa_utils/m4/missing-dev-prog.sh
===================================================================
--- trunk/drmaa_utils/m4/missing-dev-prog.sh	(revision 1)
+++ trunk/drmaa_utils/m4/missing-dev-prog.sh	(revision 1)
@@ -0,0 +1,7 @@
+#!/bin/sh
+cat >&2 <<MESSAGE
+ * ERROR: $1 was not found at configuration time while some
+ * sources are build by it.  Either install $1 or download
+ * tarball with generated sources included.
+MESSAGE
+exit 1
Index: trunk/drmaa_utils/m4/ax_gettid.m4
===================================================================
--- trunk/drmaa_utils/m4/ax_gettid.m4	(revision 1)
+++ trunk/drmaa_utils/m4/ax_gettid.m4	(revision 1)
@@ -0,0 +1,53 @@
+# $Id$
+#
+# SYNOPSIS
+#
+#   AX_GETTID([ACTION-IF-FOUND[, ACTION-IF-NOT-FOUND]])
+#
+# DESCRIPTION
+#
+#   Check for gettid system call.  When found this macro
+#   defines HAVE_GETTID.  It may be used after following
+#   definition (it is not defined in Linux headers)::
+#
+#     #include <sys/types.h>
+#     #include <sys/syscall.h>
+#     pid_t gettid(void) {  return (pid_t)syscall( __NR_gettid );  }
+#
+# LAST MODIFICATION
+#
+#   2007-12-14
+#
+# LICENSE
+#
+#   Written by Åukasz CieÅnik <lukasz.ciesnik@fedstage.com>
+#   and placed under Public Domain
+#
+
+AC_DEFUN([AX_GETTID],[
+AC_MSG_CHECKING([for gettid])
+AC_REQUIRE([AC_PROG_CC])
+
+AC_LANG_PUSH([C])
+AC_COMPILE_IFELSE(
+	AC_LANG_PROGRAM([[
+@%:@include <sys/types.h>
+@%:@include <sys/syscall.h>
+@%:@include <unistd.h>
+pid_t gettid(void) { return (pid_t)syscall(__NR_gettid); }]],
+	[[pid_t tid = gettid(); return 0;]]),
+[ax_gettid_ok=yes], [ax_gettid_ok=no])
+AC_LANG_POP([C])
+
+AC_MSG_RESULT([$ax_gettid_ok])
+if test x$ax_gettid_ok = xyes; then
+	AC_DEFINE([HAVE_GETTID],1,[Define to 1 if you have the gettid() syscall.])
+fi
+if test x$ax_gettid_ok = xyes; then
+	$1
+	:
+else
+	$2
+	:
+fi
+])
Index: trunk/drmaa_utils/.ignore
===================================================================
--- trunk/drmaa_utils/.ignore	(revision 1)
+++ trunk/drmaa_utils/.ignore	(revision 1)
@@ -0,0 +1,29 @@
+configure
+Makefile.in
+Doxyfile
+config.log
+config.status
+scripts
+stamp-h1
+config.h
+config.h.in
+autom4te.cache
+drmaa_utils-2.0.1.tar.gz
+libtool
+aclocal.m4
+Makefile
+.libs
+.deps
+Makefile
+test_exception
+libtool.m4
+lt~obsolete.m4
+ltsugar.m4
+ltversion.m4
+ltoptions.m4
+drmaa_attrib.c
+datetime_tab.c
+datetime_tab.h
+timedelta.c
+conf_tab.c
+conf_tab.h
Index: trunk/drmaa_utils/configure.ac
===================================================================
--- trunk/drmaa_utils/configure.ac	(revision 1)
+++ trunk/drmaa_utils/configure.ac	(revision 1)
@@ -0,0 +1,204 @@
+AC_INIT([FedStage DRMAA utilities library], [2.0.1], [drmaa-pbspro-users@lists.fedstage.com], [drmaa_utils])
+AC_PREREQ(2.59)
+AC_REVISION([$Id: configure.ac 1673 2008-11-21 20:17:05Z lukasz $])
+AC_COPYRIGHT([
+FedStage DRMAA utilities library
+Copyright (C) 2006-2008  FedStage Systems
+
+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/>.
+])
+
+DRMAA_UTILS_MAJOR=2
+DRMAA_UTILS_MINOR=0
+DRMAA_UTILS_MICRO=1
+DRMAA_UTILS_VERSION_INFO=2:1:0
+AC_SUBST([DRMAA_UTILS_MAJOR])
+AC_SUBST([DRMAA_UTILS_MINOR])
+AC_SUBST([DRMAA_UTILS_MICRO])
+AC_SUBST([DRMAA_UTILS_VERSION_INFO])
+
+AC_CONFIG_SRCDIR([drmaa_utils/xmalloc.c])
+AC_CONFIG_MACRO_DIR([m4])
+AC_CONFIG_AUX_DIR([scripts])
+
+AM_INIT_AUTOMAKE
+DEVELOPER_MODE="no"
+AM_CONDITIONAL([DEVELOPER_MODE], [test "x$DEVELOPER_MODE" = "xyes"])
+
+# command-line arguments:
+AC_ARG_ENABLE(debug, AC_HELP_STRING([--enable-debug],
+			[produce code suiteable for debugging and print logs at runtime]))
+AC_ARG_ENABLE(development, AC_HELP_STRING([--enable-development],
+			[enable development mode: make additional checks (suiteable for FedStage DRMAA utilities library developers)]))
+
+AC_ARG_WITH(drmaa-utils, AC_HELP_STRING([--with-drmaa-utils=...],
+		[used only to detect that drmaa utils is sub packaged]))
+AM_CONDITIONAL([DRMAA_UTILS_STANDALONE],
+		[test x$with_drmaa_utils = x])
+
+# programs:
+AC_PROG_CC
+AC_PROG_CPP
+AC_PROG_RANLIB
+AC_PROG_INSTALL
+AC_PROG_LIBTOOL
+AC_PROG_MAKE_SET
+AC_PROG_LN_S
+
+
+# code generation tools:
+AC_PROG_YACC
+AX_GPERF
+AC_CHECK_PROGS([RAGEL], [ragel], [sh m4/missing-dev-prog.sh ragel])
+
+# reStructuredText processing:
+AX_DOCUTILS
+# documentation generation:
+AC_CHECK_PROGS([DOT], [dot])
+if test x$DOT != x; then
+	HAVE_DOT=yes
+else
+	HAVE_DOT=no
+fi
+AC_SUBST([HAVE_DOT])
+
+# check compiler / set basic flags:
+if test x$ac_cv_prog_cc_stdc = xno; then
+	AC_MSG_ERROR([ANSI C compiler is required])
+fi
+
+if test x$GCC = xyes; then
+	CFLAGS="-pedantic -ansi ${CFLAGS}"
+fi
+AM_CONDITIONAL([GCC], [test x$GCC = xyes])
+
+AX_GCC_WARNINGS()
+
+AH_TEMPLATE([DEBUGGING], [Produce debugging code])
+if test x$enable_debug = xyes; then
+	AC_DEFINE(DEBUGGING,[1])
+	CFLAGS="${CFLAGS} -O0"
+else
+	CPPFLAGS="-DNDEBUG ${CPPFLAGS}"
+fi
+
+AH_TEMPLATE([DEVELOPMENT], [Development mode])
+if test x$enable_development = xyes; then
+	AC_DEFINE(DEVELOPMENT, [1])
+fi
+
+AH_BOTTOM([
+#ifndef __GNUC__
+#	define __attribute__ /* nothing */
+#endif
+])
+
+# system:
+CPPFLAGS="-D_REENTRANT -D_THREAD_SAFE ${CPPFLAGS}"
+
+AC_CANONICAL_HOST
+case "$host_os" in
+	*linux*)
+		CPPFLAGS="${CPPFLAGS} -D_GNU_SOURCE"
+		;;
+	*solaris*)
+		CPPFLAGS="${CPPFLAGS} -D_XOPEN_SOURCE=500 -D__EXTENSIONS__"
+		;;
+	*freebsd*)
+		;;
+	*darwin*)
+		CPPFLAGS="${CPPFLAGS} -D_XOPEN_SOURCE=400"
+		;;
+	*aix*)                                                                                                                                                                                                                                  
+		CPPFLAGS="${CPPFLAGS} -D_XOPEN_SOURCE=500 -D_XOPEN_SOURCE_EXTENDED=1 -D__linux__"  
+		;;
+	*)
+		CPPFLAGS="${CPPFLAGS} -D_XOPEN_SOURCE=500 -D__USE_BSD"
+		;;
+esac
+
+
+AC_C_BIGENDIAN_CROSS
+
+# project prerequisites:
+
+# libraries:
+ACX_PTHREAD([CFLAGS="$CFLAGS $PTHREAD_CFLAGS" LIBS="$PTHREAD_LIBS $LIBS"],
+		[AC_MSG_ERROR([POSIX threads library is required by DRMAA.])])
+
+# headers:
+AC_CHECK_HEADERS([execinfo.h fcntl.h inttypes.h libintl.h limits.h malloc.h stddef.h stdint.h stdlib.h string.h sys/time.h unistd.h])
+AC_HEADER_STDBOOL
+AC_HEADER_TIME
+
+# types and structures:
+AC_TYPE_PID_T
+AC_TYPE_SIZE_T
+AC_TYPE_SSIZE_T
+AC_TYPE_MODE_T
+AC_TYPE_UINT16_T
+AC_TYPE_UINT32_T
+AC_TYPE_UINT8_T
+AC_STRUCT_TM
+AC_CHECK_MEMBER(struct tm.tm_gmtoff,[AC_DEFINE([HAVE_STRUCT_TM_GMTOFF],[1],[gmtoff in struct tm])],,[#include <time.h>])
+
+# compiler characteristic
+AC_C_CONST
+AC_C_INLINE
+AC_C_VOLATILE
+
+# functions:
+AC_FUNC_ALLOCA
+AC_FUNC_STRERROR_R
+AC_FUNC_STRFTIME
+AC_CHECK_FUNCS([ \
+	asprintf \
+	fstat \
+	getcwd \
+	gettimeofday \
+	localtime_r \
+	memset \
+	strchr \
+	strdup \
+	strerror \
+	strlcpy \
+	strndup \
+	strstr \
+	vasprintf])
+AX_FUNC_GETTID
+AX_FUNC_VA_COPY
+AC_SEARCH_LIBS([backtrace], [execinfo])
+
+# system services:
+
+# turn on warning after all tests
+if test x$GCC = xyes; then
+	if test x$enable_development = xyes; then
+		CFLAGS="-Werror ${CFLAGS}"
+	fi
+	CFLAGS="-Wall -W -Wno-unused  $GCC_W_NO_FORMAT_ZERO_LENGTH  $GCC_W_NO_MISSING_FIELD_INITIALIZERS ${CFLAGS}"
+fi
+
+AC_CONFIG_FILES([
+	Makefile
+	drmaa_utils/Makefile
+	test/Makefile
+	Doxyfile
+])
+AC_CONFIG_HEADERS([config.h])
+AC_OUTPUT
+
+echo
+echo "Run 'make' now."
+
Index: trunk/drmaa_utils/autoclean.sh
===================================================================
--- trunk/drmaa_utils/autoclean.sh	(revision 1)
+++ trunk/drmaa_utils/autoclean.sh	(revision 1)
@@ -0,0 +1,24 @@
+#!/bin/sh
+# $Id: autoclean.sh 1656 2008-11-18 17:11:58Z lukasz $
+
+echo "Removing all generated files. ($PWD)"
+
+make maintainer-clean
+
+rm -f aclocal.m4 configure configure.scan config.h.in confdefs.h libtool
+
+rm -rf autom4te.cache
+rm -rf scripts
+
+find . -name Makefile.in -exec rm -f {} \;
+find . -name Makefile -exec rm -f {} \;
+find . -name \*~ -exec rm -f {} \;
+find . -name \.#* -exec rm -f {} \;
+find . -name \*.core -exec rm -f {} \;
+find . -name \*.log -exec rm -f {} \;
+find . -name \*.a -exec rm -f {} \;
+find . -name \*.o -exec rm -f {} \;
+find . -name \*.lo* -exec rm -f {} \;
+find . -name \*.la* -exec rm -f {} \;
+
+echo "done."
Index: trunk/drmaa_utils/drmaa_utils/xmalloc.h
===================================================================
--- trunk/drmaa_utils/drmaa_utils/xmalloc.h	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/xmalloc.h	(revision 1)
@@ -0,0 +1,88 @@
+/* $Id: xmalloc.h 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+/**
+ * @file xmalloc.h
+ * Memory allocation/deallocation routines.
+ */
+
+#ifndef __DRMAA_UTILS__XMALLOC_H
+#define __DRMAA_UTILS__XMALLOC_H
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <drmaa_utils/compat.h>
+
+/**
+ * @defgroup xmalloc  Memory allocation/deallocation routines.
+ */
+/* @{ */
+
+
+/**
+ * Allocates <code> sizeof(type) </code> bytes.  Address of block is stored
+ * in @a p.  Upon failure FSD_ERRNO_NO_MEMORY is raised and @a p is NULL.
+ */
+#define fsd_malloc( p, type ) \
+	fsd_malloc_( (void**)(void*)&(p), sizeof(type) )
+
+/**
+ * Allocates <code> n * sizeof(type) </code> bytes of memory and stores
+ * address in \a p.  Allocated block is filled with zeros.  Upon failure
+ * error FSD_ERRNO_NO_MEMORY is raised.
+ * \c NULL is assigned to \a p on error or when <code> n == 0 </code>.
+ */
+#define fsd_calloc( p, n, type ) \
+	fsd_calloc_( (void**)(void*)&(p), (n), sizeof(type) )
+
+#define fsd_realloc( p, n, type ) \
+	fsd_realloc_( (void**)(void*)&(p), (n)*sizeof(type) )
+
+/**
+ * Fress previously allocated memory pointed by @a p.
+ * When <code> p == NULL </code> it does nothing.
+ */
+void fsd_free( void *p );
+
+void *fsd_malloc_( void **p, size_t size );
+void *fsd_calloc_( void **p, size_t n, size_t size );
+void *fsd_realloc_( void **p, size_t size );
+
+
+#define fsd_malloc_noraise( p, type ) \
+	fsd_malloc_noraise_( (void**)(void*)&(p), sizeof(type) )
+
+#define fsd_calloc_noraise( p, n, type ) \
+	fsd_calloc_noraise_( (void**)(void*)&(p), (n), sizeof(type) )
+
+#define fsd_realloc_noraise( p, n, type ) \
+	fsd_realloc_noraise_( (void**)(void*)&(p), (n)*sizeof(type) )
+
+#define fsd_free_noraise( p )  (fsd_free(p), 0)
+
+int fsd_malloc_noraise_( void **p, size_t size );
+int fsd_calloc_noraise_( void **p, size_t n, size_t size );
+int fsd_realloc_noraise_( void **p, size_t size );
+
+/* @} */
+
+#endif /* __DRMAA_UTILS__XMALLOC_H */
+
Index: trunk/drmaa_utils/drmaa_utils/fsd_job.c
===================================================================
--- trunk/drmaa_utils/drmaa_utils/fsd_job.c	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/fsd_job.c	(revision 1)
@@ -0,0 +1,461 @@
+/* $Id: fsd_job.c 308 2010-09-21 07:29:41Z mamonski $ */
+/*
+ * FedStage DRMAA utilities library
+ * Copyright (C) 2006-2008  FedStage Systems
+ *
+ * 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 <string.h>
+
+#include <drmaa_utils/drmaa.h>
+#include <drmaa_utils/iter.h>
+#include <drmaa_utils/job.h>
+#include <drmaa_utils/lookup3.h>
+
+#ifndef lint
+static char rcsid[]
+#	ifdef __GNUC__
+		__attribute__ ((unused))
+#	endif
+	= "$Id: fsd_job.c 308 2010-09-21 07:29:41Z mamonski $";
+#endif
+
+
+static void fsd_job_release( fsd_job_t *self );
+static void fsd_job_destroy( fsd_job_t *self );
+static void fsd_job_control( fsd_job_t *self, int action );
+static void fsd_job_update_status( fsd_job_t *self );
+static void fsd_job_get_termination_status( fsd_job_t *self,
+			int *status, fsd_iter_t **rusage_out );
+static void fsd_job_on_missing( fsd_job_t *self );
+
+fsd_job_t *
+fsd_job_new( char *job_id )
+{
+	fsd_job_t *volatile self = NULL;
+	fsd_log_enter(( "(%s)", job_id ));
+	TRY
+	 {
+		fsd_malloc( self, fsd_job_t );
+		self->release = fsd_job_release;
+		self->destroy = fsd_job_destroy;
+		self->control = fsd_job_control;
+		self->update_status = fsd_job_update_status;
+		self->get_termination_status = fsd_job_get_termination_status;
+		self->on_missing = fsd_job_on_missing;
+		self->next              = NULL;
+		self->ref_cnt           = 1;
+		self->job_id            = job_id;
+		self->session           = NULL;
+		self->last_update_time  = 0;
+		self->flags             = 0;
+		self->state             = DRMAA_PS_UNDETERMINED;
+		self->exit_status       = 0;
+		self->submit_time       = 0;
+		self->start_time        = 0;
+		self->end_time          = 0;
+		self->cpu_usage         = 0;
+		self->mem_usage         = 0;
+		self->vmem_usage        = 0;
+		self->walltime          = 0;
+		self->execution_hosts   = NULL;
+		self->queue				= NULL;
+		self->project			= NULL;
+		fsd_mutex_init( &self->mutex );
+		fsd_cond_init( &self->status_cond );
+		fsd_cond_init( &self->destroy_cond );
+		fsd_mutex_lock( &self->mutex );
+	 }
+	EXCEPT_DEFAULT
+	 {
+		if( self )
+			self->destroy( self );
+		else
+			fsd_free( job_id );
+		fsd_exc_reraise();
+	 }
+	END_TRY
+	fsd_log_return(( "=%p: ref_cnt=%d [lock %s]",
+				(void*)self, self->ref_cnt, self->job_id ));
+	return self;
+}
+
+
+void
+fsd_job_release( fsd_job_t *self )
+{
+	bool destroy;
+	fsd_log_enter(( "(%p={job_id=%s, ref_cnt=%d}) [unlock %s]",
+				(void*)self, self->job_id, self->ref_cnt, self->job_id ));
+	fsd_assert( self->ref_cnt > 0 );
+	destroy = ( --(self->ref_cnt) == 0 );
+	fsd_mutex_unlock( &self->mutex );
+	if( destroy )
+		self->destroy( self );
+	fsd_log_return(( "" ));
+}
+
+
+void
+fsd_job_destroy( fsd_job_t *self )
+{
+	fsd_log_enter(( "(%p={job_id=%s})", (void*)self, self->job_id ));
+	fsd_cond_destroy( &self->status_cond );
+	fsd_cond_destroy( &self->destroy_cond );
+	fsd_mutex_destroy( &self->mutex );
+	fsd_free( self->job_id );
+	fsd_free( self->execution_hosts );
+	fsd_free( self->queue );
+	fsd_free( self->project );
+	fsd_free( self );
+	fsd_log_return(( "" ));
+}
+
+
+void
+fsd_job_control( fsd_job_t *self, int action )
+{
+	fsd_exc_raise_code( FSD_ERRNO_NOT_IMPLEMENTED );
+}
+
+void
+fsd_job_update_status( fsd_job_t *self )
+{
+	fsd_exc_raise_code( FSD_ERRNO_NOT_IMPLEMENTED );
+}
+
+void
+fsd_job_get_termination_status( fsd_job_t *self,
+			int *status, fsd_iter_t **rusage_out )
+{
+	fsd_iter_t* volatile rusage = NULL;
+
+	TRY
+	 {
+		if( rusage_out )
+		 {
+			rusage = fsd_iter_new( NULL, 0 );
+			rusage->append( rusage, fsd_asprintf(
+						"submission_time=%ld", (long)self->submit_time ) );
+			rusage->append( rusage, fsd_asprintf(
+						"start_time=%ld", (long)self->start_time ) );
+			rusage->append( rusage, fsd_asprintf(
+						"end_time=%ld", (long)self->end_time ) );
+			rusage->append( rusage, fsd_asprintf(
+						"cpu=%ld", self->cpu_usage ) );
+			rusage->append( rusage, fsd_asprintf(
+						"mem=%ld", self->mem_usage ) );
+			rusage->append( rusage, fsd_asprintf(
+						"vmem=%ld", self->vmem_usage ) );
+			rusage->append( rusage, fsd_asprintf(
+						"walltime=%ld", self->walltime ) );
+			rusage->append( rusage, fsd_asprintf(
+						"hosts=%s", self->execution_hosts ) );
+
+			if (self->queue) {
+				rusage->append( rusage, fsd_asprintf("queue=%s", self->queue ) );
+			}
+
+			if (self->project) {
+				rusage->append( rusage, fsd_asprintf("project=%s", self->project ) );
+			}
+		 }
+	 }
+	EXCEPT_DEFAULT
+	 {
+		if( rusage )
+			rusage->destroy( rusage );
+		if( rusage_out )
+			*rusage_out = NULL;
+		fsd_exc_reraise();
+	 }
+	ELSE
+	 {
+		if( status )
+			*status = self->exit_status;
+		if( rusage_out )
+			*rusage_out = rusage;
+	 }
+	END_TRY
+}
+
+void
+fsd_job_on_missing( fsd_job_t *self )
+{
+	fsd_log_warning(( "job %s missing from DRM queue", self->job_id ));
+}
+
+
+static void
+fsd_job_set_destroy( fsd_job_set_t *self );
+static void
+fsd_job_set_add( fsd_job_set_t *self, fsd_job_t *job );
+static void
+fsd_job_set_remove( fsd_job_set_t *self, fsd_job_t *job );
+static fsd_job_t *
+fsd_job_set_get( fsd_job_set_t *self, const char *job_id );
+static bool
+fsd_job_set_empty( fsd_job_set_t *self );
+static fsd_job_t *
+fsd_job_set_find_terminated( fsd_job_set_t *self );
+static char **
+fsd_job_set_get_all_job_ids( fsd_job_set_t *self );
+static void fsd_job_set_signal_all( fsd_job_set_t *self );
+
+
+fsd_job_set_t *
+fsd_job_set_new(void)
+{
+	fsd_job_set_t *volatile self = NULL;
+	const size_t initial_size = 1024;
+
+	fsd_log_enter(( "()" ));
+	TRY
+	 {
+		fsd_malloc( self, fsd_job_set_t );
+		self->destroy = fsd_job_set_destroy;
+		self->add = fsd_job_set_add;
+		self->remove = fsd_job_set_remove;
+		self->get = fsd_job_set_get;
+		self->empty = fsd_job_set_empty;
+		self->find_terminated = fsd_job_set_find_terminated;
+		self->get_all_job_ids = fsd_job_set_get_all_job_ids;
+		self->signal_all = fsd_job_set_signal_all;
+		self->tab = NULL;
+		self->n_jobs = 0;
+		fsd_calloc( self->tab, initial_size, fsd_job_t* );
+		self->tab_size = initial_size;
+		self->tab_mask = self->tab_size - 1;
+		fsd_mutex_init( &self->mutex );
+	 }
+	EXCEPT_DEFAULT
+	 {
+		if( self )
+		 {
+			fsd_free( self->tab );
+			fsd_free( self );
+		 }
+		fsd_exc_reraise();
+	 }
+	END_TRY
+
+	fsd_log_return(( " =%p", (void*)self ));
+	return self;
+}
+
+
+void
+fsd_job_set_destroy( fsd_job_set_t *self )
+{
+	unsigned i;
+	fsd_job_t *j;
+
+	fsd_log_enter(( "()" ));
+	for( i = 0;  i < self->tab_size;  i++ )
+		for( j = self->tab[i];  j != NULL;  )
+		 {
+			fsd_job_t *job = j;
+			j = j->next;
+			fsd_mutex_lock( &job->mutex );
+			job->release( job );
+		 }
+	fsd_free( self->tab );
+	fsd_free( self );
+	fsd_log_return(( "" ));
+}
+
+
+void
+fsd_job_set_add( fsd_job_set_t *self, fsd_job_t *job )
+{
+	uint32_t h;
+	fsd_log_enter(( "(job=%p, job_id=%s)", (void*)job, job->job_id ));
+	fsd_mutex_lock( &self->mutex );
+	h = hashstr( job->job_id, strlen(job->job_id), 0 );
+	h &= self->tab_mask;
+	job->next = self->tab[ h ];
+	self->tab[ h ] = job;
+	self->n_jobs++;
+	job->ref_cnt++;
+	fsd_mutex_unlock( &self->mutex );
+	fsd_log_return(( ": job->ref_cnt=%d", job->ref_cnt ));
+}
+
+
+void
+fsd_job_set_remove( fsd_job_set_t *self, fsd_job_t *job )
+{
+	fsd_job_t **pjob = NULL;
+	uint32_t h;
+
+	fsd_log_enter(( "(job_id=%s)", job->job_id ));
+	fsd_mutex_lock( &self->mutex );
+	TRY
+	 {
+		h = hashstr( job->job_id, strlen(job->job_id), 0 );
+		h &= self->tab_mask;
+		for( pjob = &self->tab[ h ];  *pjob;  pjob = &(*pjob)->next )
+		 {
+			if( *pjob == job )
+				break;
+		 }
+		if( *pjob )
+		 {
+			*pjob = (*pjob)->next;
+			job->next = NULL;
+			self->n_jobs--;
+			job->ref_cnt--;
+		 }
+		else
+			fsd_exc_raise_code( FSD_DRMAA_ERRNO_INVALID_JOB );
+	 }
+	FINALLY
+	 { fsd_mutex_unlock( &self->mutex ); }
+	END_TRY
+	fsd_log_return(( ": job->ref_cnt=%d", job->ref_cnt ));
+}
+
+
+fsd_job_t *
+fsd_job_set_get( fsd_job_set_t *self, const char *job_id )
+{
+	uint32_t h;
+	fsd_job_t *job = NULL;
+
+	fsd_log_enter(( "(job_id=%s)", job_id ));
+	fsd_mutex_lock( &self->mutex );
+	h = hashstr( job_id, strlen(job_id), 0 );
+	h &= self->tab_mask;
+	for( job = self->tab[ h ];  job;  job = job->next )
+		if( !strcmp( job->job_id, job_id ) )
+			break;
+	if( job )
+	 {
+		fsd_mutex_lock( &job->mutex );
+		fsd_assert( !(job->flags & FSD_JOB_DISPOSED) );
+		job->ref_cnt ++;
+	 }
+	fsd_mutex_unlock( &self->mutex );
+	if( job )
+		fsd_log_return(( "(job_id=%s) =%p: ref_cnt=%d [lock %s]",
+					job_id, (void*)job, job->ref_cnt, job->job_id ));
+	else
+		fsd_log_return(( "(job_id=%s) =NULL", job_id ));
+	return job;
+}
+
+
+bool
+fsd_job_set_empty( fsd_job_set_t *self )
+{
+	return self->n_jobs == 0;
+}
+
+
+fsd_job_t *
+fsd_job_set_find_terminated( fsd_job_set_t *self )
+{
+	fsd_job_t *job = NULL;
+	size_t i;
+	fsd_mutex_t* volatile mutex = & self->mutex;
+
+	fsd_log_enter(( "()" ));
+	fsd_mutex_lock( mutex );
+	TRY
+	 {
+		for( i = 0;  i < self->tab_size;  i++ )
+			for( job = self->tab[ i ];  job;  job = job->next )
+				if( job->state >= DRMAA_PS_DONE )
+					goto found;
+found:
+		if( job )
+		 {
+			fsd_mutex_lock( &job->mutex );
+			fsd_assert( !(job->flags & FSD_JOB_DISPOSED) );
+			job->ref_cnt ++;
+		 }
+	 }
+	FINALLY
+	 { fsd_mutex_unlock( mutex ); }
+	END_TRY
+	if( job )
+		fsd_log_return(( "() =%p: job_id=%s, ref_cnt=%d [lock %s]",
+					(void*)job, job->job_id, job->ref_cnt, job->job_id ));
+	else
+		fsd_log_return(( "() =%p", (void*)job ));
+	return job;
+}
+
+
+char **
+fsd_job_set_get_all_job_ids( fsd_job_set_t *self )
+{
+	fsd_job_t *job = NULL;
+	char** volatile job_ids = NULL;
+	/* size_t n_jobs = 0, capacity = 0; */
+	size_t i;
+	unsigned j = 0;
+	fsd_mutex_t* volatile mutex = & self->mutex;
+
+	fsd_log_enter(( "" ));
+	fsd_mutex_lock( mutex );
+	TRY
+	 {
+		fsd_calloc( job_ids, self->n_jobs+1, char* );
+		for( i = 0;  i < self->tab_size;  i++ )
+			for( job = self->tab[ i ];  job;  job = job->next )
+				job_ids[ j++ ] = fsd_strdup( job->job_id );
+		fsd_realloc( job_ids, j+1, char* );
+	 }
+	FINALLY
+	 {
+		fsd_mutex_unlock( mutex );
+		if( fsd_exc_get() )
+			fsd_free_vector( job_ids );
+	 }
+	END_TRY
+
+	fsd_log_return(( " =%p", (void*)job_ids ));
+	return job_ids;
+}
+
+
+void
+fsd_job_set_signal_all( fsd_job_set_t *self )
+{
+	fsd_job_t *volatile job = NULL;
+	fsd_mutex_t *volatile mutex = & self->mutex;
+
+	fsd_log_enter(( "" ));
+	fsd_mutex_lock( mutex );
+	TRY
+	 {
+		volatile size_t i;
+		for( i = 0;  i < self->tab_size;  i++ )
+			for( job = self->tab[ i ];  job;  job = job->next )
+			 {
+				fsd_mutex_lock( &job->mutex );
+				TRY{ fsd_cond_broadcast( &job->status_cond ); }
+				FINALLY{ fsd_mutex_unlock( &job->mutex ); }
+				END_TRY
+			 }
+	 }
+	FINALLY
+	 { fsd_mutex_unlock( mutex ); }
+	END_TRY
+
+	fsd_log_return(( "" ));
+}
+
Index: trunk/drmaa_utils/drmaa_utils/thread.c
===================================================================
--- trunk/drmaa_utils/drmaa_utils/thread.c	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/thread.c	(revision 1)
@@ -0,0 +1,418 @@
+/* $Id: thread.c 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+/**
+ * @file thread.c
+ * Implementation of recursive mutexes for systems without native support
+ * for it.
+ */
+
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <drmaa_utils/thread.h>
+#include <drmaa_utils/common.h>
+#include <errno.h>
+#include <unistd.h>
+
+#ifdef HAVE_GETTID
+#include <sys/types.h>
+#include <sys/syscall.h>
+pid_t gettid(void)
+{
+	return (pid_t)syscall( __NR_gettid );
+}
+#endif
+
+#ifndef lint
+static char rcsid[]
+#	ifdef __GNUC__
+		__attribute__ ((unused))
+#	endif
+	= "$Id: thread.c 2 2009-10-12 09:51:22Z mamonski $";
+#endif
+
+
+void
+fsd_thread_create( fsd_thread_t *thread, void* (*func)(void*), void *arg )
+{
+	int errno_ = 0;
+	errno_ = pthread_create( thread, NULL, func, arg );
+	if( errno_ )
+		fsd_exc_raise_sys( errno_ );
+}
+
+void
+fsd_thread_join( fsd_thread_t th, void **thread_return )
+{
+	int errno_ = 0;
+	errno_ = pthread_join( th, thread_return );
+	if( errno_ )
+		fsd_exc_raise_sys( errno_ );
+}
+
+void
+fsd_thread_detach( fsd_thread_t th )
+{
+	int errno_ = 0;
+	errno_ = pthread_detach( th );
+	if( errno_ )
+		fsd_exc_raise_sys( errno_ );
+}
+
+
+#if HAVE_RECURSIVE_MUTEXES
+
+void
+fsd_mutex_init( fsd_mutex_t *mutex )
+{
+	int errno_ = 0;
+	pthread_mutexattr_t attr;
+	do {
+		errno_ = pthread_mutexattr_init( &attr );
+		if( errno_ )  break;
+		errno_ = pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
+		if( errno_ )  break;
+		errno_ = pthread_mutex_init( mutex, &attr );
+		if( errno_ )  break;
+		errno_ = pthread_mutexattr_destroy( &attr );
+	} while( false );
+	if( errno_ )
+		fsd_exc_raise_sys( errno_ );
+}
+
+void
+fsd_mutex_destroy( fsd_mutex_t *mutex )
+{
+	int errno_ = 0;
+	errno_ = pthread_mutex_destroy( mutex );
+	if( errno_ )
+		fsd_exc_raise_sys( errno_ );
+}
+
+bool
+fsd_mutex_lock( fsd_mutex_t *mutex )
+{
+	int errno_ = 0;
+	errno_ = pthread_mutex_lock( mutex );
+	if( errno_ )
+		fsd_exc_raise_sys( errno_ );
+	return true;
+}
+
+bool
+fsd_mutex_unlock( fsd_mutex_t *mutex )
+{
+	int errno_ = 0;
+	errno_ = pthread_mutex_unlock( mutex );
+	if( errno_ )
+		fsd_exc_raise_sys( errno_ );
+	return false;
+}
+
+bool
+fsd_mutex_trylock( fsd_mutex_t *mutex )
+{
+	int errno_ = 0;
+	errno_ = pthread_mutex_trylock( mutex );
+	switch( errno_ )
+	 {
+		case 0:
+			return true;
+		case EBUSY:
+			return false;
+		default:
+			fsd_exc_raise_sys( errno_ );
+	 }
+}
+
+int
+fsd_mutex_unlock_times( fsd_mutex_t *mutex )
+{
+	int count = 0;
+	int errno_ = 0;
+	while( errno_ == 0 )
+	 {
+		errno_ = pthread_mutex_unlock( mutex );
+		if( !errno_ )
+			count++;
+	 }
+	if( errno_ != EPERM  ||  count == 0 )
+		fsd_exc_raise_sys( errno_ );
+	return count;
+}
+
+void
+fsd_cond_init( fsd_cond_t *cond )
+{
+	int errno_ = 0;
+	errno_ = pthread_cond_init( cond, NULL );
+	if( errno_ )
+		fsd_exc_raise_sys( errno_ );
+}
+
+void
+fsd_cond_destroy( fsd_cond_t *cond )
+{
+	int errno_ = 0;
+	errno_ = pthread_cond_destroy( cond );
+	if( errno_ )
+		fsd_exc_raise_sys( errno_ );
+}
+
+void
+fsd_cond_signal( fsd_cond_t *cond )
+{
+	int errno_ = 0;
+	errno_ = pthread_cond_signal( cond );
+	if( errno_ )
+		fsd_exc_raise_sys( errno_ );
+}
+
+void
+fsd_cond_broadcast( fsd_cond_t *cond )
+{
+	int errno_ = 0;
+	errno_ = pthread_cond_broadcast( cond );
+	if( errno_ )
+		fsd_exc_raise_sys( errno_ );
+}
+
+void
+fsd_cond_wait( fsd_cond_t *cond, fsd_mutex_t *mutex )
+{
+	int errno_ = 0;
+	errno_ = pthread_cond_wait( cond, mutex );
+	if( errno_ )
+		fsd_exc_raise_sys( errno_ );
+}
+
+bool
+fsd_cond_timedwait( fsd_cond_t *cond, fsd_mutex_t *mutex,
+		const struct timespec *abstime )
+{
+	int errno_ = 0;
+	errno_ = pthread_cond_timedwait( cond, mutex, abstime );
+	switch( errno_ )
+	 {
+		case 0:
+			return true;
+		case ETIMEDOUT:
+			return false;
+		default:
+			fsd_exc_raise_sys( errno_ );
+	 }
+}
+
+#else /* ! HAVE_RECURSIVE_MUTEXES */
+
+void
+fsd_mutex_init( fsd_mutex_t *mutex )
+{
+	int errno_ = 0;
+	mutex->owner = (pthread_t)-1;
+	mutex->acquired = 0;
+	errno_ = pthread_mutex_init( &mutex->mutex, NULL );
+	if( errno_ )
+		fsd_exc_raise_sys( errno_ );
+}
+
+void
+fsd_mutex_destroy( fsd_mutex_t *mutex )
+{
+	int errno_ = 0;
+	errno_ = pthread_mutex_destroy( &mutex->mutex );
+	if( errno_ )
+		fsd_exc_raise_sys( errno_ );
+}
+
+bool
+fsd_mutex_lock( fsd_mutex_t *mutex )
+{
+	/* Note: The order of checks is significant. */
+	if( mutex->acquired  &&  pthread_equal( mutex->owner, pthread_self() ) )
+		mutex->acquired ++;
+	else
+	 {
+		int errno_ = 0;
+		errno_ = pthread_mutex_lock( &mutex->mutex );
+		if( errno_ == 0 )
+		 {
+			mutex->owner    = pthread_self();
+			mutex->acquired = 1;
+		 }
+		else
+			fsd_exc_raise_sys( errno_ );
+	 }
+	return true;
+}
+
+bool
+fsd_mutex_unlock( fsd_mutex_t *mutex )
+{
+	fsd_assert( mutex->acquired
+			&&  pthread_equal( mutex->owner, pthread_self() ) );
+	if( -- (mutex->acquired) == 0 )
+	 {
+		int errno_ = 0;
+		errno_ = pthread_mutex_unlock( &mutex->mutex );
+		if( errno_ )
+			fsd_exc_raise_sys( errno_ );
+	 }
+	return false;
+}
+
+bool
+fsd_mutex_trylock( fsd_mutex_t *mutex )
+{
+	if( mutex->acquired  &&  pthread_equal( mutex->owner, pthread_self() ) )
+	 {
+		mutex->acquired ++;
+		return true;
+	 }
+	else
+	 {
+		int errno_ = 0;
+		errno_ = pthread_mutex_trylock( &mutex->mutex );
+		switch( errno_ )
+		 {
+			case 0:
+				mutex->owner    = pthread_self();
+				mutex->acquired = 1;
+				return true;
+			case ETIMEDOUT:
+				return false;
+			default:
+				fsd_exc_raise_sys( errno_ );
+		 }
+	 }
+}
+
+int
+fsd_mutex_unlock_times( fsd_mutex_t *mutex )
+{
+	int errno_ = 0;
+	int count = 0;
+	fsd_assert( mutex->acquired
+			&&  pthread_equal( mutex->owner, pthread_self() ) );
+	count = mutex->acquired;
+	mutex->acquired = 0;
+	errno_ = pthread_mutex_unlock( &mutex->mutex );
+	if( errno_ )
+		fsd_exc_raise_sys( errno_ );
+	return count;
+}
+
+void
+fsd_cond_init( fsd_cond_t *cond )
+{
+	int errno_ = 0;
+	errno_ = pthread_cond_init( cond, NULL );
+	if( errno_ )
+		fsd_exc_raise_sys( errno_ );
+}
+
+void
+fsd_cond_destroy( fsd_cond_t *cond )
+{
+	int errno_ = 0;
+	errno_ = pthread_cond_destroy( cond );
+	if( errno_ )
+		fsd_exc_raise_sys( errno_ );
+}
+
+void
+fsd_cond_signal( fsd_cond_t *cond )
+{
+	int errno_ = 0;
+	errno_ = pthread_cond_signal( cond );
+	if( errno_ )
+		fsd_exc_raise_sys( errno_ );
+}
+
+void
+fsd_cond_broadcast( fsd_cond_t *cond )
+{
+	int errno_ = 0;
+	errno_ = pthread_cond_broadcast( cond );
+	if( errno_ )
+		fsd_exc_raise_sys( errno_ );
+}
+
+void
+fsd_cond_wait( fsd_cond_t *cond, fsd_mutex_t *mutex )
+{
+	int errno_ = 0;
+	int acquired_save = mutex->acquired;
+	fsd_assert( mutex->acquired
+			&&  pthread_equal( mutex->owner, pthread_self() ) );
+	errno_ = pthread_cond_wait( cond, &mutex->mutex );
+	if( errno_ == 0 )
+	 {
+		mutex->owner = pthread_self();
+		mutex->acquired = acquired_save;
+	 }
+	else
+		fsd_exc_raise_sys( errno_ );
+}
+
+bool
+fsd_cond_timedwait( fsd_cond_t *cond, fsd_mutex_t *mutex,
+		const struct timespec *abstime )
+{
+	int errno_ = 0;
+	int acquired_save = mutex->acquired;
+	fsd_assert( mutex->acquired
+			&&  pthread_equal( mutex->owner, pthread_self() ) );
+	errno_ = pthread_cond_timedwait( cond, &mutex->mutex, abstime );
+	switch( errno_ )
+	 {
+		case 0:
+			mutex->owner = pthread_self();
+			mutex->acquired = acquired_save;
+			return true;
+		case ETIMEDOUT:
+			mutex->owner = pthread_self();
+			mutex->acquired = acquired_save;
+			return false;
+		default:
+			fsd_exc_raise_sys( errno_ );
+	 }
+}
+
+#endif /* ! HAVE_RECURSIVE_MUTEXES */
+
+
+
+int
+fsd_thread_id(void)
+{
+#if HAVE_GETTID
+	/*
+	 * On Linux 2.6 (with NPTL) getpid() returns
+	 * same value for all threads in single process.
+	 */
+	return (int)gettid();
+#else
+	return (int)getpid();
+#endif
+}
+
Index: trunk/drmaa_utils/drmaa_utils/datetime_tab.y
===================================================================
--- trunk/drmaa_utils/drmaa_utils/datetime_tab.y	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/datetime_tab.y	(revision 1)
@@ -0,0 +1,110 @@
+/* $Id: datetime_tab.y 1450 2008-10-01 22:22:59Z lukasz $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+%{
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+#include <drmaa_utils/datetime_impl.h>
+%}
+
+/* those are Bison extensions */
+%glr-parser
+%pure-parser
+%name-prefix="fsd_dt_"
+%parse-param { fsd_dt_parser_t *parser }
+%parse-param { fsd_dt_lexer_t *lexer }
+%lex-param { fsd_dt_lexer_t *lexer }
+
+%union {
+	fsd_datetime_t datetime;
+	int              integer;
+}
+
+%type<datetime> datetime date time timezone
+%type<integer>  sign
+%token<integer> NUM
+%token LEXER_ERROR
+
+%%
+
+start : datetime { parser->result = $1; }
+	;
+
+datetime
+	: time timezone {
+		$$.mask = $1.mask | $2.mask;
+		$$.year = 0;  $$.month = 0;  $$.day = 0;
+		$$.hour   = $1.hour;
+		$$.minute = $1.minute;
+		$$.second = $1.second;
+		$$.tz_delta = $2.tz_delta;
+	}
+	| date opt_sep time timezone {
+		$$.mask = $1.mask | $3.mask | $4.mask;
+		$$.year   = $1.year;
+		$$.month  = $1.month;
+		$$.day    = $1.day;
+		$$.hour   = $3.hour;
+		$$.minute = $3.minute;
+		$$.second = $3.second;
+		$$.tz_delta = $4.tz_delta;
+	}
+	;
+
+opt_sep
+	:
+	| 'T'
+	;
+
+date
+	: NUM '-' NUM '-' NUM  { $$.year=$1;  $$.month=$3;  $$.day=$5;
+	                         $$.mask=FSD_DT_YEAR|FSD_DT_MONTH|FSD_DT_DAY; }
+	| NUM '-' NUM          { $$.year=0;   $$.month=$1;  $$.day=$3;
+	                         $$.mask=FSD_DT_MONTH|FSD_DT_DAY; }
+	| NUM '/' NUM '/' NUM  { $$.year=$1;  $$.month=$3;  $$.day=$5;
+	                         $$.mask=FSD_DT_YEAR|FSD_DT_MONTH|FSD_DT_DAY; }
+	| NUM '/' NUM          { $$.year=0;   $$.month=$1;  $$.day=$3;
+	                         $$.mask=FSD_DT_MONTH|FSD_DT_DAY; }
+	| NUM                  { $$.year=0;   $$.month=0;   $$.day=$1;
+	                         $$.mask=FSD_DT_DAY; }
+	;
+
+
+time
+	: NUM ':' NUM          { $$.hour=$1;  $$.minute=$3;  $$.second=0;
+	                         $$.mask=FSD_DT_HOUR|FSD_DT_MINUTE; }
+	| NUM ':' NUM ':' NUM  { $$.hour=$1;  $$.minute=$3;  $$.second=$5;
+	                         $$.mask=FSD_DT_HOUR|FSD_DT_MINUTE|FSD_DT_SECOND; }
+	;
+
+timezone
+	:                   { $$.tz_delta=0;  $$.mask=0; }
+	| sign NUM          { $$.tz_delta=$1*3600*$2;  $$.mask=FSD_DT_TZ_DELTA; }
+	| sign NUM ':' NUM  { $$.tz_delta=$1*60*(60*$2+$4);
+	                      $$.mask=FSD_DT_TZ_DELTA; }
+	| 'Z'               { $$.tz_delta=0;  $$.mask=FSD_DT_TZ_DELTA; }
+	;
+
+sign
+	:      { $$ = +1; }
+	| '+'  { $$ = +1; }
+	| '-'  { $$ = -1; }
+	;
+
Index: trunk/drmaa_utils/drmaa_utils/fsd_util.c
===================================================================
--- trunk/drmaa_utils/drmaa_utils/fsd_util.c	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/fsd_util.c	(revision 1)
@@ -0,0 +1,644 @@
+/* $Id: fsd_util.c 185 2010-05-13 17:10:00Z mmatloka $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <unistd.h>
+
+#include <ctype.h>
+#include <errno.h>
+#include <limits.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+
+#include <drmaa_utils/common.h>
+#include <drmaa_utils/util.h>
+
+#ifndef lint
+static char rcsid[]
+#	ifdef __GNUC__
+		__attribute__ ((unused))
+#	endif
+	= "$Id: fsd_util.c 185 2010-05-13 17:10:00Z mmatloka $";
+#endif
+
+
+static char *
+fsd_expand_printf_ph( const char *fmt );
+
+
+void
+fsd_free_vector( char **vector )
+{
+	char **i;
+	if( vector == NULL )
+		return;
+	for( i = vector;  *i != NULL;  i++ )
+		fsd_free( *i );
+	fsd_free( vector );
+}
+
+
+char **
+fsd_copy_vector( const char *const * vector )
+{
+	unsigned n_items, i;
+	char** volatile buf = NULL;
+	char** volatile result = NULL;
+
+	TRY
+	 {
+		if( vector )
+			for( n_items = 0;  vector[ n_items ] != NULL;  n_items++ ) {}
+		else
+			n_items = 0;
+
+		fsd_calloc( buf, n_items+1, char* );
+		for( i = 0;  i < n_items;  i++ )
+			buf[i] = fsd_strdup( vector[i] );
+	 }
+	ELSE
+	 { result = buf;  buf = NULL; }
+	FINALLY
+	 { fsd_free_vector( buf ); }
+	END_TRY
+
+	return result;
+}
+
+
+char *
+fsd_replace( char *str, const char *placeholder, const char *value )
+{
+	size_t ph_len, v_len;
+	char *found = NULL;
+	char* volatile s = str;
+
+	if( str == NULL )
+		fsd_exc_raise_code( FSD_ERRNO_INTERNAL_ERROR );
+
+	ph_len = strlen( placeholder );
+	v_len  = strlen( value );
+
+	do {
+		size_t s_len;
+		s_len = strlen( s );
+		found = strstr( s, placeholder );
+		if( found )
+		 {
+			char* volatile result;
+			size_t pos = found - s;
+			TRY
+			 {
+				fsd_calloc( result, s_len - ph_len + v_len + 1, char );
+				memcpy( result, s, pos );
+				memcpy( result+pos, value, v_len );
+				memcpy( result+pos+v_len, s+pos+ph_len, s_len-pos-ph_len );
+				result[ s_len-ph_len+v_len ] = 0;
+			 }
+			FINALLY
+			 {
+				fsd_free( s );
+				s = result;
+			 }
+			END_TRY
+		 }
+	} while( found );
+
+	return s;
+}
+
+
+char *
+fsd_explode( const char *const *vector, char glue, int n )
+{
+	char* volatile result = NULL;
+	char* volatile buf = NULL;
+	char *s;
+	const char *const *i;
+	unsigned idx, max=(unsigned)n;
+	size_t size =0;
+
+	TRY
+	 {
+		for( i = vector, idx = 0;  idx < max && *i != NULL;  i++, idx++ )
+		 {
+			if( i != vector )
+				size++;
+			size += strlen(*i);
+		 }
+
+		fsd_calloc( buf, size+1, char );
+		s = buf;
+		for( i = vector, idx = 0;  idx < max && *i != NULL;  i++, idx++ )
+		 {
+			if( i != vector )
+				*s++ = glue;
+			strcpy( s, *i );
+			s += strlen( *i );
+		 }
+	 }
+	ELSE
+	 { result = buf;  buf = NULL; }
+	FINALLY
+	 { fsd_free( buf ); }
+	END_TRY
+
+	return result;
+}
+
+
+char *
+fsd_strdup( const char *s )
+{
+	char *result;
+	if( s == NULL )
+		return NULL;
+	result = strdup( s );
+	if( result == NULL )
+		fsd_exc_raise_sys( ENOMEM );
+	return result;
+}
+
+
+char *
+fsd_strndup( const char *s, size_t n )
+{
+	char *result;
+	if( s == NULL )
+		return NULL;
+	result = strndup( s, n );
+	if( result == NULL )
+		fsd_exc_raise_sys( ENOMEM );
+	return result;
+}
+
+
+int
+fsd_atoi( const char *string )
+{
+	const char *s = string;
+	int sign = +1;
+	int v = 0;
+
+	while( isspace(*(const unsigned char*)s) )
+		s++;
+	switch( *s )
+	 {
+		case '+':  sign = +1;  s++;  break;
+		case '-':  sign = -1;  s++;  break;
+		default:  break;
+	 }
+	while( isspace(*(const unsigned char*)s) )
+		s++;
+	if( '0' <= *s  &&  *s <= '9' )
+	 {
+		while( '0' <= *s  &&  *s <= '9' )
+		 {
+			if( v > INT_MAX/10 )
+				goto range_error;
+			v *= 10;
+			v += *s++ - '0';
+			if( v < 0 )
+				goto range_error;
+		 }
+	 }
+	else
+		goto nan_error;
+
+	while( isspace(*(const unsigned char*)s) )
+		s++;
+	if( *s != '\0' )
+		goto nan_error;
+
+	return sign * v;
+
+range_error:
+	fsd_exc_raise_fmt( FSD_ERRNO_INVALID_ARGUMENT,
+			"value out of range: %s", string );
+	return 0;
+
+nan_error:
+		fsd_exc_raise_fmt( FSD_ERRNO_INVALID_ARGUMENT,
+				"not an number: %s", string );
+	return 0;
+}
+
+
+void
+fsd_str_append(
+		bool *truncated,
+		char **p, char *end,
+		const char *fmt, ...
+		)
+{
+	va_list args;
+	va_start( args, fmt );
+	*p += fsd_vsnprintf( truncated, *p, end-*p, fmt, args );
+	va_end( args );
+}
+
+
+size_t
+fsd_snprintf(
+		bool *truncated,
+		char *str, size_t size,
+		const char *fmt, ...
+		)
+{
+	va_list args;
+	size_t result;
+	va_start( args, fmt );
+	result = fsd_vsnprintf( truncated, str, size, fmt, args );
+	va_end( args );
+	return result;
+}
+
+
+size_t
+fsd_vsnprintf(
+		bool *truncated,
+		char *str, size_t size,
+		const char *fmt, va_list args
+		)
+{
+	int n;
+	char *fmt_buf = NULL;
+	fmt_buf = fsd_expand_printf_ph( fmt );
+	if( fmt_buf )
+		fmt = fmt_buf;
+	n = vsnprintf( str, size, fmt, args );
+	if( fmt_buf )
+		fsd_free( fmt_buf );
+	if( 0 <= n  &&  (size_t)n < size )
+	 {}
+	else
+	 {
+		str[size-1] = '\0';
+		*truncated = true;
+	 }
+	return n;
+}
+
+
+char *
+fsd_asprintf( const char *fmt, ... )
+{
+	va_list args;
+	char *result = NULL;
+	va_start( args, fmt );
+	result = fsd_vasprintf( fmt, args );
+	va_end( args );
+	return result;
+}
+
+
+char *
+fsd_vasprintf( const char *fmt, va_list args )
+{
+	char *result = NULL;
+	char *fmt_buf = NULL;
+	int rc;
+	fmt_buf = fsd_expand_printf_ph( fmt );
+	if( fmt_buf )
+		fmt = fmt_buf;
+	rc = vasprintf( &result, fmt, args );
+	if( fmt_buf )
+		fsd_free( fmt_buf );
+	if( rc == -1 )
+		fsd_exc_raise_sys( ENOMEM );
+	return result;
+}
+
+
+/**
+ * ``%m`` placeholder which is a glibc extension
+ * can be safely used in fsd_*printf functions.
+ */
+char *
+fsd_expand_printf_ph( const char *fmt )
+{
+	char* volatile result = NULL;
+
+	if( strstr(fmt, "%m") == NULL )
+		return result;
+
+	TRY
+	 {
+		const char *pos;
+		while( (pos = strstr(fmt, "%m")) != NULL
+				&&  (pos == fmt  ||  pos[-1] != '%') )
+		 {
+			char* volatile errno_msg = NULL;
+			volatile bool own_errno_msg = false;
+			TRY
+			 {
+				char *buf = NULL;
+				size_t fmt_len = strlen(fmt);
+				size_t ph_pos = pos - fmt;
+				size_t errno_msg_len;
+				errno_msg = fsd_astrerror( errno, (bool*)&own_errno_msg );
+				errno_msg_len = strlen(errno_msg);
+				fsd_calloc( buf, fmt_len-2+errno_msg_len+1, char );
+				/* replace ``%m`` with strerror(errno) */
+				strncat( buf, fmt, ph_pos );
+				strcat( buf+ph_pos, errno_msg );
+				strcat( buf+ph_pos+errno_msg_len, fmt+ph_pos+2 );
+				fsd_free( result );
+				fmt = result = buf;
+			 }
+			FINALLY
+			 {
+				if( errno_msg && own_errno_msg )
+					fsd_free( errno_msg );
+			 }
+			END_TRY
+		 }
+	 }
+	EXCEPT_DEFAULT
+	 {
+		fsd_free( result );
+		fsd_exc_reraise();
+	 }
+	END_TRY
+
+	return result;
+}
+
+
+const char *
+fsd_strerror_r( int errnum, char *buffer, size_t buffer_size )
+{
+#	ifdef HAVE_DECL_STRERROR_R
+#		ifdef _GNU_SOURCE
+			return strerror_r( errnum, buffer, buffer_size );
+#		else
+			strerror_r( errnum, buffer, buffer_size );
+			return buffer;
+#		endif /* !_GNU_SOURCE */
+#	else /* assume strerror is thread safe -- returned string is constant */
+		return strerror(errnum);
+#	endif /* ! HAVE_STRERROR_R */
+}
+
+
+char *
+fsd_astrerror( int errnum, bool *malloced )
+{
+#ifdef HAVE_DECL_STRERROR_R
+	char *buffer = NULL;
+	size_t buffer_size = 0;
+	char *result = NULL;
+
+	do {
+		if( buffer_size == 0 )
+			buffer_size = 1024;
+		else
+			buffer_size *= 2;
+		fsd_realloc( buffer, buffer_size, char );
+#		ifdef _GNU_SOURCE
+		result = strerror_r( errnum, buffer, buffer_size );
+		if( result == buffer && strlen(result)+1 == buffer_size )
+			continue;
+#		else
+		if( strerror_r( errnum, buffer, buffer_size ) && errno == ERANGE )
+		 {
+			result = buffer;
+			continue;
+		 }
+#		endif /* !_GNU_SOURCE */
+	} while( false );
+	*malloced = (buffer == result);
+	if( buffer != result )
+		fsd_free( buffer );
+	return result;
+#else /* ! HAVE_DECL_STRERROR_R */
+	/* assume strerror is thread safe -- returned string is constant */
+	*malloced = false;
+	return strerror(errnum);
+#endif /* ! HAVE_DECL_STRERROR_R */
+}
+
+
+void
+fsd_get_time( struct timespec *ts )
+{
+	struct timeval tv;
+	int rc;
+	rc = gettimeofday( &tv, NULL );
+	if( rc )
+		fsd_exc_raise_sys( 0 );
+	else
+	 {
+		ts->tv_sec = tv.tv_sec;
+		ts->tv_nsec = 1000 * tv.tv_usec;
+	 }
+}
+
+
+void
+fsd_ts_add( struct timespec *a, const struct timespec *b )
+{
+	const int nano = 1000000000;
+	a->tv_sec += b->tv_sec;
+	a->tv_nsec += b->tv_nsec;
+	if( a->tv_nsec >= nano )
+	 {
+		a->tv_nsec -= nano;
+		a->tv_sec ++;
+	 }
+}
+
+
+int
+fsd_ts_cmp( const struct timespec *a, const struct timespec *b )
+{
+	if( a->tv_sec != b->tv_sec )
+		return a->tv_sec - b->tv_sec;
+	else
+		return a->tv_nsec - b->tv_nsec;
+}
+
+
+void
+fsd_read_file(
+		const char *filename, bool must_exist,
+		char **content, size_t *length
+		)
+{
+	volatile int fd = -1;
+	char* volatile buffer = NULL;
+	size_t size = 0;
+	size_t capacity = 0;
+	ssize_t n_read;
+
+	TRY
+	 {
+		*content = NULL;
+		*length = 0;
+
+		fd = open( filename, O_RDONLY );
+		if( fd == -1 )
+		 {
+			if( errno==ENOENT && !must_exist )
+			 {
+				*content = NULL;
+				*length = 0;
+			 }
+			else
+				fsd_exc_raise_sys( 0 );
+		 }
+		else
+		 {
+			do {
+				capacity = size + 1024;
+				fsd_realloc( buffer, capacity, char );
+				n_read = read( fd, buffer, capacity-size );
+				if( n_read == (ssize_t)-1 )
+					fsd_exc_raise_sys( 0 );
+				else
+					size += n_read;
+			} while( n_read != 0 );
+
+			fsd_realloc( buffer, size+1, char );
+			buffer[ size ] = '\0';
+		 }
+	 }
+	ELSE
+	 {
+		*content = buffer;  buffer = NULL;
+		*length = size;
+	 }
+	FINALLY
+	 {
+		fsd_free( buffer );
+		if( fd >= 0 )
+			close( fd );
+	 }
+	END_TRY
+}
+
+
+char *
+fsd_getcwd(void)
+{
+	char* volatile buffer = NULL;
+	char* volatile result = NULL;
+	size_t size = 64;
+
+	TRY
+	 {
+		fsd_calloc( buffer, size, char );
+		while( true )
+		 {
+			char *result = getcwd( buffer, size );
+			if( result != NULL )
+				break;
+			else if( errno == ERANGE )
+			 {
+				size *= 2;
+				fsd_realloc( buffer, size, char );
+			 }
+			else
+				fsd_exc_raise_sys( 0 );
+		 }
+		fsd_realloc( buffer, strlen(buffer)+1, char );
+	 }
+	ELSE
+	 { result = buffer;  buffer = NULL; }
+	FINALLY
+	 { fsd_free( buffer ); }
+	END_TRY
+
+	return result;
+}
+
+
+const char *
+fsd_strsignal( int signum )
+{
+#define DETECT_SIG( signame ) \
+	case signame:  return #signame;
+	switch( signum )
+	 {
+		/* signals described by POSIX.1 */
+		DETECT_SIG( SIGHUP  )
+		DETECT_SIG( SIGINT	)
+		DETECT_SIG( SIGQUIT )
+		DETECT_SIG( SIGILL	)
+		DETECT_SIG( SIGABRT )
+		DETECT_SIG( SIGFPE	)
+		DETECT_SIG( SIGKILL )
+		DETECT_SIG( SIGSEGV )
+		DETECT_SIG( SIGPIPE )
+		DETECT_SIG( SIGALRM )
+		DETECT_SIG( SIGTERM )
+		DETECT_SIG( SIGUSR1 )
+		DETECT_SIG( SIGUSR2 )
+		DETECT_SIG( SIGCHLD )
+		DETECT_SIG( SIGCONT )
+		DETECT_SIG( SIGSTOP )
+		DETECT_SIG( SIGTSTP )
+		DETECT_SIG( SIGTTIN )
+		DETECT_SIG( SIGTTOU )
+		/* signals described in SUSv2 and SUSv3 / POSIX 1003.1-2001 */
+#ifdef SIGBUS
+		DETECT_SIG( SIGBUS    )
+#endif
+#ifdef SIGPOLL
+		DETECT_SIG( SIGPOLL	  )
+#endif
+#ifdef SIGPROF
+		DETECT_SIG( SIGPROF	  )
+#endif
+#ifdef SIGSYS
+		DETECT_SIG( SIGSYS	  )
+#endif
+#ifdef SIGTRAP
+		DETECT_SIG( SIGTRAP	  )
+#endif
+#ifdef SIGURG
+		DETECT_SIG( SIGURG	  )
+#endif
+#ifdef SIGVTALRM
+		DETECT_SIG( SIGVTALRM )
+#endif
+#ifdef SIGXCPU
+		DETECT_SIG( SIGXCPU	  )
+#endif
+#ifdef SIGXFSZ
+		DETECT_SIG( SIGXFSZ	  )
+#endif
+		default:
+#		ifdef HAVE_SYS_SIGLIST
+			return sys_siglist[signum];
+#		else
+			return "unknown signal?!";
+#		endif
+			break;
+	 }
+}
+
Index: trunk/drmaa_utils/drmaa_utils/drmaa_attrib.gperf
===================================================================
--- trunk/drmaa_utils/drmaa_utils/drmaa_attrib.gperf	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/drmaa_attrib.gperf	(revision 1)
@@ -0,0 +1,139 @@
+%{
+/* $Id: drmaa_attrib.gperf 1409 2008-09-25 08:59:45Z lukasz $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <drmaa_utils/common.h>
+#include <drmaa_utils/drmaa_attrib.h>
+#include <drmaa_utils/template.h>
+
+#ifndef lint
+static char rcsid[]
+#	ifdef __GNUC__
+		__attribute__ ((unused))
+#	endif
+	= "$Id: drmaa_attrib.gperf 1409 2008-09-25 08:59:45Z lukasz $";
+#endif
+
+extern const fsd_attribute_t drmaa_attributes[];
+#define t(code) \
+	( & drmaa_attributes[ code ] )
+
+%}
+
+%language=ANSI-C
+%includes
+%readonly-tables
+%pic
+%define lookup-function-name drmaa_attrib_lookup
+%struct-type
+struct drmaa_attrib { int name; const fsd_attribute_t *attr; }
+
+%%
+drmaa_remote_command, t(DRMAA_ATTR_REMOTE_COMMAND)
+drmaa_v_argv, t(DRMAA_ATTR_ARGS)
+drmaa_js_state, t(DRMAA_ATTR_JOB_SUBMISSION_STATE)
+drmaa_v_env, t(DRMAA_ATTR_JOB_ENVIRONMENT)
+drmaa_wd, t(DRMAA_ATTR_WORKING_DIRECTORY)
+drmaa_job_category, t(DRMAA_ATTR_JOB_CATEGORY)
+drmaa_native_specification, t(DRMAA_ATTR_NATIVE_SPECIFICATION)
+drmaa_v_email, t(DRMAA_ATTR_EMAIL)
+drmaa_block_email, t(DRMAA_ATTR_BLOCK_EMAIL)
+drmaa_start_time, t(DRMAA_ATTR_START_TIME)
+drmaa_job_name, t(DRMAA_ATTR_JOB_NAME)
+drmaa_input_path, t(DRMAA_ATTR_INPUT_PATH)
+drmaa_output_path, t(DRMAA_ATTR_OUTPUT_PATH)
+drmaa_error_path, t(DRMAA_ATTR_ERROR_PATH)
+drmaa_join_files, t(DRMAA_ATTR_JOIN_FILES)
+drmaa_transfer_files, t(DRMAA_ATTR_TRANSFER_FILES)
+drmaa_deadline_time, t(DRMAA_ATTR_DEADLINE_TIME)
+drmaa_wct_hlimit, t(DRMAA_ATTR_HARD_WALL_CLOCK_TIME_LIMIT)
+drmaa_wct_slimit, t(DRMAA_ATTR_SOFT_WALL_CLOCK_TIME_LIMIT)
+drmaa_duration_hlimit, t(DRMAA_ATTR_HARD_RUN_DURATION_LIMIT)
+drmaa_duration_slimit, t(DRMAA_ATTR_SOFT_RUN_DURATION_LIMIT)
+%%
+
+#undef t
+
+static const fsd_attribute_t *
+drmaa_template_by_name( const fsd_template_t *self, const char *name )
+{
+	const struct drmaa_attrib *found;
+	found = drmaa_attrib_lookup( name, strlen(name) );
+	if( found != NULL )
+		return found->attr;
+	else
+		fsd_exc_raise_fmt(
+				FSD_ERRNO_INVALID_ARGUMENT,
+				"invalid DRMAA attribute name: %s", name
+				);
+}
+
+
+static const fsd_attribute_t *
+drmaa_template_by_code( const fsd_template_t *self, int code )
+{
+	if( 0 <= code  &&  code < DRMAA_N_ATTRIBUTES )
+		return & drmaa_attributes[ code ];
+	else
+		fsd_exc_raise_fmt(
+				FSD_ERRNO_INVALID_ARGUMENT,
+				"invalid attribute code: %d", code
+				);
+}
+
+
+fsd_template_t *
+drmaa_template_new(void)
+{
+	return fsd_template_new(
+			drmaa_template_by_name,
+			drmaa_template_by_code,
+			DRMAA_N_ATTRIBUTES
+			);
+}
+
+
+const fsd_attribute_t drmaa_attributes[ DRMAA_N_ATTRIBUTES ] = {
+	 { "drmaa_remote_command", DRMAA_ATTR_REMOTE_COMMAND, false },
+	 { "drmaa_v_argv", DRMAA_ATTR_ARGS, true },
+	 { "drmaa_js_state", DRMAA_ATTR_JOB_SUBMISSION_STATE, false },
+	 { "drmaa_v_env", DRMAA_ATTR_JOB_ENVIRONMENT, true },
+	 { "drmaa_wd", DRMAA_ATTR_WORKING_DIRECTORY, false },
+	 { "drmaa_job_category", DRMAA_ATTR_JOB_CATEGORY, false },
+	 { "drmaa_native_specification", DRMAA_ATTR_NATIVE_SPECIFICATION, false },
+	 { "drmaa_v_email", DRMAA_ATTR_EMAIL, true },
+	 { "drmaa_block_email", DRMAA_ATTR_BLOCK_EMAIL, false },
+	 { "drmaa_start_time", DRMAA_ATTR_START_TIME, false },
+	 { "drmaa_job_name", DRMAA_ATTR_JOB_NAME, false },
+	 { "drmaa_input_path", DRMAA_ATTR_INPUT_PATH, false },
+	 { "drmaa_output_path", DRMAA_ATTR_OUTPUT_PATH, false },
+	 { "drmaa_error_path", DRMAA_ATTR_ERROR_PATH, false },
+	 { "drmaa_join_files", DRMAA_ATTR_JOIN_FILES, false },
+	 { "drmaa_transfer_files", DRMAA_ATTR_TRANSFER_FILES, false },
+	 { "drmaa_deadline_time", DRMAA_ATTR_DEADLINE_TIME, false },
+	 { "drmaa_wct_hlimit", DRMAA_ATTR_HARD_WALL_CLOCK_TIME_LIMIT, false },
+	 { "drmaa_wct_slimit", DRMAA_ATTR_SOFT_WALL_CLOCK_TIME_LIMIT, false },
+	 { "drmaa_duration_hlimit", DRMAA_ATTR_HARD_RUN_DURATION_LIMIT, false },
+	 { "drmaa_duration_slimit", DRMAA_ATTR_SOFT_RUN_DURATION_LIMIT, false }
+};
+
+/* vim: set ft=c: */
Index: trunk/drmaa_utils/drmaa_utils/conf_impl.h
===================================================================
--- trunk/drmaa_utils/drmaa_utils/conf_impl.h	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/conf_impl.h	(revision 1)
@@ -0,0 +1,81 @@
+/* $Id: conf_impl.h 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+#ifndef __DRMAA_UTILS__CONF_IMPL_H
+#define __DRMAA_UTILS__CONF_IMPL_H
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <drmaa_utils/conf.h>
+
+typedef struct fsd_conf_parser_s fsd_conf_parser_t;
+typedef struct fsd_conf_lexer_s fsd_conf_lexer_t;
+union YYSTYPE;
+struct YYLTYPE;
+typedef unsigned char uchar;
+
+
+int
+fsd_conf_parse( fsd_conf_parser_t *parser, fsd_conf_lexer_t *lexer );
+
+int
+fsd_conf_lex( union YYSTYPE *lvalp, struct YYLTYPE *locp,
+		fsd_conf_lexer_t *lexer );
+
+void
+fsd_conf_error(
+		struct YYLTYPE *locp,
+		fsd_conf_parser_t *parser, fsd_conf_lexer_t *lexer,
+		const char *fmt, ...
+		);
+
+
+/** DRMAA configuration file parser data. */
+struct fsd_conf_parser_s {
+	fsd_conf_lexer_t *lexer;
+
+	/** Parsing result - root of syntax tree. */
+	fsd_conf_dict_t *result;
+
+	int n_errors;  /**< Number of parse/lexical errors. */
+	char **errors;
+};
+
+/** DRMAA configuration file lexical analyzer data. */
+struct fsd_conf_lexer_s {
+	fsd_conf_parser_t *parser;  /**< Parser which use this lexer. */
+	const char *filename; /**< Name of configuration file. */
+
+	const uchar *buffer;  /**< Entire content of parsed configuration file. */
+	size_t buflen;  /**< Length of \a buffer. */
+
+	const uchar *pos;  /**< Current position of lexical analyzer. */
+	int lineno; /**< Current line number (counted from 1). */
+	const uchar *cline;  /**< Points to first character (byte) of current line. */
+};
+
+typedef struct fsd_conf_pair_s {
+	char *key;
+	fsd_conf_option_t *value;
+} fsd_conf_pair_t;
+
+#endif /* __DRMAA_UTILS__CONF_IMPL_H */
+
Index: trunk/drmaa_utils/drmaa_utils/thread.h
===================================================================
--- trunk/drmaa_utils/drmaa_utils/thread.h	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/thread.h	(revision 1)
@@ -0,0 +1,125 @@
+/* $Id: thread.h 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+/**
+ * @file thread.h
+ *
+ * Thread and synchronization primitives.
+ */
+
+#ifndef __DRMAA_UTILS__THREAD_H
+#define __DRMAA_UTILS__THREAD_H
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <pthread.h>
+#include <time.h>
+
+#include <drmaa_utils/compat.h>
+
+/**
+ * @defgroup recursive_mutex  Recursive mutexes implementation.
+ * It uses recursive mutexes if supplied by POSIX threads library
+ * or implements it over plain mutexes.
+ */
+/* @{ */
+
+#if defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP)
+#	define HAVE_RECURSIVE_MUTEXES 1
+#else
+#	define HAVE_RECURSIVE_MUTEXES 0
+#endif /* ! PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP */
+
+
+#if HAVE_RECURSIVE_MUTEXES
+
+	typedef pthread_mutex_t fsd_mutex_t;
+#	define FSD_MUTEX_INITIALIZER  PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
+	typedef pthread_cond_t  fsd_cond_t;
+#	define FSD_COND_INITIALIZER  PTHREAD_COND_INITAILIZER
+
+#else /* !HAVE_RECURSIVE_MUTEXES */
+
+	/**
+	 * Recursive mutex build on top of non-recursive mutex
+	 * (used when recursive mutexes are not provided by POSIX
+	 * thread library).
+	 */
+	typedef struct fsd_mutex_s {
+		pthread_mutex_t mutex; /**< Non-recursive mutex. */
+		pthread_t       owner; /**< Thread which owns critical section. */
+		int             acquired; /**< How many times
+			owning thread acquired this mutex. */
+	} fsd_mutex_t;
+#	define FSD_MUTEX_INITIALIZER  { PTHREAD_MUTEX_INITIALIZER, (pthread_t)-1, 0 }
+	typedef pthread_cond_t  fsd_cond_t;
+#	define FSD_COND_INITIALIZER  PTHREAD_COND_INITAILIZER
+
+#endif /* ! HAVE_RECURSIVE_MUTEXES */
+
+
+/** pthread_mutex_init wrapper.  Initializes recursive mutex. */
+void fsd_mutex_init     ( fsd_mutex_t *mutex );
+void fsd_mutex_destroy  ( fsd_mutex_t *mutex );
+bool fsd_mutex_lock     ( fsd_mutex_t *mutex );
+bool fsd_mutex_unlock   ( fsd_mutex_t *mutex );
+bool fsd_mutex_trylock  ( fsd_mutex_t *mutex );
+
+/**
+ * Try to unlock mutex as many times as possible
+ * returning the count of locks previously granted
+ * to current thread.
+ */
+int fsd_mutex_unlock_times( fsd_mutex_t *mutex );
+
+void fsd_cond_init      ( fsd_cond_t *cond );
+void fsd_cond_destroy   ( fsd_cond_t *cond );
+void fsd_cond_signal    ( fsd_cond_t *cond );
+void fsd_cond_broadcast ( fsd_cond_t *cond );
+void fsd_cond_wait      ( fsd_cond_t *cond, fsd_mutex_t *mutex );
+bool fsd_cond_timedwait ( fsd_cond_t *cond, fsd_mutex_t *mutex,
+		const struct timespec *abstime );
+/* @} */
+
+
+/**
+ * @defgroup thread  Wrapper around POSIX thread functions.
+ */
+/* @{ */
+typedef pthread_t fsd_thread_t;
+/** pthread_create wrapper */
+void fsd_thread_create( fsd_thread_t *thread, void* (*func)(void*), void *arg );
+#define fsd_thread_self    pthraed_self
+#define fsd_thraed_equal   pthread_equal
+#define fsd_thread_exit    pthread_exit
+/** pthread_join wrapper */
+void fsd_thread_join( fsd_thread_t th, void **thread_return );
+/** pthread_detach wrapper */
+void fsd_thread_detach( fsd_thread_t th );
+/* void fsd_thread_cancel( fsd_thread_t th ); */
+/* @} */
+
+
+/** Returns thread identifier. */
+int fsd_thread_id(void);
+
+#endif /* __DRMAA_UTILS__THREAD_H */
+
Index: trunk/drmaa_utils/drmaa_utils/drmaa_base.c
===================================================================
--- trunk/drmaa_utils/drmaa_utils/drmaa_base.c	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/drmaa_base.c	(revision 1)
@@ -0,0 +1,758 @@
+/* $Id: drmaa_base.c 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+/**
+ * @file drmaa_base.c
+ * DRM independant part of DRMAA library.
+ */
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <stdlib.h>
+#include <string.h>
+
+#include <drmaa_utils/common.h>
+#include <drmaa_utils/conf.h>
+#include <drmaa_utils/drmaa_attrib.h>
+#include <drmaa_utils/drmaa_base.h>
+#include <drmaa_utils/drmaa_util.h>
+#include <drmaa_utils/iter.h>
+#include <drmaa_utils/job.h>
+#include <drmaa_utils/logging.h>
+#include <drmaa_utils/lookup3.h>
+#include <drmaa_utils/session.h>
+#include <drmaa_utils/template.h>
+#include <drmaa_utils/util.h>
+
+#ifndef lint
+static char rcsid[]
+#	ifdef __GNUC__
+		__attribute__ ((unused))
+#	endif
+	= "$Id: drmaa_base.c 2 2009-10-12 09:51:22Z mamonski $";
+#endif
+
+
+#define DRMAA_API_BEGIN \
+	volatile int rc = -1; \
+	TRY \
+	 {
+#define DRMAA_API_END \
+		rc = DRMAA_ERRNO_SUCCESS; \
+	 } \
+	EXCEPT_DEFAULT \
+	 { \
+		const fsd_exc_t *e = fsd_exc_get(); \
+		rc = fsd_drmaa_code( e->code(e) ); \
+		strlcpy( error_diagnosis, FSD_SAFE_STR(e->message(e)), error_diag_len ); \
+		fsd_log_return(( "=%d: %s", rc, e->message(e) )); \
+	 } \
+	END_TRY \
+	if( rc < 0 ) \
+	 { \
+		rc = DRMAA_ERRNO_NO_MEMORY; \
+		strlcpy( error_diagnosis, drmaa_strerror(rc), error_diag_len ); \
+	 } \
+	return rc;
+
+
+int
+drmaa_init(
+		const char *contact,
+		char *error_diagnosis, size_t error_diag_len
+		)
+{
+	DRMAA_API_BEGIN
+	fsd_drmaa_singletone_t *global = &_fsd_drmaa_singletone;
+	fsd_log_enter(( "(contact=%s)", contact ));
+
+	fsd_mutex_lock( &global->session_mutex );
+	TRY
+	 {
+		if( global->session != NULL )
+			fsd_exc_raise_code( FSD_DRMAA_ERRNO_ALREADY_ACTIVE_SESSION );
+		global->session = global->new_session( global, contact );
+	 }
+	FINALLY
+	 { fsd_mutex_unlock( &global->session_mutex ); }
+	END_TRY
+
+	fsd_log_return(( " =0" ));
+	DRMAA_API_END
+}
+
+
+int
+drmaa_exit( char *error_diagnosis, size_t error_diag_len )
+{
+	DRMAA_API_BEGIN
+	fsd_drmaa_singletone_t *global = &_fsd_drmaa_singletone;
+	fsd_log_enter(( "()" ));
+
+	fsd_mutex_lock( &global->session_mutex );
+	TRY
+	 {
+		if( global->session != NULL )
+		 {
+			global->session->destroy( global->session );
+			global->session = NULL;
+		 }
+		else
+		 {
+			fsd_exc_raise_code( FSD_DRMAA_ERRNO_NO_ACTIVE_SESSION );
+		 }
+	 }
+	FINALLY
+	 { fsd_mutex_unlock( &global->session_mutex ); }
+	END_TRY
+
+	fsd_log_return(( " =0" ));
+	DRMAA_API_END
+}
+
+
+int
+drmaa_allocate_job_template(
+		drmaa_job_template_t **p_jt,
+		char *error_diagnosis, size_t error_diag_len
+		)
+{
+	DRMAA_API_BEGIN
+	fsd_drmaa_singletone_t *global = &_fsd_drmaa_singletone;
+	fsd_log_enter((""));
+	*p_jt = (drmaa_job_template_t*)global->new_job_template( global );
+	fsd_log_return(( " =0: jt=%p", (void*)*p_jt ));
+	DRMAA_API_END
+}
+
+
+int
+drmaa_delete_job_template(
+		drmaa_job_template_t *drmaa_jt,
+		char *error_diagnosis, size_t error_diag_len
+		)
+{
+	DRMAA_API_BEGIN
+	fsd_template_t *jt = (fsd_template_t*)drmaa_jt;
+	fsd_log_enter(( "(%p)", (void*)jt ));
+	if( jt != NULL )
+		jt->destroy( jt );
+	fsd_log_return(( " =0" ));
+	DRMAA_API_END
+}
+
+
+int
+drmaa_set_attribute(
+		drmaa_job_template_t *drmaa_jt,
+		const char *name, const char *value,
+		char *error_diagnosis, size_t error_diag_len
+		)
+{
+	DRMAA_API_BEGIN
+	fsd_template_t *jt = (fsd_template_t*)drmaa_jt;
+	fsd_log_enter(( "(jt=%p, name='%s', value='%s')",
+				(void*)drmaa_jt, name, value ));
+	if( jt != NULL  &&  name != NULL )
+		jt->set_attr( jt, name, value );
+	else
+		fsd_exc_raise_code( FSD_ERRNO_INVALID_ARGUMENT );
+	fsd_log_return(( " =0" ));
+	DRMAA_API_END
+}
+
+
+int
+drmaa_get_attribute(
+	drmaa_job_template_t *drmaa_jt,
+	const char *name, char *value, size_t value_len,
+	char *error_diagnosis, size_t error_diag_len
+	)
+{
+	DRMAA_API_BEGIN
+	fsd_template_t *jt = (fsd_template_t*)drmaa_jt;
+	const char *v = NULL;
+	fsd_log_enter(( "(jt=%p, name='%s')", (void*)drmaa_jt, name ));
+	if( jt == NULL || name == NULL || value == NULL )
+		fsd_exc_raise_code( FSD_ERRNO_INVALID_ARGUMENT );
+	v = jt->get_attr( jt, name );
+	if( v == NULL )
+		v = "";
+	strlcpy( value, v, value_len );
+	fsd_log_return(( " =0: '%s'", value ));
+	DRMAA_API_END
+}
+
+
+int
+drmaa_set_vector_attribute(
+		drmaa_job_template_t *drmaa_jt,
+		const char *name, const char *value[],
+		char *error_diagnosis, size_t error_diag_len
+		)
+{
+	DRMAA_API_BEGIN
+	fsd_template_t *jt = (fsd_template_t*)drmaa_jt;
+	fsd_log_enter(( "(jt=%p, name='%s', value=...)",
+				(void*)drmaa_jt, name ));
+	if( jt == NULL || name == NULL )
+		fsd_exc_raise_code( FSD_ERRNO_INVALID_ARGUMENT );
+	jt->set_v_attr( jt, name, value );
+	fsd_log_return(( " =0" ));
+	DRMAA_API_END
+}
+
+
+int
+drmaa_get_vector_attribute(
+		drmaa_job_template_t *drmaa_jt,
+		const char *name, drmaa_attr_values_t **out_values,
+		char *error_diagnosis, size_t error_diag_len
+		)
+{
+	DRMAA_API_BEGIN
+	fsd_template_t *jt = (fsd_template_t*)drmaa_jt;
+
+	fsd_log_enter(( "(jt=%p, name='%s')", (void*)drmaa_jt, name ));
+	if( jt == NULL || name == NULL || out_values == NULL )
+		fsd_exc_raise_code( FSD_ERRNO_INVALID_ARGUMENT );
+	*out_values = NULL;
+	*out_values = (drmaa_attr_values_t*)fsd_iter_new(
+			fsd_copy_vector( jt->get_v_attr( jt, name ) ), -1 );
+	fsd_log_return(( " =0" ));
+
+	DRMAA_API_END
+}
+
+
+int
+drmaa_get_attribute_names(
+		drmaa_attr_names_t **values,
+		char *error_diagnosis, size_t error_diag_len )
+{
+	DRMAA_API_BEGIN
+	fsd_drmaa_singletone_t *global = &_fsd_drmaa_singletone;
+	*values = (drmaa_attr_names_t*)global->get_attribute_names( global );
+	DRMAA_API_END
+}
+
+
+int
+drmaa_get_vector_attribute_names(
+		drmaa_attr_names_t **values,
+		char *error_diagnosis, size_t error_diag_len )
+{
+	DRMAA_API_BEGIN
+	fsd_drmaa_singletone_t *global = &_fsd_drmaa_singletone;
+	*values = (drmaa_attr_names_t*)global->get_vector_attribute_names( global );
+	DRMAA_API_END
+}
+
+
+#define iter_function(name, type) \
+int drmaa_get_next_##name( type *values, char *value, size_t value_len ) \
+{ \
+	char error_diagnosis[1]; \
+	size_t error_diag_len = sizeof(error_diagnosis); \
+	DRMAA_API_BEGIN \
+	fsd_iter_t *iter = (fsd_iter_t*)values; \
+	strlcpy( value, iter->next(iter), value_len ); \
+	DRMAA_API_END \
+} \
+int drmaa_get_num_##name##s( type *values, size_t *size ) \
+{ \
+	char error_diagnosis[1]; \
+	size_t error_diag_len = sizeof(error_diagnosis); \
+	DRMAA_API_BEGIN \
+	fsd_iter_t *iter = (fsd_iter_t*)values; \
+	*size = iter->len(iter); \
+	DRMAA_API_END \
+} \
+void drmaa_release_##name##s( type *values ) \
+{ \
+	fsd_iter_t *iter = (fsd_iter_t*)values; \
+	iter->destroy(iter); \
+}
+
+iter_function(attr_name, drmaa_attr_names_t)
+iter_function(attr_value, drmaa_attr_values_t)
+iter_function(job_id, drmaa_job_ids_t)
+
+#undef iter_function
+
+
+int
+drmaa_control(
+		const char *job_id, int action,
+		char *error_diagnosis, size_t error_diag_len
+		)
+{
+	DRMAA_API_BEGIN
+	fsd_drmaa_session_t *volatile session = NULL;
+
+	fsd_log_enter(( "(job_id=%s, action=%s)",
+				job_id, drmaa_control_to_str(action) ));
+
+	if( job_id == NULL )
+		fsd_exc_raise_code( FSD_ERRNO_INVALID_ARGUMENT );
+
+	TRY
+	 {
+		session = fsd_drmaa_session_get();
+		session->control_job( session, job_id, action );
+	 }
+	FINALLY
+	 {
+		if( session )
+			session->release( session );
+	 }
+	END_TRY
+
+	fsd_log_return(( " =0" ));
+	DRMAA_API_END
+}
+
+
+
+int
+drmaa_job_ps(
+		const char *job_id, int *remote_ps,
+		char *error_diagnosis, size_t error_diag_len
+		)
+{
+	DRMAA_API_BEGIN
+	fsd_drmaa_session_t *volatile session = NULL;
+
+	fsd_log_enter(( "(job_id=%s)", job_id ));
+	if( job_id == NULL )
+		fsd_exc_raise_code( FSD_ERRNO_INVALID_ARGUMENT );
+
+	TRY
+	 {
+		session = fsd_drmaa_session_get();
+		session->job_ps( session, job_id, remote_ps );
+	 }
+	FINALLY
+	 {
+		if( session )
+			session->release( session );
+	 }
+	END_TRY
+
+	fsd_log_return(( "(job_id=%s) =0: remote_ps=%s (0x%02x)",
+				job_id, drmaa_job_ps_to_str(*remote_ps), *remote_ps ));
+	DRMAA_API_END
+}
+
+
+
+int
+drmaa_run_job(
+		char *job_id, size_t job_id_len,
+		const drmaa_job_template_t *jt,
+		char *error_diagnosis, size_t error_diag_len
+		)
+{
+	DRMAA_API_BEGIN
+	fsd_drmaa_session_t *volatile session = NULL;
+	char *volatile job_id_buf = NULL;
+	fsd_log_enter(( "(jt=%p)", (void*)jt ));
+	TRY
+	 {
+		session = fsd_drmaa_session_get();
+		job_id_buf = session->run_job( session, (fsd_template_t*)jt ),
+		strlcpy( job_id, job_id_buf, job_id_len );
+	 }
+	FINALLY
+	 {
+		if( session )
+			session->release( session );
+		fsd_free( job_id_buf );
+	 }
+	END_TRY
+
+	fsd_log_return(( " =0: job_id=%s", job_id ));
+	DRMAA_API_END
+}
+
+
+int
+drmaa_run_bulk_jobs(
+		drmaa_job_ids_t **job_ids,
+		const drmaa_job_template_t *jt,
+		int start, int end, int incr,
+		char *error_diagnosis, size_t error_diag_len
+		)
+{
+	DRMAA_API_BEGIN
+	fsd_drmaa_session_t *volatile session = NULL;
+	fsd_log_enter(( "(jt=%p, start=%d, end=%d, incr=%d)",
+		(void*)jt, start, end, incr ));
+	TRY
+	 {
+		if( incr > 0 )
+		 {
+			if( !(0 < start  &&  start <= end) )
+				fsd_exc_raise_code( FSD_ERRNO_INVALID_ARGUMENT );
+		 }
+		else if( incr < 0 )
+		 {
+			if( !(start >= end  &&  end > 0) )
+				fsd_exc_raise_code( FSD_ERRNO_INVALID_ARGUMENT );
+		 }
+		else
+			fsd_exc_raise_code( FSD_ERRNO_INVALID_ARGUMENT );
+
+		session = fsd_drmaa_session_get();
+		*job_ids = (drmaa_job_ids_t*)session->run_bulk(
+				session, (fsd_template_t*)jt,
+				start, end, incr
+				);
+	 }
+	EXCEPT_DEFAULT
+	 {
+		*job_ids = NULL;
+		fsd_exc_reraise();
+	 }
+	FINALLY
+	 {
+		if( session )
+			session->release( session );
+	 }
+	END_TRY
+	fsd_log_return(( " =0" ));
+	DRMAA_API_END
+}
+
+
+
+static struct timespec *
+drmaa_timeout_time( signed long timeout, struct timespec *ts )
+{
+	if( timeout == DRMAA_TIMEOUT_WAIT_FOREVER )
+		return NULL;
+	else
+	 {
+		fsd_get_time( ts );
+		if( timeout != DRMAA_TIMEOUT_NO_WAIT )
+			ts->tv_sec += timeout;
+		return ts;
+	 }
+}
+
+
+int
+drmaa_synchronize(
+		const char **job_ids, signed long timeout,
+		int dispose,
+		char *error_diagnosis, size_t error_diag_len
+		)
+{
+	DRMAA_API_BEGIN
+	fsd_drmaa_session_t *volatile session = NULL;
+	struct timespec ts;
+
+	fsd_log_enter(( "(job_ids={...}, timeout=%ld, dispose=%d)",
+			timeout, dispose ));
+
+	if( job_ids == NULL )
+		fsd_exc_raise_code( FSD_ERRNO_INVALID_ARGUMENT );
+
+	TRY
+	 {
+		session = fsd_drmaa_session_get();
+		session->synchronize( session, job_ids,
+				drmaa_timeout_time(timeout, &ts), dispose );
+	 }
+	FINALLY
+	 {
+		if( session )
+			session->release( session );
+	 }
+	END_TRY
+
+	fsd_log_return(( " =0" ));
+	DRMAA_API_END
+}
+
+
+int
+drmaa_wait(
+		const char *job_id, char *job_id_out, size_t job_id_out_len,
+		int *stat, signed long timeout, drmaa_attr_values_t **rusage,
+		char *error_diagnosis, size_t error_diag_len
+		)
+{
+	DRMAA_API_BEGIN
+	fsd_drmaa_session_t *volatile session = NULL;
+	struct timespec ts;
+	char *result_job_id = NULL;
+
+	fsd_log_enter(( "(job_id=%s, timeout=%ld)", job_id, timeout ));
+
+	TRY
+	 {
+		session = fsd_drmaa_session_get();
+		result_job_id = session->wait(
+				session, job_id, drmaa_timeout_time(timeout, &ts),
+				stat, (fsd_iter_t**)rusage
+				);
+		strlcpy( job_id_out, result_job_id, job_id_out_len );
+	 }
+	FINALLY
+	 {
+		fsd_free( result_job_id );
+		if( session )
+			session->release( session );
+	 }
+	END_TRY
+
+	fsd_log_return(( " =0: job_id=%s", job_id_out ));
+	DRMAA_API_END
+}
+
+
+#if 0
+int
+drmaa_get_contact(
+		char *contact, size_t contact_len,
+		char *error_diagnosis, size_t error_diag_len
+		)
+{
+	DRMAA_API_BEGIN
+	drmaa_session_t *volatile session = NULL;
+	const drmaa_implementation_info_t *impl_info = NULL;
+	const char *result = NULL;
+
+	impl_info = drmaa_get_implementation_info();
+	TRY
+	 {
+		session = drmaa_session_get();
+		if( session->contact )
+			result = session->contact;
+		else
+			result = impl_info->default_contact;
+		strlcpy( contact, result, contact_len );
+	 }
+	EXCEPT( FSD_DRMAA_ERRNO_NO_ACTIVE_SESSION )
+	 {
+		result = impl_info->default_contact;
+		strlcpy( contact, result, contact_len );
+	 }
+	FINALLY
+	 {
+		drmaa_session_release( session );
+	 }
+	END_TRY
+
+	DRMAA_API_END
+}
+#endif
+
+
+int
+drmaa_get_contact(
+		char *contact, size_t contact_len,
+		char *error_diagnosis, size_t error_diag_len
+		)
+{
+	DRMAA_API_BEGIN
+	fsd_drmaa_singletone_t *global = &_fsd_drmaa_singletone;
+	fsd_log_enter(( "" ));
+	strlcpy( contact, global->get_contact( global ), contact_len );
+	fsd_log_return(( " =0: %s", contact ));
+	DRMAA_API_END
+}
+
+
+int
+drmaa_version(
+		unsigned int *major, unsigned int *minor,
+		char *error_diagnosis, size_t error_diag_len
+		)
+{
+	DRMAA_API_BEGIN
+	fsd_drmaa_singletone_t *global = &_fsd_drmaa_singletone;
+	fsd_log_enter(( "" ));
+	global->get_version( global, major, minor );
+	fsd_log_return(( " =0: %d.%d", *major, *minor ));
+	DRMAA_API_END
+}
+
+
+int
+drmaa_get_DRM_system(
+		char *drm_system, size_t drm_system_len,
+		char *error_diagnosis, size_t error_diag_len
+		)
+{
+	DRMAA_API_BEGIN
+	fsd_drmaa_singletone_t *global = &_fsd_drmaa_singletone;
+	fsd_log_enter(( "" ));
+	strlcpy( drm_system, global->get_DRM_system( global ), drm_system_len );
+	fsd_log_return(( " =0: %s", drm_system ));
+	DRMAA_API_END
+}
+
+
+int
+drmaa_get_DRMAA_implementation(
+		char *drmaa_impl, size_t drmaa_impl_len,
+		char *error_diagnosis, size_t error_diag_len
+		)
+{
+	DRMAA_API_BEGIN
+	fsd_drmaa_singletone_t *global = &_fsd_drmaa_singletone;
+	fsd_log_enter(( "" ));
+	strlcpy( drmaa_impl, global->get_DRMAA_implementation( global ), 
+			drmaa_impl_len );
+	fsd_log_return(( " =0: %s", drmaa_impl ));
+	DRMAA_API_END
+}
+
+
+const char *
+drmaa_strerror( int drmaa_errno )
+{
+	return fsd_drmaa_strerror( drmaa_errno );
+}
+
+
+int
+drmaa_read_configuration_file(
+		const char *filename, int must_exist,
+		char *error_diagnosis, size_t error_diag_len
+		)
+{
+	fsd_drmaa_session_t *volatile session = NULL;
+
+	DRMAA_API_BEGIN
+	fsd_log_enter(( "(filename=%s)", filename ));
+	TRY
+	 {
+		session = fsd_drmaa_session_get();
+		session->read_configuration(
+				session, filename, must_exist, NULL, 0 );
+	 }
+	FINALLY
+	 {
+		if( session )
+			session->release( session );
+	 }
+	END_TRY
+
+	fsd_log_return(( " =0" ));
+	DRMAA_API_END
+}
+
+
+int
+drmaa_read_configuration(
+		const char *configuration, size_t configuration_len,
+		char *error_diagnosis, size_t error_diag_len
+		)
+{
+	DRMAA_API_BEGIN
+	fsd_drmaa_session_t *volatile session = NULL;
+	fsd_log_enter(( "(configuration=\"%.*s\")",
+				(int)configuration_len, configuration ));
+	TRY
+	 {
+		session = fsd_drmaa_session_get();
+		session->read_configuration(
+				session, NULL, false, configuration, configuration_len );
+	 }
+	FINALLY
+	 {
+		if( session )
+			session->release( session );
+	 }
+	END_TRY
+	fsd_log_return(( " =0" ));
+	DRMAA_API_END
+}
+
+
+
+fsd_drmaa_session_t *
+fsd_drmaa_session_get(void)
+{
+	fsd_drmaa_session_t *self = NULL;
+	fsd_mutex_lock( &_fsd_drmaa_singletone.session_mutex );
+	self = _fsd_drmaa_singletone.session;
+	fsd_mutex_unlock( &_fsd_drmaa_singletone.session_mutex );
+	if( self != NULL )
+	 {
+		fsd_mutex_lock( &self->mutex );
+		self->ref_cnt ++;
+		fsd_mutex_unlock( &self->mutex );
+	 }
+	else
+		fsd_exc_raise_code( FSD_DRMAA_ERRNO_NO_ACTIVE_SESSION );
+	return self;
+}
+
+
+#define wiffunc( name, args_decl, args_list ) \
+int drmaa_##name args_decl \
+{ \
+	return _fsd_drmaa_singletone.name args_list;\
+}
+
+wiffunc(
+		wifexited,
+		(	int *exited, int stat, char *error_diagnosis, size_t error_diag_len ),
+		( exited, stat, error_diagnosis, error_diag_len )
+		)
+
+wiffunc(
+		wexitstatus,
+		(	int *exit_status, int stat,
+			char *error_diagnosis, size_t error_diag_len ),
+		( exit_status, stat, error_diagnosis, error_diag_len )
+		)
+
+wiffunc(
+		wifsignaled,
+		(	int *signaled, int stat, char *error_diagnosis, size_t error_diag_len ),
+		( signaled, stat, error_diagnosis, error_diag_len )
+		)
+
+wiffunc(
+		wtermsig,
+		(	char *signal, size_t signal_len, int stat,
+			char *error_diagnosis, size_t error_diag_len ),
+		( signal, signal_len, stat, error_diagnosis, error_diag_len )
+		)
+
+wiffunc(
+		wcoredump,
+		(	int *core_dumped, int stat,
+			char *error_diagnosis, size_t error_diag_len ),
+		( core_dumped, stat, error_diagnosis, error_diag_len )
+		)
+
+wiffunc(
+		wifaborted,
+		(	int *aborted, int stat, char *error_diagnosis, size_t error_diag_len ),
+		( aborted, stat, error_diagnosis, error_diag_len )
+		)
+
Index: trunk/drmaa_utils/drmaa_utils/fsd_session.c
===================================================================
--- trunk/drmaa_utils/drmaa_utils/fsd_session.c	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/fsd_session.c	(revision 1)
@@ -0,0 +1,1030 @@
+/* $Id: fsd_session.c 359 2010-11-02 17:47:19Z mamonski $ */
+/*
+ * FedStage DRMAA utilities library
+ * Copyright (C) 2006-2008  FedStage Systems
+ *
+ * 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 <ctype.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <drmaa_utils/conf.h>
+#include <drmaa_utils/drmaa.h>
+#include <drmaa_utils/iter.h>
+#include <drmaa_utils/job.h>
+#include <drmaa_utils/session.h>
+
+#ifndef lint
+static char rcsid[]
+#	ifdef __GNUC__
+		__attribute__ ((unused))
+#	endif
+	= "$Id: fsd_session.c 359 2010-11-02 17:47:19Z mamonski $";
+#endif
+
+
+static void
+fsd_drmaa_session_release( fsd_drmaa_session_t *self );
+
+static void
+fsd_drmaa_session_destroy(
+		fsd_drmaa_session_t *self );
+
+static void
+fsd_drmaa_session_destroy_nowait( fsd_drmaa_session_t *self );
+
+static char*
+fsd_drmaa_session_run_job(
+		fsd_drmaa_session_t *self,
+		const fsd_template_t *jt
+		);
+
+static fsd_iter_t*
+fsd_drmaa_session_run_bulk(
+		fsd_drmaa_session_t *self,
+		const fsd_template_t *jt,
+		int start, int end, int incr
+		);
+
+static void
+fsd_drmaa_session_control_job(
+		fsd_drmaa_session_t *self,
+		const char *job_id, int action
+		);
+
+static void
+fsd_drmaa_session_job_ps(
+		fsd_drmaa_session_t *self,
+		const char *job_id, int *remote_ps
+		);
+
+static void
+fsd_drmaa_session_synchronize(
+		fsd_drmaa_session_t *self,
+		const char **input_job_ids, const struct timespec *timeout,
+		bool dispose
+		);
+
+static char*
+fsd_drmaa_session_wait(
+		fsd_drmaa_session_t *self,
+		const char *job_id, const struct timespec *timeout,
+		int *status, fsd_iter_t **rusage
+		);
+
+static fsd_job_t *
+fsd_drmaa_session_new_job(
+		fsd_drmaa_session_t *self,
+		const char *job_id
+		);
+
+static char*
+fsd_drmaa_session_run_impl(
+		fsd_drmaa_session_t *self,
+		const fsd_template_t *jt, int bulk_incr
+		);
+
+static void
+fsd_drmaa_session_wait_for_single_job(
+		fsd_drmaa_session_t *self,
+		const char *job_id, const struct timespec *timeout,
+		int *status, fsd_iter_t **rusage, bool dispose
+		);
+
+static char*
+fsd_drmaa_session_wait_for_any_job(
+		fsd_drmaa_session_t *self,
+		const struct timespec *timeout,
+		int *status, fsd_iter_t **rusage,
+		bool dispose
+		);
+
+static void
+fsd_drmaa_session_wait_for_job_status_change(
+		fsd_drmaa_session_t *self,
+		fsd_cond_t *wait_condition,
+		fsd_mutex_t *mutex,
+		const struct timespec *timeout
+		);
+
+static void*
+fsd_drmaa_session_wait_thread( fsd_drmaa_session_t *self );
+
+static void
+fsd_drmaa_session_stop_wait_thread( fsd_drmaa_session_t *self );
+
+static void
+fsd_drmaa_session_update_all_jobs_status( fsd_drmaa_session_t *self );
+
+static char**
+fsd_drmaa_session_get_submited_job_ids(
+		fsd_drmaa_session_t *self
+		);
+
+static fsd_job_t*
+fsd_drmaa_session_get_job(
+		fsd_drmaa_session_t *self, const char *job_id
+		);
+
+static void
+fsd_drmaa_session_load_configuration(
+		fsd_drmaa_session_t *self, const char *basename
+		);
+
+static void
+fsd_drmaa_session_read_configuration(
+		fsd_drmaa_session_t *self,
+		const char *filename, bool must_exist,
+		const char *configuration, size_t config_len
+		);
+
+static void
+fsd_drmaa_session_apply_configuration(
+		fsd_drmaa_session_t *self
+		);
+
+
+
+fsd_drmaa_session_t *
+fsd_drmaa_session_new( const char *contact )
+{
+	fsd_drmaa_session_t *volatile self = NULL;
+
+	fsd_log_enter(( "(%s)", contact ));
+	TRY
+	 {
+		fsd_malloc( self, fsd_drmaa_session_t );
+
+		self->release = fsd_drmaa_session_release;
+		self->destroy = fsd_drmaa_session_destroy;
+		self->destroy_nowait = fsd_drmaa_session_destroy_nowait;
+		self->run_job = fsd_drmaa_session_run_job;
+		self->run_bulk = fsd_drmaa_session_run_bulk;
+		self->control_job = fsd_drmaa_session_control_job;
+		self->job_ps = fsd_drmaa_session_job_ps;
+		self->synchronize = fsd_drmaa_session_synchronize;
+		self->wait = fsd_drmaa_session_wait;
+		self->new_job = fsd_drmaa_session_new_job;
+		self->run_impl = fsd_drmaa_session_run_impl;
+		self->wait_for_single_job = fsd_drmaa_session_wait_for_single_job;
+		self->wait_for_any_job = fsd_drmaa_session_wait_for_any_job;
+		self->wait_for_job_status_change =
+			fsd_drmaa_session_wait_for_job_status_change;
+		self->wait_thread = fsd_drmaa_session_wait_thread;
+		self->stop_wait_thread = fsd_drmaa_session_stop_wait_thread;
+		self->update_all_jobs_status = fsd_drmaa_session_update_all_jobs_status;
+		self->get_submited_job_ids = fsd_drmaa_session_get_submited_job_ids;
+		self->get_job = fsd_drmaa_session_get_job;
+		self->load_configuration = fsd_drmaa_session_load_configuration;
+		self->read_configuration = fsd_drmaa_session_read_configuration;
+		self->apply_configuration = fsd_drmaa_session_apply_configuration;
+
+		self->ref_cnt = 1;
+		self->destroy_requested = false;
+		self->contact = NULL;
+		self->jobs = NULL;
+		self->configuration = NULL;
+		self->pool_delay.tv_sec = 5;
+		self->pool_delay.tv_nsec = 0;
+		self->cache_job_state = 0;
+		self->enable_wait_thread = true;
+		self->job_categories = NULL;
+		self->missing_jobs = FSD_REVEAL_MISSING_JOBS;
+		self->wait_thread_started = false;
+		self->wait_thread_run_flag = false;
+
+		fsd_mutex_init( &self->mutex );
+		fsd_cond_init( &self->wait_condition );
+		fsd_cond_init( &self->destroy_condition );
+		fsd_mutex_init( &self->drm_connection_mutex );
+		self->jobs = fsd_job_set_new();
+		self->contact = fsd_strdup( contact );
+	 }
+	EXCEPT_DEFAULT
+	 {
+		if( self != NULL )
+			self->destroy( self );
+		fsd_exc_reraise();
+	 }
+	END_TRY
+
+	return self;
+}
+
+
+void
+fsd_drmaa_session_release( fsd_drmaa_session_t *self )
+{
+	fsd_mutex_lock( &self->mutex );
+	self->ref_cnt--;
+	fsd_assert( self->ref_cnt > 0 );
+	if( self->ref_cnt == 1 )
+		fsd_cond_broadcast( &self->destroy_condition );
+	fsd_mutex_unlock( &self->mutex );
+}
+
+
+void
+fsd_drmaa_session_destroy( fsd_drmaa_session_t *self )
+{
+	bool already_destroying = false;
+
+	fsd_log_enter(( "" ));
+	fsd_mutex_lock( &self->mutex );
+	TRY
+	 {
+		if( self->destroy_requested )
+			already_destroying = true;
+		else
+		 {
+			self->destroy_requested = true;
+			fsd_cond_broadcast( &self->wait_condition );
+		 }
+	 }
+	FINALLY
+	 { fsd_mutex_unlock( &self->mutex ); }
+	END_TRY
+
+	if( already_destroying )
+	 { /* XXX: actually it can not happen in current implementation
+				when using DRMAA API */
+		self->release( self );
+		fsd_exc_raise_code( FSD_DRMAA_ERRNO_NO_ACTIVE_SESSION );
+	 }
+
+	self->jobs->signal_all( self->jobs );
+
+	fsd_mutex_lock( &self->mutex );
+	TRY
+	 {
+		while( self->ref_cnt > 1 )
+			fsd_cond_wait( &self->destroy_condition, &self->mutex );
+		fsd_log_debug(("started = %d  run_flag = %d", self->wait_thread_started, self->wait_thread_run_flag ));
+		if( self->wait_thread_started )
+			self->stop_wait_thread( self );
+	 }
+	FINALLY
+	 { fsd_mutex_unlock( &self->mutex ); }
+	END_TRY
+
+	self->destroy_nowait( self );
+	fsd_log_return(( "" ));
+}
+
+
+void
+fsd_drmaa_session_destroy_nowait( fsd_drmaa_session_t *self )
+{
+	fsd_log_enter(( "" ));
+	fsd_conf_dict_destroy( self->configuration );
+	fsd_free( self->contact );
+
+	if( self->jobs )
+		self->jobs->destroy( self->jobs );
+
+	fsd_mutex_destroy( &self->mutex );
+	fsd_cond_destroy( &self->wait_condition );
+	fsd_cond_destroy( &self->destroy_condition );
+	fsd_mutex_destroy( &self->drm_connection_mutex );
+
+	fsd_free( self );
+	fsd_log_return(( "" ));
+}
+
+
+char *
+fsd_drmaa_session_run_job(
+		fsd_drmaa_session_t *self,
+		const fsd_template_t *jt )
+{
+	return self->run_impl( self, jt, -1 );
+}
+
+
+fsd_iter_t *
+fsd_drmaa_session_run_bulk(
+		fsd_drmaa_session_t *self,
+		const fsd_template_t *jt,
+		int start, int end, int incr )
+{
+	volatile unsigned n_jobs;
+	char **volatile result = NULL;
+
+	if( incr > 0 )
+		n_jobs = (end-start) / incr + 1;
+	else
+		n_jobs = (start-end) / -incr + 1;
+
+	TRY
+	 {
+		unsigned i;
+		int idx;
+		fsd_calloc( result, n_jobs + 1, char* );
+		for( i=0, idx=start;  i < n_jobs;  i++, idx+=incr )
+			result[i] = self->run_impl( self, jt, idx );
+	 }
+	EXCEPT_DEFAULT
+	 {
+		if( result )
+			fsd_free_vector( result );
+		fsd_exc_reraise();
+	 }
+	END_TRY
+
+	return fsd_iter_new( result, -1 );
+}
+
+
+void
+fsd_drmaa_session_control_job(
+		fsd_drmaa_session_t *self,
+		const char *job_id, int action )
+{
+	char **job_ids = NULL;
+	char **i;
+
+	TRY
+	 {
+		if( !strcmp( job_id, DRMAA_JOB_IDS_SESSION_ALL ) )
+			job_ids = self->get_submited_job_ids( self );
+		else
+		 {
+			fsd_calloc( job_ids, 2, char* );
+			job_ids[0] = fsd_strdup( job_id );
+		 }
+
+		for( i = job_ids;  *i != NULL;  i++ )
+		 {
+			fsd_job_t *job = NULL;
+			TRY
+			 {
+				job = self->get_job( self, *i );
+				if( job == NULL )
+				 {
+					if( !strcmp( job_id, DRMAA_JOB_IDS_SESSION_ALL ) )
+					 { /* job was just removed from session */ }
+					else
+						job = self->new_job( self, *i );
+				 }
+				if( job )
+					job->control( job, action );
+			 }
+			FINALLY
+			 {
+				if ( job )
+				 job->release( job );
+			 }
+			END_TRY
+		 }
+	 }
+	FINALLY
+	 {
+		fsd_free_vector( job_ids );
+	 }
+	END_TRY
+}
+
+
+void
+fsd_drmaa_session_job_ps(
+		fsd_drmaa_session_t *self, const char *job_id, int *remote_ps )
+{
+	fsd_job_t *volatile job = NULL;
+	TRY
+	 {
+		job = self->get_job( self, job_id );
+		if( job == NULL )
+			job = self->new_job( self, job_id );
+		fsd_log_debug((" job->last_update_time = %u",  (unsigned int)job->last_update_time));
+		if( time(NULL) - job->last_update_time >= self->cache_job_state
+				|| job->state == DRMAA_PS_UNDETERMINED ) 
+		  {
+			fsd_log_debug(("updating status of job: %s ", job_id));
+			job->update_status( job );
+			job->last_update_time = time(NULL);
+		  }
+		*remote_ps = job->state;
+	 }
+	FINALLY
+	 {
+		if( job )
+			job->release( job );
+	 }
+	END_TRY
+}
+
+
+void
+fsd_drmaa_session_synchronize(
+		fsd_drmaa_session_t *self,
+		const char **input_job_ids, const struct timespec *timeout,
+		bool dispose
+		)
+{
+	volatile bool wait_for_all = false;
+	char **volatile job_ids_buf = NULL;
+	const char **job_ids = NULL;
+	const char **i;
+
+	fsd_log_enter(( "(job_ids={...}, timeout=..., dispose=%d)",
+			(int)dispose ));
+
+	if( input_job_ids == NULL )
+		fsd_exc_raise_code( FSD_ERRNO_INVALID_ARGUMENT );
+
+	TRY
+	 {
+		for( i = input_job_ids;  *i != NULL;  i++ )
+			if( !strcmp(*i, DRMAA_JOB_IDS_SESSION_ALL) )
+				wait_for_all = true;
+
+		if( wait_for_all )
+		 {
+			job_ids_buf = self->get_submited_job_ids( self );
+			job_ids = (const char**)job_ids_buf;
+		 }
+		else
+			job_ids = input_job_ids;
+
+		for( i = job_ids;  *i != NULL;  i++ )
+			TRY
+			 {
+				self->wait_for_single_job( self, *i, timeout, NULL, NULL, dispose );
+			 }
+			EXCEPT( FSD_DRMAA_ERRNO_INVALID_JOB )
+			 { /* job was ripped by another thread */ }
+			END_TRY
+	 }
+	FINALLY
+	 {
+		fsd_free_vector( job_ids_buf );
+	 }
+	END_TRY
+}
+
+
+char *
+fsd_drmaa_session_wait(
+		fsd_drmaa_session_t *self,
+		const char *job_id, const struct timespec *timeout,
+		int *stat, fsd_iter_t **rusage
+		)
+{
+	if( 0==strcmp(job_id, DRMAA_JOB_IDS_SESSION_ANY) )
+		return self->wait_for_any_job( self, timeout, stat, rusage, true );
+	else
+	 {
+		self->wait_for_single_job( self, job_id, timeout, stat, rusage, true );
+		return fsd_strdup( job_id );
+	 }
+}
+
+
+fsd_job_t *
+fsd_drmaa_session_new_job( fsd_drmaa_session_t *self, const char *job_id )
+{
+	fsd_job_t *job;
+	job = fsd_job_new( fsd_strdup(job_id) );
+	job->session = self;
+	return job;
+}
+
+
+char *
+fsd_drmaa_session_run_impl(
+		fsd_drmaa_session_t *self,
+		const fsd_template_t *jt, int bulk_incr )
+{
+	fsd_exc_raise_code( FSD_ERRNO_NOT_IMPLEMENTED );
+}
+
+
+void
+fsd_drmaa_session_wait_for_single_job(
+		fsd_drmaa_session_t *self,
+		const char *job_id, const struct timespec *timeout,
+		int *status, fsd_iter_t **rusage,
+		bool dispose
+		)
+{
+	fsd_job_t *volatile job = NULL;
+	volatile bool locked = false;
+
+	fsd_log_enter(( "(%s)", job_id ));
+	TRY
+	 {
+		job = self->get_job( self, job_id );
+		if( job == NULL )
+			fsd_exc_raise_fmt( FSD_DRMAA_ERRNO_INVALID_JOB,
+					"Job '%s' not found in DRMS queue", job_id );
+		job->update_status( job );
+		while( !self->destroy_requested  &&  job->state < DRMAA_PS_DONE )
+		 {
+			bool signaled = true;
+			fsd_log_debug(( "fsd_drmaa_session_wait_for_single_job: "
+						"waiting for %s to terminate", job_id ));
+			if( self->enable_wait_thread )
+			 {
+				if( timeout )
+					signaled = fsd_cond_timedwait(
+							&job->status_cond, &job->mutex, timeout );
+				else
+				 {
+					fsd_cond_wait( &job->status_cond, &job->mutex );
+				 }
+				if( !signaled )
+					fsd_exc_raise_code( FSD_DRMAA_ERRNO_EXIT_TIMEOUT );
+			 }
+			else
+			 {
+				self->wait_for_job_status_change(
+						self, &job->status_cond, &job->mutex, timeout );
+			 }
+
+			fsd_log_debug(( "fsd_drmaa_session_wait_for_single_job: woken up" ));
+			if( !self->enable_wait_thread )
+				job->update_status( job );
+		 }
+
+		if( self->destroy_requested )
+			fsd_exc_raise_code( FSD_DRMAA_ERRNO_EXIT_TIMEOUT );
+
+		job->get_termination_status( job, status, rusage );
+		if( dispose )
+		 {
+			job->release( job ); /*release mutex in order to ensure proper order of locking: first job_set mutex then job mutex */
+
+			locked = fsd_mutex_lock( &self->mutex );
+
+			job = self->get_job( self, job_id );
+			if (job != NULL)
+			 {
+				self->jobs->remove( self->jobs, job );
+				job->flags |= FSD_JOB_DISPOSED;
+			 }
+			else
+			 {
+				fsd_log_error(("Some other thread has already reaped job %s", job_id ));
+			 }
+
+			locked = fsd_mutex_unlock( &self->mutex );
+		 }
+	 }
+	FINALLY
+	 {
+		if ( job )
+			job->release( job );
+		if ( locked )
+			fsd_mutex_unlock( &self->mutex );
+	 }
+	END_TRY
+	fsd_log_return((""));
+}
+
+
+char *
+fsd_drmaa_session_wait_for_any_job(
+		fsd_drmaa_session_t *self,
+		const struct timespec *timeout,
+		int *status, fsd_iter_t **rusage,
+		bool dispose
+		)
+{
+	fsd_job_set_t *set = self->jobs;
+	fsd_job_t *volatile job = NULL;
+	char *volatile job_id = NULL;
+	volatile bool locked = false;
+
+	fsd_log_enter(( "" ));
+
+	TRY
+	 {
+		while( job == NULL )
+		 {
+			bool signaled = true;
+
+			if( self->destroy_requested )
+				fsd_exc_raise_code( FSD_DRMAA_ERRNO_NO_ACTIVE_SESSION );
+
+			if( !self->enable_wait_thread )
+				self->update_all_jobs_status( self );
+
+			locked = fsd_mutex_lock( &self->mutex );
+			if( set->empty( set ) )
+				fsd_exc_raise_msg( FSD_DRMAA_ERRNO_INVALID_JOB,
+						"No job found to be waited for" );
+
+			if( (job = set->find_terminated( set )) != NULL )
+				break;
+
+			if( self->destroy_requested )
+				fsd_exc_raise_code( FSD_DRMAA_ERRNO_NO_ACTIVE_SESSION );
+			if( self->enable_wait_thread )
+			 {
+				fsd_log_debug(( "wait_for_any_job: waiting for wait thread" ));
+				if( timeout )
+					signaled = fsd_cond_timedwait(
+							&self->wait_condition, &self->mutex, timeout );
+				else
+					fsd_cond_wait( &self->wait_condition, &self->mutex );
+			 }
+			else
+			 {
+				fsd_log_debug(( "wait_for_any_job: waiting for next check" ));
+				self->wait_for_job_status_change( self,
+						&self->wait_condition, &self->mutex, timeout );
+			 }
+			locked = fsd_mutex_unlock( &self->mutex );
+			fsd_log_debug((
+						"wait_for_any_job: woken up; signaled=%d", signaled ));
+
+			if( !signaled )
+				fsd_exc_raise_code( FSD_DRMAA_ERRNO_EXIT_TIMEOUT );
+
+		 }
+		fsd_log_debug(( "wait_for_any_job: waiting finished" ));
+
+		job_id = fsd_strdup( job->job_id );
+		job->get_termination_status( job, status, rusage );
+	 }
+	EXCEPT_DEFAULT
+	 {
+		if( job_id )
+			fsd_free( job_id );
+		fsd_exc_reraise();
+	 }
+	FINALLY
+	 {
+		if( job )
+		 {
+			if( fsd_exc_get() == NULL  &&  dispose )
+			 {
+				set->remove( set, job );
+				job->flags |= FSD_JOB_DISPOSED;
+			 }
+			job->release( job );
+		 }
+		if( locked )
+			fsd_mutex_unlock( &self->mutex );
+	 }
+	END_TRY
+
+	fsd_log_return(( " =%s", job_id ));
+	return job_id;
+}
+
+
+void
+fsd_drmaa_session_wait_for_job_status_change(
+		fsd_drmaa_session_t *self,
+		fsd_cond_t *wait_condition,
+		fsd_mutex_t *mutex,
+		const struct timespec *timeout
+		)
+{
+	struct timespec ts, *next_check = &ts;
+	bool status_changed;
+
+	if( timeout )
+		fsd_log_enter((
+					"(timeout=%ld.%09ld)",
+					timeout->tv_sec, timeout->tv_nsec ));
+	else
+		fsd_log_enter(( "(timeout=(null))" ));
+	fsd_get_time( next_check );
+	fsd_ts_add( next_check, &self->pool_delay );
+	if( timeout  &&  fsd_ts_cmp( timeout, next_check ) < 0 )
+		next_check = (struct timespec*)timeout;
+	fsd_log_debug(( "wait_for_job_status_change: waiting untill %ld.%09ld",
+				next_check->tv_sec, next_check->tv_nsec ));
+	status_changed = fsd_cond_timedwait(
+			wait_condition, mutex, next_check );
+	if( !status_changed  &&  next_check == timeout )
+		fsd_exc_raise_code( FSD_DRMAA_ERRNO_EXIT_TIMEOUT );
+
+	fsd_log_return(( ": next_check=%ld.%09ld, status_changed=%d",
+				next_check->tv_sec, next_check->tv_nsec,
+				(int)status_changed
+				));
+}
+
+
+void *
+fsd_drmaa_session_wait_thread( fsd_drmaa_session_t *self )
+{
+	struct timespec ts, *next_check = &ts;
+        bool volatile locked = false;
+
+	fsd_log_enter(( "" ));
+	locked = fsd_mutex_lock( &self->mutex );
+	TRY
+	 {
+		while( self->wait_thread_run_flag )
+			TRY
+			 {
+				fsd_log_debug(( "wait thread: next iteration" ));
+				self->update_all_jobs_status( self );
+				fsd_cond_broadcast( &self->wait_condition );
+				
+				fsd_get_time( next_check );
+				fsd_ts_add( next_check, &self->pool_delay );
+				fsd_cond_timedwait( &self->wait_condition, &self->mutex, next_check );
+				
+			 }
+			EXCEPT_DEFAULT
+			 {
+				const fsd_exc_t *e = fsd_exc_get();
+				fsd_log_error(( "wait thread: <%d:%s>", e->code(e), e->message(e) ));
+			 }
+			END_TRY
+	 }
+	FINALLY
+	 { 
+		if (locked)
+			fsd_mutex_unlock( &self->mutex ); 
+	 }
+	END_TRY
+
+	fsd_log_return(( " =NULL" ));
+	return NULL;
+}
+
+
+void
+fsd_drmaa_session_stop_wait_thread( fsd_drmaa_session_t *self )
+{
+	volatile int lock_count = 0;
+	fsd_log_enter(( "" ));
+	fsd_mutex_lock( &self->mutex );
+	TRY
+	 {
+		fsd_log_debug(("started = %d  run_flag = %d", self->wait_thread_started, self->wait_thread_run_flag ));
+		if( self->wait_thread_started )
+		 {
+			self->wait_thread_run_flag = false;
+			fsd_log_debug(("started = %d  run_flag = %d", self->wait_thread_started, self->wait_thread_run_flag ));
+			fsd_cond_broadcast( &self->wait_condition );
+			TRY
+			 {
+				lock_count = fsd_mutex_unlock_times( &self->mutex );
+				fsd_thread_join( self->wait_thread_handle, NULL );
+			 }
+			FINALLY
+			 {
+				int i;
+				for( i = 0;  i < lock_count;  i++ )
+					fsd_mutex_lock( &self->mutex );
+			 }
+			END_TRY
+			self->wait_thread_started = false;
+		 }
+
+	 }
+	FINALLY
+	 { fsd_mutex_unlock( &self->mutex ); }
+	END_TRY
+	fsd_log_return(( "" ));
+}
+
+
+void
+fsd_drmaa_session_update_all_jobs_status(
+		fsd_drmaa_session_t *self )
+{
+	char **volatile job_ids = NULL;
+	fsd_log_enter(( "" ));
+	TRY
+	 {
+		const char **i;
+		fsd_job_t *volatile job = NULL;
+		job_ids = self->get_submited_job_ids( self );
+		for( i = (const char **)job_ids;  *i;  i++ )
+			TRY
+			 {
+				job = self->get_job( self, *i );
+				if( job )
+					job->update_status( job );
+			 }
+			FINALLY
+			 {
+				if( job )
+					job->release( job );
+			 }
+			END_TRY
+	 }
+	FINALLY
+	 {
+		fsd_free_vector( job_ids );
+	 }
+	END_TRY
+	fsd_log_return(( "" ));
+}
+
+
+char **
+fsd_drmaa_session_get_submited_job_ids( fsd_drmaa_session_t *self )
+{
+	return self->jobs->get_all_job_ids( self->jobs );
+}
+
+
+fsd_job_t *
+fsd_drmaa_session_get_job( fsd_drmaa_session_t *self, const char *job_id )
+{
+	return self->jobs->get( self->jobs, job_id );
+}
+
+
+void
+fsd_drmaa_session_load_configuration(
+		fsd_drmaa_session_t *self, const char *basename
+		)
+{
+	char *volatile system_conf = NULL;
+	char *volatile user_conf = NULL;
+	char *volatile varname = NULL;
+	TRY
+	 {
+		const char *home;
+		const char *envvalue;
+		char *i;
+
+		system_conf = fsd_asprintf( "/etc/%s.conf", basename );
+
+		home = getenv( "HOME" );
+		if( home == NULL )
+		 { home = ""; }
+		user_conf = fsd_asprintf( "%s/.%s.conf", home, basename );
+
+		varname = fsd_asprintf( "%s_CONF", basename );
+		for( i = varname;  *i;  i++ )
+			*i = toupper( *(unsigned char*)i );
+		envvalue = getenv( varname );
+
+		self->configuration = fsd_conf_read(
+			 self->configuration, system_conf, false, NULL, 0 );
+		self->configuration = fsd_conf_read(
+			 self->configuration, user_conf, false, NULL, 0 );
+		if( envvalue )
+			self->configuration = fsd_conf_read(
+				 self->configuration, envvalue, true, NULL, 0 );
+		self->apply_configuration( self );
+	 }
+	FINALLY
+	 {
+		fsd_free( system_conf );
+		fsd_free( user_conf );
+		fsd_free( varname );
+	 }
+	END_TRY
+}
+
+
+void
+fsd_drmaa_session_read_configuration(
+		fsd_drmaa_session_t *self,
+		const char *filename, bool must_exist,
+		const char *configuration, size_t configuration_len
+		)
+{
+	self->configuration = fsd_conf_read(
+		 self->configuration,
+		 filename, must_exist,
+		 configuration, configuration_len );
+	self->apply_configuration( self );
+}
+
+
+void
+fsd_drmaa_session_apply_configuration( fsd_drmaa_session_t *self )
+{
+	fsd_conf_option_t *pool_delay = NULL;
+	fsd_conf_option_t *cache_job_state = NULL;
+	fsd_conf_option_t *wait_thread = NULL;
+	fsd_conf_option_t *job_categories = NULL;
+	fsd_conf_option_t *missing_jobs = NULL;
+
+	fsd_log_enter((""));
+	if( self->configuration  !=  NULL ) {
+
+		pool_delay = fsd_conf_dict_get(
+				self->configuration, "pool_delay" );
+		cache_job_state = fsd_conf_dict_get(
+				self->configuration, "cache_job_state" );
+		wait_thread = fsd_conf_dict_get(
+				self->configuration, "wait_thread" );
+		job_categories = fsd_conf_dict_get(
+				self->configuration, "job_categories" );
+		missing_jobs = fsd_conf_dict_get(
+				self->configuration, "missing_jobs" );
+	}
+
+	if( pool_delay )
+	 {
+		if( pool_delay->type == FSD_CONF_INTEGER
+				&&  pool_delay->val.integer > 0 )
+		 {
+			fsd_log_debug(("pool_delay=%d", pool_delay->val.integer));
+			self->pool_delay.tv_sec = pool_delay->val.integer;
+		 }
+		else
+			fsd_exc_raise_msg(
+					FSD_ERRNO_INTERNAL_ERROR,
+					"configuration: 'pool_delay' must be positive integer"
+					);
+	 }
+	if( cache_job_state )
+	 {
+		if( cache_job_state->type == FSD_CONF_INTEGER
+				&&   cache_job_state->val.integer >= 0 )
+		 {
+			fsd_log_debug(("cache_job_state=%d", cache_job_state->val.integer));
+			self->cache_job_state = cache_job_state->val.integer;
+		 }
+		else
+			fsd_exc_raise_msg(
+					FSD_ERRNO_INTERNAL_ERROR,
+					"configuration: 'cache_job_state' must be nonnegative integer"
+					);
+	 }
+	if( wait_thread )
+	 {
+		if( wait_thread->type == FSD_CONF_INTEGER )
+		 {
+
+			fsd_log_debug(("wait_thread=%d", wait_thread->val.integer));
+			self->enable_wait_thread = (wait_thread->val.integer != 0 );
+		 }
+		else
+			fsd_exc_raise_msg(
+					FSD_ERRNO_INTERNAL_ERROR,
+					"configuration: 'wait_thread' should be 0 or 1"
+					);
+	 }
+	if( job_categories )
+	 {
+		if( job_categories->type == FSD_CONF_DICT )
+			self->job_categories = job_categories->val.dict;
+		else
+			fsd_exc_raise_msg(
+					FSD_ERRNO_INTERNAL_ERROR,
+					"configuration: 'job_categories' should be dictionary"
+					);
+	 }
+	if( missing_jobs )
+	 {
+		bool ok = true;
+		if( missing_jobs->type != FSD_CONF_STRING )
+		 {
+			const char *value = missing_jobs->val.string;
+			if( !strcmp( value, "ignore" ) )
+				self->missing_jobs = FSD_IGNORE_MISSING_JOBS;
+			else if( !strcmp( value, "ignore-queued" ) )
+				self->missing_jobs = FSD_IGNORE_QUEUED_MISSING_JOBS;
+			else if( !strcmp( value, "reveal" ) )
+				self->missing_jobs = FSD_REVEAL_MISSING_JOBS;
+			else
+				ok = false;
+		 }
+		else
+			ok = false;
+
+		if( !ok )
+			fsd_exc_raise_msg(
+					FSD_ERRNO_INTERNAL_ERROR,
+					"configuration: 'missing_jobs' should be one of: "
+					"'ignore', 'ignore-queued' or 'reveal'"
+					);
+	 }
+
+	if( self->enable_wait_thread  &&  !self->wait_thread_started )
+	 {
+		fsd_log_debug(("Starting wait thread"));
+		self->wait_thread_run_flag = true;
+		fsd_thread_create( &self->wait_thread_handle,
+				(void*(*)(void*))self->wait_thread, self );
+		self->wait_thread_started = true;
+		fsd_log_debug(( "wait thread started" ));
+	 }
+	else if( !self->enable_wait_thread  &&  self->wait_thread_started )
+	 {
+		fsd_log_debug(("Stopping wait thread"));
+		self->stop_wait_thread( self );
+	 }
+
+	fsd_log_return((""));
+}
+
Index: trunk/drmaa_utils/drmaa_utils/environ.c
===================================================================
--- trunk/drmaa_utils/drmaa_utils/environ.c	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/environ.c	(revision 1)
@@ -0,0 +1,241 @@
+/* $Id: environ.c 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ * FedStage DRMAA utilities library
+ * Copyright (C) 2006-2008  FedStage Systems
+ *
+ * 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 <string.h>
+#include <stdlib.h>
+
+#include <drmaa_utils/common.h>
+#include <drmaa_utils/environ.h>
+#include <drmaa_utils/lookup3.h>
+
+#ifndef lint
+static char rcsid[]
+#	ifdef __GNUC__
+		__attribute__ ((unused))
+#	endif
+	= "$Id: environ.c 2 2009-10-12 09:51:22Z mamonski $";
+#endif
+
+
+static void
+fsd_environ_destroy( fsd_environ_t *self )
+{
+	unsigned i;
+	fsd_environ_item_t *j;
+	if( self->_table )
+	 {
+		for( i = 0;  i < self->_table_size;  i++ )
+			for( j = self->_table[i];  j != NULL; )
+			 {
+				fsd_environ_item_t *to_delete = j;
+				j = j->next;
+				fsd_free( to_delete->name );
+				fsd_free( to_delete->value );
+				fsd_free( to_delete );
+			 }
+		fsd_free( self->_table );
+	 }
+	fsd_free( self );
+}
+
+static const char *
+fsd_environ_get( fsd_environ_t *self, const char *name )
+{
+	uint32_t hash;
+	const fsd_environ_item_t *i;
+	hash = hashstr( name, strlen(name), 0 );
+	hash &= self->_table_size - 1;
+	for( i = self->_table[hash];  i != NULL;  i = i->next )
+		if( strcmp( i->name, name ) == 0 )
+			return i->value;
+	return NULL;
+}
+
+static void
+fsd_environ_set( fsd_environ_t *self, char *name, char *value )
+{
+	uint32_t hash;
+	fsd_environ_item_t *i;
+	fsd_environ_item_t *item = NULL;
+	bool replaced = false;
+
+	TRY
+	 {
+		hash = hashstr( name, strlen(name), 0 );
+		hash &= self->_table_size - 1;
+		for( i = self->_table[hash];  i != NULL;  i = i->next )
+		 {
+			if( strcmp( i->name, name ) == 0 )
+			 {
+				fsd_free( i->value );
+				i->value = value;
+				replaced = true;
+				break;
+			 }
+		 }
+
+		if( !replaced )
+		 {
+			fsd_malloc( item, fsd_environ_item_t );
+			item->next = self->_table[hash];
+			item->name = name;
+			item->value = value;
+			self->_table[hash] = item;
+		 }
+	 }
+	EXCEPT_DEFAULT
+	 {
+		fsd_free( name );
+		fsd_free( value );
+		fsd_exc_reraise();
+	 }
+	END_TRY
+}
+
+static void
+fsd_environ_update( fsd_environ_t *self, const char *const envp[] )
+{
+	const char *const *i;
+	for( i = envp;  *i;  i++ )
+	 {
+		const char *eq;
+		char *volatile name = NULL;
+		char *volatile value = NULL;
+		eq = strchr( *i, '=' );
+		if( eq == NULL )
+			fsd_exc_raise_code( FSD_ERRNO_INVALID_VALUE_FORMAT );
+		name = fsd_strndup( *i, eq-*i );
+		TRY
+		 { value = fsd_strdup( eq+1 ); }
+		EXCEPT_DEFAULT
+		 { fsd_free(name); fsd_exc_reraise(); }
+		END_TRY
+		self->set( self, name, value );
+	 }
+}
+
+static char **
+fsd_environ_list( fsd_environ_t *self )
+{
+	uint32_t i;
+	const fsd_environ_item_t *j;
+	char **volatile result = NULL;
+	unsigned items = 0;
+
+	TRY
+	 {
+		for( i = 0;  i < self->_table_size;  i++ )
+			for( j = self->_table[i];  j != NULL;  j = j->next )
+			 {
+				items++;
+				fsd_realloc( result, items+1, char* );
+				result[items] = NULL;
+				result[items-1] = fsd_asprintf( "%s=%s", j->name, j->value );
+			 }
+	 }
+	EXCEPT_DEFAULT
+	 {
+		fsd_free_vector( result );
+		fsd_exc_reraise();
+	 }
+	END_TRY
+
+	i = 0;
+	while (result[i])
+	 {
+		fsd_log_debug(("enc[%d]=%s",i, result[i]));
+		i++;
+	 }
+
+	return result;
+}
+
+static fsd_environ_t *
+fsd_environ_apply( fsd_environ_t *self )
+{
+	uint32_t i;
+	const fsd_environ_item_t *j;
+	fsd_environ_t *volatile saved_state =NULL;
+	TRY
+	 {
+		saved_state = fsd_environ_new( NULL );
+		for( i = 0;  i < self->_table_size;  i++ )
+			for( j = self->_table[i];  j != NULL;  j = j->next )
+			 {
+				const char *value = getenv( j->name );
+				if( value )
+					saved_state->set( saved_state,
+							fsd_strdup(j->name), fsd_strdup(value) );
+				setenv( j->name, j->value, 1 );
+			 }
+	 }
+	EXCEPT_DEFAULT
+	 {
+		if( saved_state )
+			saved_state->destroy( saved_state );
+		fsd_exc_reraise();
+	 }
+	END_TRY
+	return saved_state;
+}
+
+static void
+fsd_environ_restore( fsd_environ_t *self, fsd_environ_t *saved_state )
+{
+	uint32_t i;
+	const fsd_environ_item_t *j;
+	for( i = 0;  i < self->_table_size;  i++ )
+		for( j = self->_table[i];  j != NULL;  j = j->next )
+		 {
+			const char *value = saved_state->get( saved_state, j->name );
+			if( value )
+				setenv( j->name, value, 1 );
+			else
+				unsetenv( j->name );
+		 }
+}
+
+fsd_environ_t *
+fsd_environ_new( const char *const envp[] )
+{
+	fsd_environ_t *volatile self = NULL;
+	TRY
+	 {
+		fsd_malloc( self, fsd_environ_t );
+		self->destroy = fsd_environ_destroy;
+		self->get = fsd_environ_get;
+		self->set = fsd_environ_set;
+		self->update = fsd_environ_update;
+		self->list = fsd_environ_list;
+		self->apply = fsd_environ_apply;
+		self->restore = fsd_environ_restore;
+		self->_table_size = 256;
+		fsd_calloc( self->_table, self->_table_size, fsd_environ_item_t* );
+		if( envp )
+			self->update( self, envp );
+	 }
+	EXCEPT_DEFAULT
+	 {
+		if( self )
+			self->destroy( self );
+	 }
+	END_TRY
+	return self;
+}
+
Index: trunk/drmaa_utils/drmaa_utils/drmaa_util.c
===================================================================
--- trunk/drmaa_utils/drmaa_utils/drmaa_util.c	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/drmaa_util.c	(revision 1)
@@ -0,0 +1,431 @@
+/* $Id: drmaa_util.c 290 2010-09-14 15:58:09Z mmatloka $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <string.h>
+#include <stdlib.h>
+
+#include <drmaa_utils/common.h>
+#include <drmaa_utils/drmaa_attrib.h>
+#include <drmaa_utils/drmaa_util.h>
+#include <drmaa_utils/logging.h>
+#include <drmaa_utils/template.h>
+#include <drmaa_utils/util.h>
+
+#ifndef lint
+static char rcsid[]
+#	ifdef __GNUC__
+		__attribute__ ((unused))
+#	endif
+	= "$Id: drmaa_util.c 290 2010-09-14 15:58:09Z mmatloka $";
+#endif
+
+
+static char *
+fsd_expand_drmaa_ph_expand( fsd_expand_drmaa_ph_t *self, char *s, unsigned set )
+{
+	unsigned mask;
+
+	for(
+			mask = 1;
+			mask <= FSD_DRMAA_PH_INCR;
+			mask <<= 1
+			)
+	 {
+		const char *ph;
+		const char *value;
+
+		switch( mask )
+		 {
+			case FSD_DRMAA_PH_HD:
+				ph = DRMAA_PLACEHOLDER_HD;
+				value = self->home_directory;
+				break;
+			case FSD_DRMAA_PH_WD:
+				ph = DRMAA_PLACEHOLDER_WD;
+				value = self->working_directory;
+				break;
+			case FSD_DRMAA_PH_INCR:
+				ph = DRMAA_PLACEHOLDER_INCR;
+				value = self->bulk_incr;
+				break;
+			default:
+				fsd_assert( false );
+		 }
+		if( value == NULL )
+			value = "";
+
+		if( mask & set )
+			s = fsd_replace( s, ph, value );
+		else if( strstr( s, ph ) != NULL )
+		 {
+			fsd_log_warning((
+						"'%s' can not be expanded in '%s'; removing from string",
+						ph, s ));
+			s = fsd_replace( s, ph, "" );
+		 }
+	 }
+
+	return s;
+}
+
+static void
+fsd_expand_drmaa_ph_set( fsd_expand_drmaa_ph_t *self,
+		int placeholder, char *value )
+{
+	char **var;
+	switch( placeholder )
+	 {
+		case FSD_DRMAA_PH_HD:  var = &self->home_directory;  break;
+		case FSD_DRMAA_PH_WD:  var = &self->working_directory;  break;
+		case FSD_DRMAA_PH_INCR:  var = &self->bulk_incr;  break;
+		default:
+			fsd_free( value );
+			fsd_exc_raise_code( FSD_ERRNO_INVALID_ARGUMENT );
+	 }
+	fsd_free( *var );
+	*var = value;
+}
+
+static void
+fsd_expand_drmaa_ph_destroy( fsd_expand_drmaa_ph_t *self )
+{
+	if( self != NULL )
+	 {
+		fsd_free( self->home_directory );
+		fsd_free( self->working_directory );
+		fsd_free( self->bulk_incr );
+		fsd_free( self );
+	 }
+}
+
+fsd_expand_drmaa_ph_t *
+fsd_expand_drmaa_ph_new(
+		char *home_directory,
+		char *working_directory,
+		char *bulk_incr
+		)
+{
+	fsd_expand_drmaa_ph_t *volatile p = NULL;
+
+	TRY
+	 {
+		fsd_expand_drmaa_ph_t *self;
+		fsd_malloc( p, fsd_expand_drmaa_ph_t );
+		self = p;
+		self->expand = fsd_expand_drmaa_ph_expand;
+		self->set = fsd_expand_drmaa_ph_set;
+		self->destroy = fsd_expand_drmaa_ph_destroy;
+
+		self->home_directory = home_directory;
+		self->working_directory = working_directory;
+		self->bulk_incr = bulk_incr;
+
+		if( self->home_directory == NULL )
+		 {
+			const char *home = getenv("HOME");
+			if( home == NULL )
+				home = "";
+			self->home_directory = fsd_strdup( home );
+		 }
+
+		if( self->working_directory == NULL )
+			self->working_directory = fsd_strdup(
+					self->home_directory );
+		else
+			self->working_directory = self->expand( self,
+					self->working_directory, FSD_DRMAA_PH_HD );
+
+		if( self->bulk_incr == NULL )
+			self->bulk_incr = fsd_strdup( "" );
+	 }
+	EXCEPT_DEFAULT
+	 {
+		if( p )
+			p->destroy( p );
+		fsd_exc_reraise();
+	 }
+	END_TRY
+	return p;
+}
+
+
+const char *
+drmaa_control_to_str( int action )
+{
+	switch( action )
+	 {
+		case DRMAA_CONTROL_SUSPEND:
+			return "suspend";
+		case DRMAA_CONTROL_RESUME:
+			return "resume";
+		case DRMAA_CONTROL_HOLD:
+			return "hold";
+		case DRMAA_CONTROL_RELEASE:
+			return "release";
+		case DRMAA_CONTROL_TERMINATE:
+			return "terminate";
+		default:
+			return "?";
+	 }
+}
+
+
+const char *
+drmaa_job_ps_to_str( int ps )
+{
+	switch( ps )
+	 {
+		case DRMAA_PS_UNDETERMINED:
+			return "undetermined";
+		case DRMAA_PS_QUEUED_ACTIVE:
+			return "queued_active";
+		case DRMAA_PS_SYSTEM_ON_HOLD:
+			return "system_on_hold";
+		case DRMAA_PS_USER_ON_HOLD:
+			return "user_on_hold";
+		case DRMAA_PS_USER_SYSTEM_ON_HOLD:
+			return "user_system_on_hold";
+		case DRMAA_PS_RUNNING:
+			return "running";
+		case DRMAA_PS_SYSTEM_SUSPENDED:
+			return "system_suspended";
+		case DRMAA_PS_USER_SUSPENDED:
+			return "user_suspended";
+		case DRMAA_PS_USER_SYSTEM_SUSPENDED:
+			return "user_system_suspended";
+		case DRMAA_PS_DONE:
+			return "done";
+		case DRMAA_PS_FAILED:
+			return "failed";
+		default:
+			return "?";
+	 }
+}
+
+
+int
+fsd_drmaa_code( int fsd_errno )
+{
+	switch( fsd_errno )
+	 {
+		case FSD_ERRNO_SUCCESS:
+			return DRMAA_ERRNO_SUCCESS;
+		case FSD_ERRNO_INTERNAL_ERROR:
+			return DRMAA_ERRNO_INTERNAL_ERROR;
+		case FSD_ERRNO_NO_MEMORY:
+			return DRMAA_ERRNO_NO_MEMORY;
+		case FSD_ERRNO_INVALID_ARGUMENT:
+			return DRMAA_ERRNO_INVALID_ARGUMENT;
+		case FSD_ERRNO_INVALID_VALUE:
+			return DRMAA_ERRNO_INVALID_ATTRIBUTE_VALUE;
+		case FSD_ERRNO_INVALID_VALUE_FORMAT:
+			return DRMAA_ERRNO_INVALID_ATTRIBUTE_FORMAT;
+		case FSD_ERRNO_STOP_ITERATION:
+			return DRMAA_ERRNO_NO_MORE_ELEMENTS;
+		case FSD_ERRNO_NOT_IMPLEMENTED:
+			return DRMAA_ERRNO_INTERNAL_ERROR;
+		case FSD_ERRNO_NOT_INITIALIZED:
+			return DRMAA_ERRNO_NO_ACTIVE_SESSION;
+		case FSD_ERRNO_TIMEOUT:
+			return DRMAA_ERRNO_EXIT_TIMEOUT;
+		case FSD_ERRNO_AUTH_FAILURE:
+			return DRMAA_ERRNO_AUTH_FAILURE;
+		case FSD_ERRNO_AUTHZ_FAILURE:
+			return DRMAA_ERRNO_AUTH_FAILURE;
+		case FSD_ERRNO_TRY_LATER:
+			return DRMAA_ERRNO_TRY_LATER;
+		case FSD_ERRNO_DRM_COMMUNICATION_FAILURE:
+			return DRMAA_ERRNO_DRM_COMMUNICATION_FAILURE;
+		case FSD_ERRNO_DRMS_INIT_FAILED:
+			return DRMAA_ERRNO_DRMS_INIT_FAILED;
+		case FSD_ERRNO_DRMS_EXIT_ERROR:
+			return DRMAA_ERRNO_DRMS_EXIT_ERROR;
+		case FSD_ERRNO_DENIED_BY_DRM:
+			return DRMAA_ERRNO_DENIED_BY_DRM;
+
+		case FSD_DRMAA_ERRNO_NO_ACTIVE_SESSION:
+			return DRMAA_ERRNO_NO_ACTIVE_SESSION;
+		case FSD_DRMAA_ERRNO_INVALID_CONTACT_STRING:
+			return DRMAA_ERRNO_INVALID_CONTACT_STRING;
+		case FSD_DRMAA_ERRNO_DEFAULT_CONTACT_STRING_ERROR:
+			return DRMAA_ERRNO_DEFAULT_CONTACT_STRING_ERROR;
+		case FSD_DRMAA_ERRNO_NO_DEFAULT_CONTACT_STRING_SELECTED:
+			return DRMAA_ERRNO_NO_DEFAULT_CONTACT_STRING_SELECTED;
+		case FSD_DRMAA_ERRNO_ALREADY_ACTIVE_SESSION:
+			return DRMAA_ERRNO_ALREADY_ACTIVE_SESSION;
+		case FSD_DRMAA_ERRNO_INVALID_ATTRIBUTE_FORMAT:
+			return DRMAA_ERRNO_INVALID_ATTRIBUTE_FORMAT;
+		case FSD_DRMAA_ERRNO_INVALID_ATTRIBUTE_VALUE:
+			return DRMAA_ERRNO_INVALID_ATTRIBUTE_VALUE;
+		case FSD_DRMAA_ERRNO_CONFLICTING_ATTRIBUTE_VALUES:
+			return DRMAA_ERRNO_CONFLICTING_ATTRIBUTE_VALUES;
+		case FSD_DRMAA_ERRNO_INVALID_JOB:
+			return DRMAA_ERRNO_INVALID_JOB;
+		case FSD_DRMAA_ERRNO_RESUME_INCONSISTENT_STATE:
+			return DRMAA_ERRNO_RESUME_INCONSISTENT_STATE;
+		case FSD_DRMAA_ERRNO_SUSPEND_INCONSISTENT_STATE:
+			return DRMAA_ERRNO_SUSPEND_INCONSISTENT_STATE;
+		case FSD_DRMAA_ERRNO_HOLD_INCONSISTENT_STATE:
+			return DRMAA_ERRNO_HOLD_INCONSISTENT_STATE;
+		case FSD_DRMAA_ERRNO_RELEASE_INCONSISTENT_STATE:
+			return DRMAA_ERRNO_RELEASE_INCONSISTENT_STATE;
+		case FSD_DRMAA_ERRNO_EXIT_TIMEOUT:
+			return DRMAA_ERRNO_EXIT_TIMEOUT;
+		case FSD_DRMAA_ERRNO_NO_RUSAGE:
+			return DRMAA_ERRNO_NO_RUSAGE;
+
+		default:
+			return DRMAA_ERRNO_INTERNAL_ERROR;
+	 }
+}
+
+
+int
+fsd_errno_from_drmaa_code( int drmaa_errno )
+{
+	switch( drmaa_errno )
+	 {
+		case DRMAA_ERRNO_SUCCESS:
+			return FSD_ERRNO_SUCCESS;
+		case DRMAA_ERRNO_INTERNAL_ERROR:
+			return FSD_ERRNO_INTERNAL_ERROR;
+		case DRMAA_ERRNO_DRM_COMMUNICATION_FAILURE:
+			return FSD_ERRNO_DRM_COMMUNICATION_FAILURE;
+		case DRMAA_ERRNO_AUTH_FAILURE:
+			return FSD_ERRNO_AUTHZ_FAILURE;
+		case DRMAA_ERRNO_INVALID_ARGUMENT:
+			return FSD_ERRNO_INVALID_ARGUMENT;
+		case DRMAA_ERRNO_NO_ACTIVE_SESSION:
+			return FSD_ERRNO_NOT_INITIALIZED;
+		case DRMAA_ERRNO_NO_MEMORY:
+			return FSD_ERRNO_NO_MEMORY;
+		case DRMAA_ERRNO_INVALID_CONTACT_STRING:
+			return FSD_DRMAA_ERRNO_INVALID_CONTACT_STRING;
+		case DRMAA_ERRNO_DEFAULT_CONTACT_STRING_ERROR:
+			return FSD_DRMAA_ERRNO_DEFAULT_CONTACT_STRING_ERROR;
+		case DRMAA_ERRNO_NO_DEFAULT_CONTACT_STRING_SELECTED:
+			return FSD_DRMAA_ERRNO_NO_DEFAULT_CONTACT_STRING_SELECTED;
+		case DRMAA_ERRNO_DRMS_INIT_FAILED:
+			return FSD_ERRNO_DRMS_INIT_FAILED;
+		case DRMAA_ERRNO_ALREADY_ACTIVE_SESSION:
+			return FSD_DRMAA_ERRNO_ALREADY_ACTIVE_SESSION;
+		case DRMAA_ERRNO_DRMS_EXIT_ERROR:
+			return FSD_ERRNO_DRMS_EXIT_ERROR;
+		case DRMAA_ERRNO_INVALID_ATTRIBUTE_FORMAT:
+			return FSD_DRMAA_ERRNO_INVALID_ATTRIBUTE_FORMAT;
+		case DRMAA_ERRNO_INVALID_ATTRIBUTE_VALUE:
+			return FSD_DRMAA_ERRNO_INVALID_ATTRIBUTE_VALUE;
+		case DRMAA_ERRNO_CONFLICTING_ATTRIBUTE_VALUES:
+			return FSD_DRMAA_ERRNO_CONFLICTING_ATTRIBUTE_VALUES;
+		case DRMAA_ERRNO_TRY_LATER:
+			return FSD_ERRNO_TRY_LATER;
+		case DRMAA_ERRNO_DENIED_BY_DRM:
+			return FSD_ERRNO_DENIED_BY_DRM;
+		case DRMAA_ERRNO_INVALID_JOB:
+			return FSD_DRMAA_ERRNO_INVALID_JOB;
+		case DRMAA_ERRNO_RESUME_INCONSISTENT_STATE:
+			return FSD_DRMAA_ERRNO_RESUME_INCONSISTENT_STATE;
+		case DRMAA_ERRNO_SUSPEND_INCONSISTENT_STATE:
+			return FSD_DRMAA_ERRNO_SUSPEND_INCONSISTENT_STATE;
+		case DRMAA_ERRNO_HOLD_INCONSISTENT_STATE:
+			return FSD_DRMAA_ERRNO_HOLD_INCONSISTENT_STATE;
+		case DRMAA_ERRNO_RELEASE_INCONSISTENT_STATE:
+			return FSD_DRMAA_ERRNO_RELEASE_INCONSISTENT_STATE;
+		case DRMAA_ERRNO_EXIT_TIMEOUT:
+			return FSD_DRMAA_ERRNO_EXIT_TIMEOUT;
+		case DRMAA_ERRNO_NO_RUSAGE:
+			return FSD_DRMAA_ERRNO_NO_RUSAGE;
+		case DRMAA_ERRNO_NO_MORE_ELEMENTS:
+			return FSD_ERRNO_STOP_ITERATION;
+		default:
+			fsd_assert(false);
+			return FSD_ERRNO_INTERNAL_ERROR;
+	 }
+}
+
+
+const char *
+fsd_drmaa_strerror( int drmaa_errno )
+{
+	switch( drmaa_errno )
+	 {
+		case DRMAA_ERRNO_SUCCESS:
+			return "Success.";
+		case DRMAA_ERRNO_INTERNAL_ERROR:
+			return "Unexpected or internal DRMAA error.";
+		case DRMAA_ERRNO_DRM_COMMUNICATION_FAILURE:
+			return "Could not contact DRM system for this request.";
+		case DRMAA_ERRNO_AUTH_FAILURE:
+			return "Authorization failure.";
+		case DRMAA_ERRNO_INVALID_ARGUMENT:
+			return "Invalid argument value.";
+		case DRMAA_ERRNO_NO_ACTIVE_SESSION:
+			return "No active DRMAA session.";
+		case DRMAA_ERRNO_NO_MEMORY:
+			return "Not enough memory.";
+		case DRMAA_ERRNO_INVALID_CONTACT_STRING:
+			return "Invalid contact string.";
+		case DRMAA_ERRNO_DEFAULT_CONTACT_STRING_ERROR:
+			return "Can not determine default contact to DRM system.";
+		case DRMAA_ERRNO_NO_DEFAULT_CONTACT_STRING_SELECTED:
+			return "Contact to DRM must be set explicitly "
+				"because there is no default.";
+		case DRMAA_ERRNO_DRMS_INIT_FAILED:
+			return "Unable to initialize DRM system.";
+		case DRMAA_ERRNO_ALREADY_ACTIVE_SESSION:
+			return "DRMAA session already exist.";
+		case DRMAA_ERRNO_DRMS_EXIT_ERROR:
+			return "Disengagement from the DRM system failed.";
+		case DRMAA_ERRNO_INVALID_ATTRIBUTE_FORMAT:
+			return "Invalid format of job attribute.";
+		case DRMAA_ERRNO_INVALID_ATTRIBUTE_VALUE:
+			return "Invalid value of job attribute.";
+		case DRMAA_ERRNO_CONFLICTING_ATTRIBUTE_VALUES:
+			return "Value of attribute conflicts with other attribute value.";
+		case DRMAA_ERRNO_TRY_LATER:
+			return "DRM system is overloaded.  Try again later.";
+		case DRMAA_ERRNO_DENIED_BY_DRM:
+			return "DRM rejected job due to its configuration or job attributes.";
+		case DRMAA_ERRNO_INVALID_JOB:
+			return "Job does not exist in DRMs queue.";
+		case DRMAA_ERRNO_RESUME_INCONSISTENT_STATE:
+			return "Can not resume job (not in valid state).";
+		case DRMAA_ERRNO_SUSPEND_INCONSISTENT_STATE:
+			return "Can not suspend job (not in valid state).";
+		case DRMAA_ERRNO_HOLD_INCONSISTENT_STATE:
+			return "Can not hold job (not in valid state).";
+		case DRMAA_ERRNO_RELEASE_INCONSISTENT_STATE:
+			return "Can not release job (not in valid state).";
+		case DRMAA_ERRNO_EXIT_TIMEOUT:
+			return "Waiting for job to terminate finished due to time-out.";
+		case DRMAA_ERRNO_NO_RUSAGE:
+			return "Job finished but resource usage information "
+				"and/or termination status could not be provided.";
+		case DRMAA_ERRNO_NO_MORE_ELEMENTS:
+			return "Vector have no more elements.";
+
+		default:
+			return "Unknown DRMAA error code!?";
+	 }
+}
+
Index: trunk/drmaa_utils/drmaa_utils/datetime_impl.h
===================================================================
--- trunk/drmaa_utils/drmaa_utils/datetime_impl.h	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/datetime_impl.h	(revision 1)
@@ -0,0 +1,73 @@
+/* $Id: datetime_impl.h 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+/**
+ * @file datetime_impl.h
+ * DRMAA date/time parser - Bison interface functions.
+ */
+#ifndef __DRMAA_UTILS__DATETIME_IMPL_H
+#define __DRMAA_UTILS__DATETIME_IMPL_H
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <drmaa_utils/datetime.h>
+
+/** @addtogroup datetime */
+/* @{ */
+
+typedef struct fsd_dt_parser_s fsd_dt_parser_t;
+typedef struct fsd_dt_lexer_s fsd_dt_lexer_t;
+union YYSTYPE;
+
+/** Date/time parser data. */
+struct fsd_dt_parser_s {
+	fsd_dt_lexer_t *lexer;  /**< Lexical analyzer. */
+	fsd_datetime_t result;  /**< Parsing result. */
+	int n_errors; /**< Number of parse errors. */
+};
+
+/** Date/time lexical analyzer. */
+struct fsd_dt_lexer_s {
+	fsd_dt_parser_t *parser;  /**< Date/time parser. */
+	const unsigned char *begin; /**< Begin of parsed string. */
+	const unsigned char *end;   /**< End of parsed string. */
+	const unsigned char *p;     /**< Scanner position
+		(points to first not parsed character). */
+};
+
+/** Parser interface function (Bison generated). */
+int fsd_dt_parse( fsd_dt_parser_t *parser, fsd_dt_lexer_t *lexer );
+
+/**
+ * Error reporting function (hand written).
+ */
+void fsd_dt_error(
+		fsd_dt_parser_t *parser, fsd_dt_lexer_t *lexer,
+		const char *fmt, ...
+		);
+
+/** Lexer interface (hand written). */
+int fsd_dt_lex( union YYSTYPE *lvalp, fsd_dt_lexer_t *lexer );
+
+/* @} */
+
+#endif /* __DRMAA_UTILS__DATETIME_IMPL_H */
+
Index: trunk/drmaa_utils/drmaa_utils/compat.c
===================================================================
--- trunk/drmaa_utils/drmaa_utils/compat.c	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/compat.c	(revision 1)
@@ -0,0 +1,162 @@
+/* $Id: compat.c 138 2010-04-29 17:13:31Z mamonski $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <errno.h>
+#include <string.h>
+#include <assert.h>
+#include <drmaa_utils/compat.h>
+
+
+#ifndef lint
+static char rcsid[]
+#	ifdef __GNUC__
+		__attribute__ ((unused))
+#	endif
+	= "$Id: compat.c 138 2010-04-29 17:13:31Z mamonski $";
+#endif
+
+
+#ifndef HAVE_STRLCPY
+size_t
+strlcpy( char *dest, const char *src, size_t size )
+{
+	size_t result = 0;
+	if( size == 0 )
+		return 0;
+	while( *src  &&  --size > 0 )
+	 {
+		*dest++ = *src++;
+		result++;
+	 }
+	*dest++ = '\0';
+	return result;
+}
+#endif /* ! HAVE_STRLCPY */
+
+
+#ifndef HAVE_STRNDUP
+char *
+strndup( const char *s, size_t n )
+{
+	char *result;
+	if( s == NULL )
+		return NULL;
+	result = calloc( n + 1, sizeof(char) );
+
+	if( result == NULL )
+	 {
+		errno = ENOMEM;
+		return NULL;
+	 }
+
+	strlcpy( result, s, n + 1 );
+	return result;
+}
+#endif /* ! HAVE_STRNDUP */
+
+
+#ifndef HAVE_ASPRINTF
+int
+asprintf( char **strp, const char *fmt, ... )
+{
+	va_list args;
+	int result;
+	va_start( args, fmt );
+	result = vasprintf( strp, fmt, args );
+	va_end( args );
+	return result;
+}
+#endif /* ! HAVE_ASPRINTF */
+
+
+#ifndef HAVE_VASPRINTF
+int
+vasprintf( char **strp, const char *format, va_list ap )
+{
+	int size, check_size;
+	char *buf = NULL;
+
+#ifdef HAVE_VA_COPY
+	va_list aq;
+
+	va_copy(aq, ap);
+#else
+#  ifdef HAVE___VA_COPY
+	va_list aq;
+
+	__va_copy(aq, ap);
+#  endif
+#endif
+
+	*strp = NULL;
+
+#ifndef HAVE_C99_VSNPRINTF
+	{
+		int res;
+		char *tmp;
+
+		size = 128;
+		do {
+			size *= 2;
+			if (!(tmp = realloc(buf, size))) {
+				if (buf)
+					free(buf);
+				return -1;
+			}
+			buf = tmp;
+			/* XXX we're assuming here there's no va_copy on this system */
+			res = vsnprintf(buf, size, format, ap);
+		} while (res == -1);
+	}
+#else
+	{
+		char tmp[2];
+
+		/* on Solaris vsnprintf fails if buf is empty, so use a small one */
+		size = vsnprintf(tmp, sizeof(tmp), format, ap);
+		if (!(buf = malloc(size + 1)))
+			return -1;
+	}
+#endif
+
+#ifdef HAVE_VA_COPY
+	check_size = vsnprintf(buf, size + 1, format, aq);
+	va_end(aq);
+#else
+#  ifdef HAVE___VA_COPY
+	check_size = vsnprintf(buf, size + 1, format, aq);
+	va_end(aq);
+#  else
+	check_size = vsnprintf(buf, size + 1, format, ap);
+#  endif
+#endif
+	assert(check_size <= size);
+	*strp = buf;
+	return 0;
+}
+#endif
+
Index: trunk/drmaa_utils/drmaa_utils/drmaa_base.h
===================================================================
--- trunk/drmaa_utils/drmaa_utils/drmaa_base.h	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/drmaa_base.h	(revision 1)
@@ -0,0 +1,76 @@
+/* $Id: drmaa_base.h 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ * FedStage DRMAA utilities library
+ * Copyright (C) 2006-2008  FedStage Systems
+ *
+ * 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/>.
+ */
+
+#ifndef __DRMAA_UTILS__DRMAA_BASE_H
+#define __DRMAA_UTILS__DRMAA_BASE_H
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <drmaa_utils/common.h>
+#include <drmaa_utils/thread.h>
+
+struct fsd_drmaa_singletone_s {
+	/** Global session object */
+	fsd_drmaa_session_t *session;
+	fsd_mutex_t session_mutex;
+
+	fsd_drmaa_session_t *(*new_session)(
+			fsd_drmaa_singletone_t *self,
+			const char *contact
+			);
+
+	fsd_template_t *(*new_job_template)(
+			fsd_drmaa_singletone_t *self
+			);
+
+	const char* (*get_contact)( fsd_drmaa_singletone_t *self );
+	void (*get_version)(
+			fsd_drmaa_singletone_t *self,
+			unsigned *major, unsigned *minor
+			);
+	const char* (*get_DRM_system)( fsd_drmaa_singletone_t *self );
+	const char* (*get_DRMAA_implementation)( fsd_drmaa_singletone_t *self );
+
+	fsd_iter_t * (*
+	get_attribute_names)(
+		fsd_drmaa_singletone_t *self );
+
+	fsd_iter_t * (*
+	get_vector_attribute_names)(
+		fsd_drmaa_singletone_t *self );
+
+	int (*wifexited)( int *exited, int stat,
+		char *error_diagnosis, size_t error_diag_len );
+	int (*wexitstatus)( int *exit_status, int stat,
+		char *error_diagnosis, size_t error_diag_len );
+	int (*wifsignaled)( int *signaled, int stat,
+		char *error_diagnosis, size_t error_diag_len );
+	int (*wtermsig)( char *signal, size_t signal_len, int stat,
+		char *error_diagnosis, size_t error_diag_len );
+	int (*wcoredump)( int *core_dumped, int stat,
+		char *error_diagnosis, size_t error_diag_len );
+	int (*wifaborted)( int *aborted, int stat,
+		char *error_diagnosis, size_t error_diag_len );
+};
+
+extern fsd_drmaa_singletone_t _fsd_drmaa_singletone;
+
+#endif /* __DRMAA_UTILS__DRMAA_BASE_H */
Index: trunk/drmaa_utils/drmaa_utils/environ.h
===================================================================
--- trunk/drmaa_utils/drmaa_utils/environ.h	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/environ.h	(revision 1)
@@ -0,0 +1,81 @@
+/* $Id: environ.h 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ * FedStage DRMAA utilities library
+ * Copyright (C) 2006-2008  FedStage Systems
+ *
+ * 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/>.
+ */
+
+#ifndef __DRMAA_UTILS__ENVIRON_H
+#define __DRMAA_UTILS__ENVIRON_H
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <drmaa_utils/compat.h>
+
+typedef struct fsd_environ_s fsd_environ_t;
+typedef struct fsd_environ_item_s fsd_environ_item_t;
+
+struct fsd_environ_s {
+	void (*
+	destroy)( fsd_environ_t *self );
+
+	const char* (*
+	get)( fsd_environ_t *self, const char *name );
+
+	void (*
+	set)( fsd_environ_t *self, char *name, char *value );
+
+	void (*
+	update)( fsd_environ_t *self, const char *const envp[] );
+
+	char ** (*
+	list)( fsd_environ_t *self );
+
+	/**
+	 * Modifies process's environment overwriting variables
+	 * set in environ object.
+	 * @return  Dictionary of overwritten values.
+	 * @see #restore
+	 */
+	fsd_environ_t * (*
+	apply)( fsd_environ_t *self );
+
+	/**
+	 * Restore process's environment to original state.
+	 * All variables from \a self gets overwritten with values
+	 * from \a saved_state or unset if variable doesn't exist
+	 * in \a saved_state.
+	 * @see #apply
+	 */
+	void (*
+	restore)( fsd_environ_t *self, fsd_environ_t *saved_state );
+
+	fsd_environ_item_t **_table;
+	unsigned _table_size;
+};
+
+fsd_environ_t *
+fsd_environ_new( const char *const envp[] );
+
+struct fsd_environ_item_s {
+	fsd_environ_item_t *next;
+	char *name;
+	char *value;
+};
+
+#endif /* __DRMAA_UTILS__ENVIRON_H */
+
Index: trunk/drmaa_utils/drmaa_utils/drmaa_util.h
===================================================================
--- trunk/drmaa_utils/drmaa_utils/drmaa_util.h	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/drmaa_util.h	(revision 1)
@@ -0,0 +1,91 @@
+/* $Id: drmaa_util.h 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+#ifndef __DRMAA_UTILS__DRMAA_UTIL_H
+#define __DRMAA_UTILS__DRMAA_UTIL_H
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <drmaa_utils/common.h>
+
+enum{
+	FSD_DRMAA_PH_HD    = 1<<0,
+	FSD_DRMAA_PH_WD    = 1<<1,
+	FSD_DRMAA_PH_INCR  = 1<<2
+};
+
+struct fsd_expand_drmaa_ph_s {
+	/**
+	 * Expands placeholders in DRMAA job attribute value.
+	 * @param self   Context.
+	 * @param input  String to transform.  Should be malloc'ed
+	 *   and ownership is passed to callee.
+	 * @param set    Set of placeholders to expand.  Bitwise
+	 *   `or' of any of following bits:
+	 *   - FSD_DRMAA_PH_HD,
+	 *   - FSD_DRMAA_PH_WD,
+	 *   - FSD_DRMAA_PH_INCR
+	 * @return Value with expanded placeholders or \c NULL
+	 *   upon error.  Caller is responsible for free()'ing it.
+	 */
+	char *(*
+	expand)( fsd_expand_drmaa_ph_t *self, char *input, unsigned set );
+
+	void (*
+	set)( fsd_expand_drmaa_ph_t *self, int placeholder, char *value );
+
+	void (*destroy)( fsd_expand_drmaa_ph_t *self );
+
+	char *home_directory;
+	char *working_directory;
+	char *bulk_incr;
+};
+
+fsd_expand_drmaa_ph_t *
+fsd_expand_drmaa_ph_new(
+		char *home_directory,
+		char *working_directory,
+		char *bulk_incr
+		);
+
+int fsd_parse_timedelta( const char *string );
+
+/**
+ * Return textual representation of action
+ * - argument of drmaa_control().
+ */
+const char *drmaa_control_to_str( int action );
+
+/**
+ * Return textual representation of job status
+ * - result of drmaa_job_ps().
+ */
+const char *drmaa_job_ps_to_str( int ps );
+
+int fsd_drmaa_code( int fsd_errno );
+
+int fsd_errno_from_drmaa_code( int drmaa_errno );
+
+const char *
+fsd_drmaa_strerror( int drmaa_errno );
+
+#endif /* __DRMAA_UTILS__DRMAA_UTIL_H */
+
Index: trunk/drmaa_utils/drmaa_utils/compat.h
===================================================================
--- trunk/drmaa_utils/drmaa_utils/compat.h	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/compat.h	(revision 1)
@@ -0,0 +1,77 @@
+/* $Id: compat.h 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+#ifndef __DRMAA_UTILS__COMPAT_H
+#define __DRMAA_UTILS__COMPAT_H
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <sys/types.h>
+
+#include <stddef.h>
+#include <stdarg.h>
+
+#ifdef HAVE_STDINT_H
+#	include <stdint.h>
+#else
+#	ifdef HAVE_INTTYPES_H
+#		include <inttypes.h>
+#	else
+#		warning "no stdint.h nor inttypes.h found"
+#	endif
+#endif /* ! HAVE_STDINT_H */
+
+#ifdef HAVE_STDBOOL_H
+#	include <stdbool.h>
+#else
+#	ifndef bool
+#		define bool int
+#	endif
+#	ifndef true
+#		define true 1
+#	endif
+#	ifndef false
+#		define false 0
+#	endif
+#endif /* ! HAVE_STDBOOL_H */
+
+#ifndef HAVE_STRLCPY
+size_t strlcpy( char *dest, const char *src, size_t size )
+	__attribute__(( weak ));
+#endif
+
+#ifndef HAVE_STRNDUP
+char *strndup( const char *s, size_t n )
+	__attribute__(( weak ));
+#endif
+
+#ifndef HAVE_ASPRINTF
+int asprintf( char **strp, const char *fmt, ... )
+	__attribute__(( weak ));
+#endif
+
+#ifndef HAVE_VASPRINTF
+int vasprintf( char **strp, const char *fmt, va_list ap )
+	__attribute__(( weak ));
+#endif
+
+#endif /* __DRMAA_UTILS__COMPAT_H */
+
Index: trunk/drmaa_utils/drmaa_utils/lookup3.c
===================================================================
--- trunk/drmaa_utils/drmaa_utils/lookup3.c	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/lookup3.c	(revision 1)
@@ -0,0 +1,644 @@
+/*
+-------------------------------------------------------------------------------
+lookup3.c, by Bob Jenkins, May 2006, Public Domain.
+These are functions for producing 32-bit hashes for hash table lookup.
+hashword(), hashlittle(), hashbig(), mix(), and final() are externally
+useful functions.  Routines to test the hash are included if SELF_TEST
+is defined.  You can use this free for any purpose.  It has no warranty.
+
+You probably want to use hashlittle().  hashlittle() and hashbig()
+hash byte arrays.  hashlittle() is is faster than hashbig() on
+little-endian machines.  Intel and AMD are little-endian machines.
+
+If you want to find a hash of, say, exactly 7 integers, do
+  a = i1;  b = i2;  c = i3;
+  mix(a,b,c);
+  a += i4; b += i5; c += i6;
+  mix(a,b,c);
+  a += i7;
+  final(a,b,c);
+then use c as the hash value.  If you have a variable length array of
+4-byte integers to hash, use hashword().  If you have a byte array (like
+a character string), use hashlittle().  If you have several byte arrays, or
+a mix of things, see the comments above hashlittle().
+
+Code changed for ANSI C compilers and autotools by Åukasz CieÅnik.
+-------------------------------------------------------------------------------
+*/
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <drmaa_utils/lookup3.h>
+
+#ifdef SELF_TEST
+#include <stdio.h>
+#include <time.h>
+#include <stdlib.h>
+#endif
+
+#ifndef lint
+static char rcsid[]
+#	ifdef __GNUC__
+		__attribute__ ((unused))
+#	endif
+	= "$Id: lookup3.c 232 2010-05-30 17:03:23Z mamonski $";
+#endif
+
+typedef uint32_t uint32;   /* unsigned 4-byte quantities */
+typedef uint16_t uint16;   /* unsigned 2-byte quantities */
+typedef uint8_t  uint8;    /* unsigned 1-byte quantities */
+
+/* do not make any assumptions about the endianess - safer and prevents from reading not initialized memory */
+#	define HASH_LITTLE_ENDIAN 0
+#	define HASH_BIG_ENDIAN    0
+
+#define hashsize(n) ((uint32)1<<(n))
+#define hashmask(n) (hashsize(n)-1)
+#define rot(x,k) (((x)<<(k)) ^ ((x)>>(32-(k))))
+
+/*
+-------------------------------------------------------------------------------
+mix -- mix 3 32-bit values reversibly.
+
+This is reversible, so any information in (a,b,c) before mix() is
+still in (a,b,c) after mix().
+
+If four pairs of (a,b,c) inputs are run through mix(), or through
+mix() in reverse, there are at least 32 bits of the output that
+are sometimes the same for one pair and different for another pair.
+This was tested for:
+* pairs that differed by one bit, by two bits, in any combination
+  of top bits of (a,b,c), or in any combination of bottom bits of
+  (a,b,c).
+* "differ" is defined as +, -, ^, or ~^.  For + and -, I transformed
+  the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
+  is commonly produced by subtraction) look like a single 1-bit
+  difference.
+* the base values were pseudorandom, all zero but one bit set, or
+  all zero plus a counter that starts at zero.
+
+Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that
+satisfy this are
+    4  6  8 16 19  4
+    9 15  3 18 27 15
+   14  9  3  7 17  3
+Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing
+for "differ" defined as + with a one-bit base and a two-bit delta.  I
+used http://burtleburtle.net/bob/hash/avalanche.html to choose
+the operations, constants, and arrangements of the variables.
+
+This does not achieve avalanche.  There are input bits of (a,b,c)
+that fail to affect some output bits of (a,b,c), especially of a.  The
+most thoroughly mixed value is c, but it doesn't really even achieve
+avalanche in c.
+
+This allows some parallelism.  Read-after-writes are good at doubling
+the number of bits affected, so the goal of mixing pulls in the opposite
+direction as the goal of parallelism.  I did what I could.  Rotates
+seem to cost as much as shifts on every machine I could lay my hands
+on, and rotates are much kinder to the top and bottom bits, so I used
+rotates.
+-------------------------------------------------------------------------------
+*/
+#define mix(a,b,c) \
+{ \
+  a -= c;  a ^= rot(c, 4);  c += b; \
+  b -= a;  b ^= rot(a, 6);  a += c; \
+  c -= b;  c ^= rot(b, 8);  b += a; \
+  a -= c;  a ^= rot(c,16);  c += b; \
+  b -= a;  b ^= rot(a,19);  a += c; \
+  c -= b;  c ^= rot(b, 4);  b += a; \
+}
+
+/*
+-------------------------------------------------------------------------------
+final -- final mixing of 3 32-bit values (a,b,c) into c
+
+Pairs of (a,b,c) values differing in only a few bits will usually
+produce values of c that look totally different.  This was tested for
+* pairs that differed by one bit, by two bits, in any combination
+  of top bits of (a,b,c), or in any combination of bottom bits of
+  (a,b,c).
+* "differ" is defined as +, -, ^, or ~^.  For + and -, I transformed
+  the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
+  is commonly produced by subtraction) look like a single 1-bit
+  difference.
+* the base values were pseudorandom, all zero but one bit set, or
+  all zero plus a counter that starts at zero.
+
+These constants passed:
+ 14 11 25 16 4 14 24
+ 12 14 25 16 4 14 24
+and these came close:
+  4  8 15 26 3 22 24
+ 10  8 15 26 3 22 24
+ 11  8 15 26 3 22 24
+-------------------------------------------------------------------------------
+*/
+#define final(a,b,c) \
+{ \
+  c ^= b; c -= rot(b,14); \
+  a ^= c; a -= rot(c,11); \
+  b ^= a; b -= rot(a,25); \
+  c ^= b; c -= rot(b,16); \
+  a ^= c; a -= rot(c,4);  \
+  b ^= a; b -= rot(a,14); \
+  c ^= b; c -= rot(b,24); \
+}
+
+/**
+ * This works on all machines.  To be useful, it requires
+ * -- that the key be an array of uint32's, and
+ * -- that all your machines have the same endianness, and
+ * -- that the length be the number of uint32's in the key
+
+ * The function hashword() is identical to hashlittle() on little-endian
+ * machines, and identical to hashbig() on big-endian machines,
+ * except that the length has to be measured in uint32s rather than in
+ * bytes.  hashlittle() is more complicated than hashword() only because
+ * hashlittle() has to dance around fitting the key bytes into registers.
+ *
+ * @param k          the key, an array of uint32 values
+ * @param length     the length of the key, in uint32s
+ * @param initval    the previous hash, or an arbitrary value
+ */
+uint32 hashword( const uint32 *k, size_t length, uint32 initval )
+{
+  uint32 a,b,c;
+
+  /* Set up the internal state */
+  a = b = c = 0xdeadbeef + (((uint32)length)<<2) + initval;
+
+  /*------------------------------------------------- handle most of the key */
+  while (length > 3)
+  {
+    a += k[0];
+    b += k[1];
+    c += k[2];
+    mix(a,b,c);
+    length -= 3;
+    k += 3;
+  }
+
+  /*--------------------------------------------- handle the last 3 uint32's */
+  switch(length)                     /* all the case statements fall through */
+  {
+  case 3 : c+=k[2];
+  case 2 : b+=k[1];
+  case 1 : a+=k[0];
+    final(a,b,c);
+  case 0:     /* case 0: nothing left to add */
+    break;
+  }
+  /*------------------------------------------------------ report the result */
+  return c;
+}
+
+
+/**
+ * hashlittle() -- hash a variable-length key into a 32-bit value
+ *  @param k         the key (the unaligned variable-length array of bytes)
+ *  @param length    the length of the key, counting by bytes
+ *  @param initval   can be any 4-byte value
+ *
+ * Returns a 32-bit value.  Every bit of the key affects every bit of
+ * the return value.  Two keys differing by one or two bits will have
+ * totally different hash values.
+ *
+ * The best hash table sizes are powers of 2.  There is no need to do
+ * mod a prime (mod is sooo slow!).  If you need less than 32 bits,
+ * use a bitmask.  For example, if you need only 10 bits, do
+ *   h = (h & hashmask(10));
+ * In which case, the hash table should have hashsize(10) elements.
+ *
+ * If you are hashing n strings (uint8 **)k, do it like this:
+ *   for (i=0, h=0; i<n; ++i) h = hashlittle( k[i], len[i], h);
+ *
+ * By Bob Jenkins, 2006.  bob_jenkins@burtleburtle.net.  You may use this
+ * code any way you wish, private, educational, or commercial.  It's free.
+ *
+ * Use for hash table lookup, or anything where one collision in 2^^32 is
+ * acceptable.  Do NOT use for cryptographic purposes.
+ */
+uint32 hashlittle( const void *key, size_t length, uint32 initval )
+{
+  uint32 a,b,c;
+
+  /* Set up the internal state */
+  a = b = c = 0xdeadbeef + ((uint32)length) + initval;
+
+  if (HASH_LITTLE_ENDIAN && !((((uint8 *)key)-(uint8 *)0) & 0x3)) {
+    const uint32 *k = key;                                 /* read 32-bit chunks */
+
+    /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
+    while (length > 12)
+    {
+      a += k[0];
+      b += k[1];
+      c += k[2];
+      mix(a,b,c);
+      length -= 12;
+      k += 3;
+    }
+
+    /*----------------------------- handle the last (probably partial) block */
+    switch(length)
+    {
+    case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
+    case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
+    case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
+    case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
+    case 8 : b+=k[1]; a+=k[0]; break;
+    case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
+    case 6 : b+=k[1]&0xffff; a+=k[0]; break;
+    case 5 : b+=k[1]&0xff; a+=k[0]; break;
+    case 4 : a+=k[0]; break;
+    case 3 : a+=k[0]&0xffffff; break;
+    case 2 : a+=k[0]&0xffff; break;
+    case 1 : a+=k[0]&0xff; break;
+    case 0 : return c;              /* zero length strings require no mixing */
+    }
+
+  } else if (HASH_LITTLE_ENDIAN && !((((uint8 *)key)-(uint8 *)0) & 0x1)) {
+    const uint16 *k = key;                                   /* read 16-bit chunks */
+
+    /*--------------- all but last block: aligned reads and different mixing */
+    while (length > 12)
+    {
+      a += k[0] + (((uint32)k[1])<<16);
+      b += k[2] + (((uint32)k[3])<<16);
+      c += k[4] + (((uint32)k[5])<<16);
+      mix(a,b,c);
+      length -= 12;
+      k += 6;
+    }
+
+    /*----------------------------- handle the last (probably partial) block */
+    switch(length)
+    {
+    case 12: c+=k[4]+(((uint32)k[5])<<16);
+             b+=k[2]+(((uint32)k[3])<<16);
+             a+=k[0]+(((uint32)k[1])<<16);
+             break;
+    case 11: c+=((uint32)(k[5]&0xff))<<16;/* fall through */
+    case 10: c+=k[4];
+             b+=k[2]+(((uint32)k[3])<<16);
+             a+=k[0]+(((uint32)k[1])<<16);
+             break;
+    case 9 : c+=k[4]&0xff;                /* fall through */
+    case 8 : b+=k[2]+(((uint32)k[3])<<16);
+             a+=k[0]+(((uint32)k[1])<<16);
+             break;
+    case 7 : b+=((uint32)(k[3]&0xff))<<16;/* fall through */
+    case 6 : b+=k[2];
+             a+=k[0]+(((uint32)k[1])<<16);
+             break;
+    case 5 : b+=k[2]&0xff;                /* fall through */
+    case 4 : a+=k[0]+(((uint32)k[1])<<16);
+             break;
+    case 3 : a+=((uint32)(k[1]&0xff))<<16;/* fall through */
+    case 2 : a+=k[0];
+             break;
+    case 1 : a+=k[0]&0xff;
+             break;
+    case 0 : return c;                     /* zero length requires no mixing */
+    }
+
+  } else {                        /* need to read the key one byte at a time */
+    const uint8 *k = key;
+
+    /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
+    while (length > 12)
+    {
+      a += k[0];
+      a += ((uint32)k[1])<<8;
+      a += ((uint32)k[2])<<16;
+      a += ((uint32)k[3])<<24;
+      b += k[4];
+      b += ((uint32)k[5])<<8;
+      b += ((uint32)k[6])<<16;
+      b += ((uint32)k[7])<<24;
+      c += k[8];
+      c += ((uint32)k[9])<<8;
+      c += ((uint32)k[10])<<16;
+      c += ((uint32)k[11])<<24;
+      mix(a,b,c);
+      length -= 12;
+      k += 12;
+    }
+
+    /*-------------------------------- last block: affect all 32 bits of (c) */
+    switch(length)                   /* all the case statements fall through */
+    {
+    case 12: c+=((uint32)k[11])<<24;
+    case 11: c+=((uint32)k[10])<<16;
+    case 10: c+=((uint32)k[9])<<8;
+    case 9 : c+=k[8];
+    case 8 : b+=((uint32)k[7])<<24;
+    case 7 : b+=((uint32)k[6])<<16;
+    case 6 : b+=((uint32)k[5])<<8;
+    case 5 : b+=k[4];
+    case 4 : a+=((uint32)k[3])<<24;
+    case 3 : a+=((uint32)k[2])<<16;
+    case 2 : a+=((uint32)k[1])<<8;
+    case 1 : a+=k[0];
+             break;
+    case 0 : return c;
+    }
+  }
+
+  final(a,b,c);
+  return c;
+}
+
+
+
+/**
+ * hashbig():
+ * This is the same as hashword() on big-endian machines.  It is different
+ * from hashlittle() on all machines.  hashbig() takes advantage of
+ * big-endian byte ordering.
+ */
+uint32 hashbig( const void *key, size_t length, uint32 initval )
+{
+  uint32 a,b,c;
+
+  /* Set up the internal state */
+  a = b = c = 0xdeadbeef + ((uint32)length) + initval;
+
+  if (HASH_BIG_ENDIAN && !((((uint8 *)key)-(uint8 *)0) & 0x3)) {
+    const uint32 *k = key;                                 /* read 32-bit chunks */
+
+    /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
+    while (length > 12)
+    {
+      a += k[0];
+      b += k[1];
+      c += k[2];
+      mix(a,b,c);
+      length -= 12;
+      k += 3;
+    }
+
+    /*----------------------------- handle the last (probably partial) block */
+    switch(length)
+    {
+    case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
+    case 11: c+=k[2]<<8; b+=k[1]; a+=k[0]; break;
+    case 10: c+=k[2]<<16; b+=k[1]; a+=k[0]; break;
+    case 9 : c+=k[2]<<24; b+=k[1]; a+=k[0]; break;
+    case 8 : b+=k[1]; a+=k[0]; break;
+    case 7 : b+=k[1]<<8; a+=k[0]; break;
+    case 6 : b+=k[1]<<16; a+=k[0]; break;
+    case 5 : b+=k[1]<<24; a+=k[0]; break;
+    case 4 : a+=k[0]; break;
+    case 3 : a+=k[0]<<8; break;
+    case 2 : a+=k[0]<<16; break;
+    case 1 : a+=k[0]<<24; break;
+    case 0 : return c;              /* zero length strings require no mixing */
+    }
+
+  } else {                        /* need to read the key one byte at a time */
+    const uint8 *k = key;
+
+    /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
+    while (length > 12)
+    {
+      a += ((uint32)k[0])<<24;
+      a += ((uint32)k[1])<<16;
+      a += ((uint32)k[2])<<8;
+      a += ((uint32)k[3]);
+      b += ((uint32)k[4])<<24;
+      b += ((uint32)k[5])<<16;
+      b += ((uint32)k[6])<<8;
+      b += ((uint32)k[7]);
+      c += ((uint32)k[8])<<24;
+      c += ((uint32)k[9])<<16;
+      c += ((uint32)k[10])<<8;
+      c += ((uint32)k[11]);
+      mix(a,b,c);
+      length -= 12;
+      k += 12;
+    }
+
+    /*-------------------------------- last block: affect all 32 bits of (c) */
+    switch(length)                   /* all the case statements fall through */
+    {
+    case 12: c+=((uint32)k[11])<<24;
+    case 11: c+=((uint32)k[10])<<16;
+    case 10: c+=((uint32)k[9])<<8;
+    case 9 : c+=k[8];
+    case 8 : b+=((uint32)k[7])<<24;
+    case 7 : b+=((uint32)k[6])<<16;
+    case 6 : b+=((uint32)k[5])<<8;
+    case 5 : b+=k[4];
+    case 4 : a+=((uint32)k[3])<<24;
+    case 3 : a+=((uint32)k[2])<<16;
+    case 2 : a+=((uint32)k[1])<<8;
+    case 1 : a+=k[0];
+             break;
+    case 0 : return c;
+    }
+  }
+
+  final(a,b,c);
+  return c;
+}
+
+
+#ifdef SELF_TEST
+
+/* used for timings */
+void driver1(void)
+{
+  uint8 buf[256];
+  uint32 i;
+  uint32 h=0;
+  time_t a,z;
+
+  time(&a);
+  for (i=0; i<256; ++i) buf[i] = 'x';
+  for (i=0; i<1; ++i)
+  {
+    h = hashlittle(&buf[0],1,h);
+  }
+  time(&z);
+  if (z-a > 0) printf("time %ld %.8lx\n", z-a, h);
+}
+
+/* check that every input bit changes every output bit half the time */
+#define HASHSTATE 1
+#define HASHLEN   1
+#define MAXPAIR 60
+#define MAXLEN  70
+void driver2(void)
+{
+  uint8 qa[MAXLEN+1], qb[MAXLEN+2], *a = &qa[0], *b = &qb[1];
+  uint32 c[HASHSTATE], d[HASHSTATE], i, j=0, k, l, m, z;
+  uint32 e[HASHSTATE],f[HASHSTATE],g[HASHSTATE],h[HASHSTATE];
+  uint32 x[HASHSTATE],y[HASHSTATE];
+  uint32 hlen;
+
+  printf("No more than %d trials should ever be needed \n",MAXPAIR/2);
+  for (hlen=0; hlen < MAXLEN; ++hlen)
+  {
+    z=0;
+    for (i=0; i<hlen; ++i)  /*----------------------- for each input byte, */
+    {
+      for (j=0; j<8; ++j)   /*------------------------ for each input bit, */
+      {
+	for (m=1; m<8; ++m) /*------------ for serveral possible initvals, */
+	{
+	  for (l=0; l<HASHSTATE; ++l) e[l]=f[l]=g[l]=h[l]=x[l]=y[l]=~((uint32)0);
+
+		/*---- check that every output bit is affected by that input bit */
+	  for (k=0; k<MAXPAIR; k+=2)
+	  {
+	    uint32 finished=1;
+	    /* keys have one bit different */
+	    for (l=0; l<hlen+1; ++l) {a[l] = b[l] = (uint8)0;}
+	    /* have a and b be two keys differing in only one bit */
+	    a[i] ^= (k<<j);
+	    a[i] ^= (k>>(8-j));
+	     c[0] = hashlittle(a, hlen, m);
+	    b[i] ^= ((k+1)<<j);
+	    b[i] ^= ((k+1)>>(8-j));
+	     d[0] = hashlittle(b, hlen, m);
+	    /* check every bit is 1, 0, set, and not set at least once */
+	    for (l=0; l<HASHSTATE; ++l)
+	    {
+	      e[l] &= (c[l]^d[l]);
+	      f[l] &= ~(c[l]^d[l]);
+	      g[l] &= c[l];
+	      h[l] &= ~c[l];
+	      x[l] &= d[l];
+	      y[l] &= ~d[l];
+	      if (e[l]|f[l]|g[l]|h[l]|x[l]|y[l]) finished=0;
+	    }
+	    if (finished) break;
+	  }
+	  if (k>z) z=k;
+	  if (k==MAXPAIR) 
+	  {
+	     printf("Some bit didn't change: ");
+	     printf("%.8lx %.8lx %.8lx %.8lx %.8lx %.8lx  ",
+	            e[0],f[0],g[0],h[0],x[0],y[0]);
+	     printf("i %ld j %ld m %ld len %ld\n",i,j,m,hlen);
+	  }
+	  if (z==MAXPAIR) goto done;
+	}
+      }
+    }
+   done:
+    if (z < MAXPAIR)
+    {
+      printf("Mix success  %2ld bytes  %2ld initvals  ",i,m);
+      printf("required  %ld  trials\n",z/2);
+    }
+  }
+  printf("\n");
+}
+
+/* Check for reading beyond the end of the buffer and alignment problems */
+void driver3(void)
+{
+  uint8 buf[MAXLEN+20], *b;
+  uint32 len;
+  uint8 q[] = "This is the time for all good men to come to the aid of their country...";
+  uint32 dummy1;
+  uint8 qq[] = "xThis is the time for all good men to come to the aid of their country...";
+  uint32 dummy2;
+  uint8 qqq[] = "xxThis is the time for all good men to come to the aid of their country...";
+  uint32 dummy3;
+  uint8 qqqq[] = "xxxThis is the time for all good men to come to the aid of their country...";
+  uint32 h,i,j,ref,x,y;
+  uint8 *p;
+
+  printf("Endianness.  These lines should all be the same (for values filled in):\n");
+  printf("%.8lx                            %.8lx                            %.8lx\n",
+         hashword((uint32 *)q, (sizeof(q)-1)/4, 13),
+         hashword((uint32 *)q, (sizeof(q)-5)/4, 13),
+         hashword((uint32 *)q, (sizeof(q)-9)/4, 13));
+  p = q;
+  printf("%.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx\n",
+         hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
+         hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
+         hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
+         hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
+         hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
+         hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
+  p = &qq[1];
+  printf("%.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx\n",
+         hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
+         hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
+         hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
+         hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
+         hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
+         hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
+  p = &qqq[2];
+  printf("%.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx\n",
+         hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
+         hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
+         hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
+         hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
+         hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
+         hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
+  p = &qqqq[3];
+  printf("%.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx %.8lx\n",
+         hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
+         hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
+         hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
+         hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
+         hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
+         hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
+  printf("\n");
+  for (h=0, b=buf+1; h<8; ++h, ++b)
+  {
+    for (i=0; i<MAXLEN; ++i)
+    {
+      len = i;
+      for (j=0; j<i; ++j) *(b+j)=0;
+
+      /* these should all be equal */
+      ref = hashlittle(b, len, (uint32)1);
+      *(b+i)=(uint8)~0;
+      *(b-1)=(uint8)~0;
+      x = hashlittle(b, len, (uint32)1);
+      y = hashlittle(b, len, (uint32)1);
+      if ((ref != x) || (ref != y)) 
+      {
+	printf("alignment error: %.8lx %.8lx %.8lx %ld %ld\n",ref,x,y,h,i);
+      }
+    }
+  }
+}
+
+/* check for problems with nulls */
+ void driver4(void)
+{
+  uint8 buf[1];
+  uint32 h,i,state[HASHSTATE];
+
+
+  buf[0] = ~0;
+  for (i=0; i<HASHSTATE; ++i) state[i] = 1;
+  printf("These should all be different\n");
+  for (i=0, h=0; i<8; ++i)
+  {
+    h = hashlittle(buf, (uint32)0, h);
+    printf("%2ld  0-byte strings, hash is  %.8lx\n", i, h);
+  }
+}
+
+
+int main()
+{
+  driver1();   /* test that the key is hashed: used for timings */
+  driver2();   /* test that whole key is hashed thoroughly */
+  driver3();   /* test that nothing but the key is hashed */
+  driver4();   /* test hashing multiple buffers (all buffers are null) */
+  return 1;
+}
+
+#endif  /* SELF_TEST */
Index: trunk/drmaa_utils/drmaa_utils/datetime.c
===================================================================
--- trunk/drmaa_utils/drmaa_utils/datetime.c	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/datetime.c	(revision 1)
@@ -0,0 +1,361 @@
+/* $Id: datetime.c 132 2010-04-28 14:34:34Z mamonski $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+/**
+ * @file datetime.c
+ * DRMAA date/time parser.
+ */
+
+#include <ctype.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include <drmaa_utils/compat.h>
+#include <drmaa_utils/datetime_impl.h>
+#include <drmaa_utils/datetime_tab.h>
+#include <drmaa_utils/logging.h>
+
+
+void
+fsd_datetime_dump( const fsd_datetime_t *dt, char *s, size_t len )
+{
+	char mask[] = "YMDhmsZ";
+	char sign = '+';
+	long tz_delta = dt->tz_delta;
+	unsigned d_hour, d_min, d_sec;
+	unsigned m;
+	if( tz_delta < 0 )
+	 {
+		tz_delta = -tz_delta;
+		sign = '-';
+	 }
+	d_sec = tz_delta%60;  tz_delta/=60;
+	d_min = tz_delta%60;  tz_delta/=60;
+	d_hour = tz_delta;
+	for( m=0;  m<7;  m++ )
+	 {
+		if( !(dt->mask & (1<<m)) )
+			mask[m]='-';
+	 }
+	snprintf( s, len, "%04d-%02d-%02d %02d:%02d:%02d %c%02d:%02d:%02d [%s]",
+			dt->year, dt->month, dt->day,
+			dt->hour, dt->minute, dt->second,
+			sign, d_hour, d_min, d_sec,
+			mask
+			);
+}
+
+
+long
+fsd_timezone( time_t t )
+{
+	struct tm utc_tm;
+	struct tm local_tm;
+	int d;
+	long result;
+
+	gmtime_r( &t, &utc_tm );
+	localtime_r( &t, &local_tm );
+	if( local_tm.tm_year != utc_tm.tm_year )
+		d = local_tm.tm_year - utc_tm.tm_year;
+	else if( local_tm.tm_mon != utc_tm.tm_mon )
+		d = local_tm.tm_mon - utc_tm.tm_mon;
+	else if( local_tm.tm_mday != utc_tm.tm_mday )
+		d = local_tm.tm_mday - utc_tm.tm_mday;
+	else
+		d = 0;
+	result =
+		( (local_tm.tm_hour-utc_tm.tm_hour)*60
+		+ local_tm.tm_min-utc_tm.tm_min )*60
+		+ local_tm.tm_sec-utc_tm.tm_sec;
+	if( d > 0 )
+		result += 24*3600;
+	else if( d < 0 )
+		result -= 24*3600;
+	return result;
+}
+
+
+void
+fsd_datetime_fill( fsd_datetime_t *dt, time_t filler )
+{
+	unsigned unfilled = ~dt->mask;
+	struct tm t;
+
+#ifdef DEBUGGING
+	char dbg[256];
+	fsd_datetime_dump( dt, dbg, sizeof(dbg) );
+	fsd_log_enter(( "(dt={%s}, filler=%u)",
+				dbg, (unsigned)filler ));
+#endif
+
+#ifdef HAVE_STRUCT_TM_GMTOFF
+	/*
+	 * glibc have tm_gmtoff field in tm struct
+	 * which is number of second east from UTC
+	 */
+	if( unfilled & FSD_DT_TZ_DELTA )
+	 {
+		localtime_r( &filler, &t );
+		dt->tz_delta = t.tm_gmtoff;
+	 }
+	else
+	 {
+		filler += dt->tz_delta;
+		gmtime_r( &filler, &t );
+	 }
+#else /* ! __GNUC__ */
+	if( unfilled & FSD_DT_TZ_DELTA )
+		dt->tz_delta = fsd_timezone( filler );
+	filler += dt->tz_delta;
+	gmtime_r( &filler, &t );
+#endif
+
+	if( unfilled & FSD_DT_YEAR )
+		dt->year = t.tm_year + 1900;
+	else if( dt->year < 100 )
+		dt->year += 100 * ( (t.tm_year+1900)/100 );
+	if( unfilled & FSD_DT_MONTH )
+		dt->month = t.tm_mon + 1;
+	if( unfilled & FSD_DT_DAY )
+		dt->day = t.tm_mday;
+	if( unfilled & FSD_DT_HOUR )
+		dt->hour = t.tm_hour;
+	if( unfilled & FSD_DT_MINUTE )
+		dt->minute = t.tm_min;
+	if( unfilled & FSD_DT_SECOND )
+		dt->second = 0;
+
+	dt->mask |= FSD_DT_ALL;
+
+#ifdef DEBUGGING
+	fsd_datetime_dump( dt, dbg, sizeof(dbg) );
+	fsd_log_return(( ": dt={%s}", dbg ));
+#endif
+}
+
+
+time_t
+fsd_datetime_mktime( const fsd_datetime_t *dt )
+{
+	const unsigned month_days[12]
+		= { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
+	unsigned long year, month;
+	unsigned long years, days;
+	time_t result;
+#ifdef DEBUGGING
+	char dbg[ 128 ];
+	fsd_datetime_dump( dt, dbg, sizeof(dbg) );
+	fsd_log_enter(( "(dt={%s})", dbg ));
+#endif
+	year = dt->year;
+	month = dt->month;
+	while( month < 1 )
+	 { year--;  month += 12; }
+	while( month > 12 )
+	 { year++;  month -= 12; }
+	years = year - 1970;
+	days = 365*years + (years+1)/4;
+	days += month_days[ month-1 ];
+	if( month > 2  &&  (year&3) == 0 )
+		days ++;
+	days += dt->day - 1;
+	result = ( ( days*24 + dt->hour )*60 + dt->minute )*60
+		+ dt->second - dt->tz_delta;
+#ifdef DEBUGGING
+	 {
+		struct tm utc_tm;
+		gmtime_r( &result, &utc_tm );
+		fsd_log_trace(( "years=%ld, days=%ld", years, days ));
+		fsd_log_return(( " =%ld (%04d-%02d-%02d %02d:%02d:%02d+00:00)",
+					result,
+					1900+utc_tm.tm_year, 1+utc_tm.tm_mon, utc_tm.tm_mday,
+					utc_tm.tm_hour, utc_tm.tm_min, utc_tm.tm_sec
+					));
+	 }
+#endif
+	return result;
+}
+
+
+time_t
+fsd_datetime_after( fsd_datetime_t *dt, time_t t )
+{
+	char dbg[256];
+	unsigned unfilled = ~dt->mask;
+	time_t result;
+
+	fsd_datetime_fill( dt, t );
+	fsd_datetime_dump( dt, dbg, sizeof(dbg) );
+	fsd_log_debug(( "filled: %s", dbg ));
+	result = fsd_datetime_mktime( dt );
+
+	if( result < t )
+	 {
+		if( unfilled & FSD_DT_DAY )
+		 {
+			while( result < t )
+			 {
+				fsd_log_debug(( "next day" ));
+				result += 24*3600;
+			 }
+		 }
+		else if( unfilled & FSD_DT_MONTH )
+		 {
+			while( result < t )
+			 {
+				fsd_log_debug(( "next month" ));
+				dt->month++;
+				result = fsd_datetime_mktime( dt );
+			 }
+		 }
+		else if( unfilled & FSD_DT_YEAR )
+		 {
+			while( result < t )
+			 {
+				fsd_log_debug(( "next year" ));
+				dt->year++;
+				result = fsd_datetime_mktime( dt );
+			 }
+		 }
+		else /* FIXME: error message */
+			fsd_exc_raise_fmt( FSD_ERRNO_INVALID_VALUE,
+					"'%s' is in the past", dbg );
+	 }
+
+	return result;
+}
+
+
+time_t
+fsd_datetime_parse( const char *string )
+{
+#ifdef DEBUGGING
+	char dbg[256];
+#endif
+	fsd_dt_parser_t *volatile parser = NULL;
+	fsd_dt_lexer_t *volatile lexer = NULL;
+	int parse_err = 0;
+	fsd_datetime_t dt;
+	time_t result;
+
+	fsd_log_enter(( "(%s)", string ));
+	TRY
+	 {
+		fsd_malloc( parser, fsd_dt_parser_t );
+		fsd_malloc( lexer, fsd_dt_lexer_t );
+
+		parser->lexer = lexer;
+		parser->n_errors = 0;
+		lexer->parser = parser;
+		lexer->begin = lexer->p = (unsigned char*)string;
+		lexer->end = (unsigned char*)( string + strlen(string) );
+		parse_err = fsd_dt_parse( parser, lexer );
+		if( parse_err || parser->n_errors )
+			fsd_exc_raise_fmt(
+					FSD_ERRNO_INVALID_VALUE_FORMAT,
+					"invalid date/time format: %s", string
+					);
+
+		dt = parser->result;
+#ifdef DEBUGGING
+		fsd_datetime_dump( &dt, dbg, sizeof(dbg) );
+		fsd_log_debug(( "parsed: %s", dbg ));
+#endif
+		result = fsd_datetime_after( &dt, time(NULL) );
+	 }
+	FINALLY
+	 {
+		fsd_free( parser );
+		fsd_free( lexer );
+	 }
+	END_TRY
+
+	fsd_log_return(( "(%s) =%u", string, (unsigned)result ));
+	return result;
+}
+
+
+void
+fsd_dt_error(
+		fsd_dt_parser_t *parser,
+		fsd_dt_lexer_t *lexer __attribute__((unused)),
+		const char *fmt, ... )
+{
+	va_list args;
+	char *msg = NULL;
+	parser->n_errors ++;
+	va_start( args, fmt );
+	vasprintf( &msg, fmt, args );
+	va_end( args );
+	fsd_log_error(( "fsd_dt_error: %s", msg ));
+	free( msg );
+}
+
+
+
+int
+fsd_dt_lex( YYSTYPE *lvalp, fsd_dt_lexer_t *lex )
+{
+	const unsigned char *end = lex->end;
+	/* int sign = +1; */
+	while( isspace(*lex->p)  &&  lex->p != end )
+		lex->p++;
+	if( lex->p == end )
+		return -1;
+	switch( *lex->p )
+	 {
+		case '/':  case ':':
+		case '+':  case '-':
+		case 'T':  case 'Z':
+			return * lex->p++;
+#if 0
+		case '-':
+			sign = -1;
+		case '+': /* fall through */
+			if( ++(lex->p) == end )
+			 {
+				fsd_dt_error( lex->parser, lex, "unexpected EOT" );
+				return -1;
+			 }
+		default: /* fall through */
+#endif
+		default:
+		 {
+			int num = 0;
+			if( ! ('0' <= *lex->p  &&  *lex->p <= '9') )
+			 {
+				fsd_dt_error( lex->parser, lex, "invalid char '%c'", *(lex->p)++ );
+				return LEXER_ERROR;
+			 }
+			while( lex->p != end  &&  '0' <= *lex->p  &&  *lex->p <= '9' )
+			 {
+				num *= 10;
+				num += *(lex->p)++ - '0';
+			 }
+			lvalp->integer = num;
+			return NUM;
+		 }
+	 }
+}
+
+
Index: trunk/drmaa_utils/drmaa_utils/common.h
===================================================================
--- trunk/drmaa_utils/drmaa_utils/common.h	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/common.h	(revision 1)
@@ -0,0 +1,53 @@
+/* $Id: common.h 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+#ifndef __DRMAA_UTILS__COMMON_H
+#define __DRMAA_UTILS__COMMON_H
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <drmaa_utils/compat.h>
+#include <drmaa_utils/exception.h>
+#include <drmaa_utils/logging.h>
+#include <drmaa_utils/xmalloc.h>
+
+#define FSD_SAFE_STR(str) ( str != NULL ? str : "(null)" )
+
+/* configuration */
+typedef struct fsd_conf_option_s  fsd_conf_option_t;
+typedef struct fsd_conf_dict_s    fsd_conf_dict_t;
+
+/* iterator */
+typedef struct fsd_iter_s fsd_iter_t;
+
+/* template type */
+typedef struct fsd_attribute_s  fsd_attribute_t;
+typedef struct fsd_template_s   fsd_template_t;
+
+/* DRMAA structures */
+typedef struct fsd_drmaa_singletone_s  fsd_drmaa_singletone_t;
+typedef struct fsd_drmaa_session_s     fsd_drmaa_session_t;
+typedef struct fsd_job_set_s           fsd_job_set_t;
+typedef struct fsd_job_s               fsd_job_t;
+typedef struct fsd_expand_drmaa_ph_s   fsd_expand_drmaa_ph_t;
+
+#endif /* __DRMAA_UTILS__COMMON_H */
+
Index: trunk/drmaa_utils/drmaa_utils/exception.c
===================================================================
--- trunk/drmaa_utils/drmaa_utils/exception.c	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/exception.c	(revision 1)
@@ -0,0 +1,610 @@
+/* $Id: exception.c 321 2010-09-21 16:06:45Z mmatloka $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <errno.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include <pthread.h>
+
+#include <drmaa_utils/common.h>
+#include <drmaa_utils/exception.h>
+
+
+#ifndef lint
+static char rcsid[]
+#	ifdef __GNUC__
+		__attribute__ ((unused))
+#	endif
+	= "$Id: exception.c 321 2010-09-21 16:06:45Z mmatloka $";
+#endif
+
+
+int fsd_exc_code( const fsd_exc_t *self );
+const char *fsd_exc_message( const fsd_exc_t *self );
+void fsd_exc_destroy( fsd_exc_t *self );
+
+#define EXC_INITIALIZER( code, message ) \
+ { \
+	fsd_exc_code, fsd_exc_message, fsd_exc_destroy, \
+	code, message, false, false \
+ }
+
+static const fsd_exc_t no_memory_exception \
+	= EXC_INITIALIZER( FSD_ERRNO_NO_MEMORY, "Not enough memory." );
+
+
+/**
+ * Thread specific stack of restore points
+ * @see fsd_exc_try_block_t
+ */
+typedef struct fsd_exc_stack_s {
+	fsd_exc_try_block_t **restore_points;
+	int n_restore_points;
+} fsd_exc_stack_t;
+
+
+static pthread_key_t fsd_exc_stack;
+static pthread_once_t fsd_exc_init_once = PTHREAD_ONCE_INIT;
+
+
+static void
+fsd_exc_stack_destroy( fsd_exc_stack_t *stack );
+
+
+void
+fsd_exc_init(void)
+{
+	int rc;
+	fsd_log_enter((""));
+	rc = pthread_key_create(
+			&fsd_exc_stack,
+			(void (*)(void*))fsd_exc_stack_destroy
+			);
+	if( rc )
+	 {
+		char errbuf[256] = "InternalError";
+		(void)strerror_r(errno, errbuf, 256);
+		fsd_log_fatal(( "pthread_key_create: %s",errbuf ));
+		abort();
+	 }
+	fsd_log_return((""));
+}
+
+
+fsd_exc_stack_t *
+fsd_exc_get_stack( bool create )
+{
+	fsd_exc_stack_t *stack = NULL;
+	int rc;
+
+	rc = pthread_once( &fsd_exc_init_once, fsd_exc_init );
+	if( rc )
+	 {
+		char errbuf[256] = "InternalError";
+		(void)strerror_r(errno, errbuf, 256);
+		fsd_log_fatal(( "pthread_once: %s",errbuf));
+		abort();
+	 }
+	stack = (fsd_exc_stack_t*)pthread_getspecific( fsd_exc_stack );
+	if( stack == NULL  &&  create )
+	 {
+		rc = fsd_malloc_noraise( stack, fsd_exc_stack_t );
+		if( rc )  return NULL;
+		stack->restore_points = NULL;
+		stack->n_restore_points = 0;
+		rc = pthread_setspecific( fsd_exc_stack, stack );
+		if( rc  &&  errno != ENOMEM )
+		 {
+			char errbuf[256] = "InternalError";
+			(void)strerror_r(errno, errbuf, 256);
+			fsd_log_fatal(( "pthread_setspecific: %s",errbuf ));
+			abort();
+		 }
+		else if( rc )
+		 {
+			fsd_exc_stack_destroy( stack );
+		 }
+	 }
+	else
+		fsd_assert( stack != NULL );
+	return stack;
+}
+
+
+void
+fsd_exc_stack_destroy( fsd_exc_stack_t *stack )
+{
+	int i;
+	fsd_log_enter((""));
+	for( i = 0;  i < stack->n_restore_points;  i++ )
+	 {
+		fsd_exc_try_block_t *b = stack->restore_points[i];
+		if( b->handled_exc != NULL )
+			b->handled_exc->destroy( b->handled_exc );
+		fsd_free( b );
+	 }
+	fsd_free( stack->restore_points );
+	fsd_free( stack );
+	fsd_log_return((""));
+}
+
+
+fsd_exc_try_block_t *
+fsd_exc_try( const char *function, int lineno )
+{
+	fsd_exc_stack_t *stack = NULL;
+	fsd_exc_try_block_t *p = NULL;
+	int rc;
+
+	/* fsd_log_enter(( "(%s, %d)", function, lineno )); */
+	stack = fsd_exc_get_stack( true );
+	if( stack == NULL )
+		return NULL;
+
+	rc = fsd_realloc_noraise(
+			stack->restore_points, stack->n_restore_points+1,
+			fsd_exc_try_block_t* );
+	if( rc )
+		return NULL;
+	rc = fsd_malloc_noraise( p, fsd_exc_try_block_t );
+	if( rc )
+		return NULL;
+	p->handled_exc = NULL;
+	p->state = FSD_EXC_ENTER;
+	p->function = function;
+	p->lineno = lineno;
+	stack->restore_points[ stack->n_restore_points++ ] = p;
+	/* fsd_log_return(( " =%p", (void*)p )); */
+	return p;
+}
+
+
+void
+fsd_exc_control( fsd_exc_try_block_t *block, int *rc )
+{
+	/* fsd_log_enter(( "(block=%p, rc=%d)", (void*)block, *rc )); */
+	if( block == NULL  ||  *rc == FSD_ERRNO_EXC_END )
+		return;
+
+	switch( block->state )
+	 {
+		case FSD_EXC_ENTER:
+			block->state = FSD_EXC_TRY_BLOCK;
+			fsd_assert( *rc == 0 );
+			/* fsd_log_return(( ": rc=%d => %s:%d",
+						*rc, block->function, block->lineno )); */
+			return;
+
+		case FSD_EXC_TRY_BLOCK:
+			if( *rc == 0 )
+			 {
+				block->state = FSD_EXC_ELSE_BLOCK;
+				/* fsd_log_return(( ": rc=FSD_ERRNO_EXC_ELSE => %s:%d",
+							block->function, block->lineno )); */
+				*rc = FSD_ERRNO_EXC_ELSE;
+				return;
+			 }
+			else
+			 {
+				fsd_assert( *rc > 0 );
+				block->state = FSD_EXC_EXCEPTION_HANDLE;
+				/* fsd_log_return(( ": rc=%d => %s:%d",
+							*rc, block->function, block->lineno )); */
+				return;
+			 }
+
+		case FSD_EXC_EXCEPTION_HANDLE:
+		case FSD_EXC_ELSE_BLOCK:
+			block->state = FSD_EXC_FINALLY_BLOCK;
+			/* fsd_log_return(( ": rc=FSD_ERRNO_EXC_FINALLY => %s:%d",
+						block->function, block->lineno )); */
+			*rc = FSD_ERRNO_EXC_FINALLY;
+			return;
+
+		case FSD_EXC_FINALLY_BLOCK:
+		 {
+			fsd_exc_try_block_t *current = NULL;
+			fsd_exc_try_block_t *upper = NULL;
+			fsd_exc_stack_t *stack = NULL;
+
+			block->state = FSD_EXC_LEAVE;
+
+			stack = fsd_exc_get_stack( false );
+			current = stack->restore_points[ stack->n_restore_points-1 ];
+			fsd_assert( block == current );
+			if( stack->n_restore_points > 1 )
+				upper = stack->restore_points[ stack->n_restore_points-2 ];
+			stack->n_restore_points --;
+
+			if( current->handled_exc  &&  upper )
+			 {
+				if( upper->handled_exc )
+				 {
+					fsd_assert( upper->state == FSD_EXC_EXCEPTION_HANDLE
+							|| upper->state == FSD_EXC_FINALLY_BLOCK );
+					if( upper->state == FSD_EXC_FINALLY_BLOCK )
+						fsd_log_warning((
+									"overriding previously raised exception: <%d:%s>",
+									upper->handled_exc->_code, upper->handled_exc->_message ));
+					upper->handled_exc->destroy( upper->handled_exc );
+				 }
+				upper->handled_exc = current->handled_exc;
+				/* current->handled_exc = NULL; */
+				fsd_free_noraise( current );
+				/* fsd_log_return(( ": longjmp(..., %d) => %s:%d",
+							upper->handled_exc->_code, upper->function, upper->lineno )); */
+				longjmp( upper->env, upper->handled_exc->_code );
+			 }
+			else
+			 {
+				if( current->handled_exc )
+					current->handled_exc->destroy( current->handled_exc );
+				fsd_free_noraise( current );
+				/* fsd_log_return(( ": rc=FSD_ERRNO_EXC_END => %s:%d",
+							block->function, block->lineno )); */
+				*rc = FSD_ERRNO_EXC_END;
+				return;
+			 }
+		 }
+
+		default:
+			fsd_assert(false);
+	 }
+
+	/* no return */
+}
+
+
+const fsd_exc_t *
+fsd_exc_get(void)
+{
+	fsd_exc_stack_t *stack;
+	fsd_exc_try_block_t *block;
+	stack = fsd_exc_get_stack( false );
+	fsd_assert( stack->n_restore_points > 0 );
+	block = stack->restore_points[ stack->n_restore_points-1 ];
+	return block->handled_exc;
+}
+
+
+void
+fsd_exc_clear(void)
+{
+	fsd_exc_stack_t *stack;
+	fsd_exc_try_block_t *block;
+	fsd_log_enter((""));
+	stack = fsd_exc_get_stack( false );
+	fsd_assert( stack->n_restore_points > 0 );
+	block = stack->restore_points[ stack->n_restore_points-1 ];
+	if( block->handled_exc )
+		block->handled_exc->destroy( block->handled_exc );
+	block->handled_exc = NULL;
+	fsd_log_return((""));
+}
+
+
+fsd_exc_t *
+fsd_exc_new( int code, char *message, bool own_message )
+{
+	fsd_exc_t *exc = NULL;
+	char *volatile message_buffer = NULL;
+
+	fsd_log_error(("fsd_exc_new(%d,%s,%d)", code, message, own_message));
+
+	TRY
+	 {
+		if( own_message )
+			message_buffer = message;
+		fsd_malloc( exc, fsd_exc_t );
+		exc->_code = code;
+		exc->_message = message;
+		exc->_own_message = own_message;
+		exc->_own_self = true;
+		exc->code = fsd_exc_code;
+		exc->message = fsd_exc_message;
+		exc->destroy = fsd_exc_destroy;
+	 }
+	EXCEPT_DEFAULT
+	 {
+		fsd_free( message_buffer );
+		fsd_exc_reraise();
+	 }
+	END_TRY
+	return exc;
+}
+
+int
+fsd_exc_code( const fsd_exc_t *self )
+{
+	return self->_code;
+}
+
+const char *
+fsd_exc_message( const fsd_exc_t *self )
+{
+	return self->_message;
+}
+
+void
+fsd_exc_destroy( fsd_exc_t *self )
+{
+	if( self->_own_message )
+		fsd_free_noraise( self->_message );
+	if( self->_own_self )
+		fsd_free_noraise( self );
+}
+
+
+void
+fsd_exc_raise( fsd_exc_t *exc )
+{
+	fsd_exc_stack_t *stack = NULL;
+	fsd_exc_try_block_t *block = NULL;
+	fsd_assert(( exc->_code > 0 ));
+	stack = fsd_exc_get_stack( false );
+	fsd_assert(( stack->n_restore_points > 0 ));
+	block = stack->restore_points[ stack->n_restore_points - 1 ];
+	if( block->handled_exc )
+		block->handled_exc->destroy( block->handled_exc );
+	block->handled_exc = exc;
+	longjmp( block->env, exc->_code );
+}
+
+
+void
+fsd_exc_raise_code( int error_code )
+{
+	fsd_exc_t *exc;
+
+	if( error_code == FSD_ERRNO_NO_MEMORY )
+		exc = (fsd_exc_t*)&no_memory_exception;
+	else
+		exc = fsd_exc_new( error_code, (char*)fsd_strerror(error_code), false );
+	fsd_exc_raise( exc );
+}
+
+void
+fsd_exc_raise_msg( int error_code, const char *message )
+{
+	fsd_exc_raise(
+			fsd_exc_new( error_code, fsd_strdup(message), true ) );
+}
+
+void
+fsd_exc_raise_fmt( int error_code, const char *fmt, ... )
+{
+	va_list args;
+	va_start( args, fmt );
+	fsd_exc_raise_fmtv( error_code, fmt, args );
+	va_end( args );
+}
+
+void
+fsd_exc_raise_fmtv( int error_code, const char *fmt, va_list args )
+{
+	fsd_exc_t *exc = NULL;
+	char *volatile message = NULL;
+	TRY
+	 {
+		message = fsd_vasprintf( fmt, args );
+		exc = fsd_exc_new( error_code, message, true );
+		message = NULL;
+	 }
+	FINALLY
+	 {
+		fsd_free( message );
+	 }
+	END_TRY
+	fsd_exc_raise( exc );
+}
+
+void
+fsd_exc_raise_sys( int errno_code )
+{
+	fsd_exc_t *exc = NULL;
+
+	if( errno_code == 0 )
+		errno_code = errno;
+	if( errno_code == ENOMEM )
+		exc = (fsd_exc_t*)&no_memory_exception;
+	else
+	 {
+		int code;
+		char* volatile message = NULL;
+		volatile bool own_message = false;
+		TRY
+		 {
+			switch( errno_code )
+			 {
+				case ETIMEDOUT:  code = FSD_ERRNO_TIMEOUT;  break;
+				default:         code = FSD_ERRNO_INTERNAL_ERROR;  break;
+			 }
+			message = (char*)fsd_astrerror( errno_code, (bool*)&own_message );
+			exc = fsd_exc_new( code, message, own_message );
+		 }
+		EXCEPT_DEFAULT
+		 {
+			if( message && own_message )
+				fsd_free( message );
+			fsd_exc_reraise();
+		 }
+		END_TRY
+	 }
+	fsd_exc_raise( exc );
+}
+
+
+void
+fsd_exc_reraise(void)
+{
+	fsd_exc_stack_t *stack = NULL;
+	fsd_exc_try_block_t *block = NULL;
+	stack = fsd_exc_get_stack( false );
+	fsd_assert(( stack->n_restore_points > 0 ));
+	block = stack->restore_points[ stack->n_restore_points - 1 ];
+	fsd_assert(( block->handled_exc->_code > 0 ));
+	longjmp( block->env, block->handled_exc->_code );
+}
+
+
+const char *
+fsd_strerror( int error_code )
+{
+	switch( error_code )
+	 {
+		case FSD_ERRNO_SUCCESS:
+			return "Success.";
+		case FSD_ERRNO_INTERNAL_ERROR:
+			return "Unexpected or internal error.";
+		case FSD_ERRNO_NO_MEMORY:
+			return "Not enough memory.";
+		case FSD_ERRNO_INVALID_ARGUMENT:
+			return "Invalid argument value.";
+		case FSD_ERRNO_INVALID_VALUE:
+			return "Invalid value.";
+		case FSD_ERRNO_INVALID_VALUE_FORMAT:
+			return "Invalid value format.";
+		case FSD_ERRNO_STOP_ITERATION:
+			return "Vector have no more elements.";
+		case FSD_ERRNO_NOT_IMPLEMENTED:
+			return "Functionality is not implemented.";
+		case FSD_ERRNO_NOT_INITIALIZED:
+			return "Library is not initialized";
+		case FSD_ERRNO_TIMEOUT:
+			return "Routine returned due to time-out.";
+		case FSD_ERRNO_AUTH_FAILURE:
+			return "Authentication failure.";
+		case FSD_ERRNO_AUTHZ_FAILURE:
+			return "Authorization failure";
+		case FSD_ERRNO_TRY_LATER:
+			return "System is overloaded.  Try again later.";
+		case FSD_ERRNO_DRM_COMMUNICATION_FAILURE:
+			return "Could not contact DRM system for this request.";
+		case FSD_ERRNO_DRMS_INIT_FAILED:
+			return "Unable to initialize DRM system.";
+		case FSD_ERRNO_DRMS_EXIT_ERROR:
+			return "Disengagement from the DRM system failed.";
+		case FSD_ERRNO_DENIED_BY_DRM:
+			return "DRM rejected request due to its configuration "
+				"or request attributes.";
+
+		case FSD_DRMAA_ERRNO_NO_ACTIVE_SESSION:
+			return "No active DRMAA session.";
+		case FSD_DRMAA_ERRNO_INVALID_CONTACT_STRING:
+			return "Invalid contact string.";
+		case FSD_DRMAA_ERRNO_DEFAULT_CONTACT_STRING_ERROR:
+			return "Can not determine default contact to DRM system.";
+		case FSD_DRMAA_ERRNO_NO_DEFAULT_CONTACT_STRING_SELECTED:
+			return "Contact to DRM must be set explicitly "
+				"because there is no default.";
+		case FSD_DRMAA_ERRNO_ALREADY_ACTIVE_SESSION:
+			return "DRMAA session already exist.";
+		case FSD_DRMAA_ERRNO_INVALID_ATTRIBUTE_FORMAT:
+			return "Invalid format of job attribute.";
+		case FSD_DRMAA_ERRNO_INVALID_ATTRIBUTE_VALUE:
+			return "Invalid value of job attribute.";
+		case FSD_DRMAA_ERRNO_CONFLICTING_ATTRIBUTE_VALUES:
+			return "Value of attribute conflicts with other attribute value.";
+		case FSD_DRMAA_ERRNO_INVALID_JOB:
+			return "Job does not exist in DRMs queue.";
+		case FSD_DRMAA_ERRNO_RESUME_INCONSISTENT_STATE:
+			return "Can not resume job (not in valid state).";
+		case FSD_DRMAA_ERRNO_SUSPEND_INCONSISTENT_STATE:
+			return "Can not suspend job (not in valid state).";
+		case FSD_DRMAA_ERRNO_HOLD_INCONSISTENT_STATE:
+			return "Can not hold job (not in valid state).";
+		case FSD_DRMAA_ERRNO_RELEASE_INCONSISTENT_STATE:
+			return "Can not release job (not in valid state).";
+		case FSD_DRMAA_ERRNO_EXIT_TIMEOUT:
+			return "Waiting for job to terminate finished due to time-out.";
+		case FSD_DRMAA_ERRNO_NO_RUSAGE:
+			return "Job finished but resource usage information "
+				"and/or termination status could not be provided.";
+
+		case FSD_ARES_ERRNO_INVALID_CONTACT_STRING:
+			return "Invalid contact string.";
+		case FSD_ARES_ERRNO_INVALID_ATTRIBUTE_FORMAT:
+			return "Invalid format of job attribute.";
+		case FSD_ARES_ERRNO_INVALID_ATTRIBUTE_VALUE:
+			return "Invalid value of job attribute.";
+		case FSD_ARES_ERRNO_CONFLICTING_ATTRIBUTE_VALUES:
+			return "Value of attribute conflicts with other attribute value.";
+		case FSD_ARES_ERRNO_INVALID_ARES:
+			return "Invalid advance reservation identifier..";
+
+		default:
+			return "Unknown error code!?";
+	 }
+}
+
+
+static const int fsd_stacktrace_length = 32;
+
+void
+fsd_assertion_failed(
+		const char *file, int lineno,
+		const char *function, const char *precondition
+		)
+{
+	char *message = NULL;
+	if( asprintf( &message, "%s:%d: %s: Assertion `%s' failed.",
+			file, lineno, function, precondition ) == -1 )
+		message = NULL;
+	if( message != NULL )
+		fsd_log_fatal(( "%s", message ));
+	fsd_log_stacktrace( 1, fsd_stacktrace_length );
+	if( message != NULL )
+		free( message );
+	abort();
+}
+
+
+void *
+fsd_exc_try_except(
+		void*(*f)(void*), void *data,
+		int *error_code,
+		char **error_message
+		)
+{
+	void *result = NULL;
+	TRY
+	 {
+		result = f( data );
+	 }
+	EXCEPT_DEFAULT
+	 {
+		const fsd_exc_t *e = fsd_exc_get();
+		*error_code = e->code(e);
+		*error_message = fsd_strdup( e->message(e) );
+	 }
+	ELSE
+	 {
+		*error_code = FSD_ERRNO_SUCCESS;
+		*error_message = NULL;
+	 }
+	END_TRY
+	return result;
+}
+
+
Index: trunk/drmaa_utils/drmaa_utils/drmaa_attrib.h
===================================================================
--- trunk/drmaa_utils/drmaa_utils/drmaa_attrib.h	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/drmaa_attrib.h	(revision 1)
@@ -0,0 +1,70 @@
+/* $Id: drmaa_attrib.h 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+/**
+ * @file attrib.h
+ * DRMAA attributes.
+ */
+#ifndef __DRMAA_UTILS__DRMAA_ATTRIB_H
+#define __DRMAA_UTILS__DRMAA_ATTRIB_H
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <drmaa_utils/compat.h>
+#include <drmaa_utils/drmaa.h>
+#include <drmaa_utils/common.h>
+
+/**
+ * Attributes codes.
+ */
+enum {
+	/* DRMAA 1.0 attributes: */
+	DRMAA_ATTR_REMOTE_COMMAND,
+	DRMAA_ATTR_ARGS, /* vector */
+	DRMAA_ATTR_JOB_SUBMISSION_STATE,
+	DRMAA_ATTR_JOB_ENVIRONMENT, /* vector */
+	DRMAA_ATTR_WORKING_DIRECTORY,
+	DRMAA_ATTR_JOB_CATEGORY,
+	DRMAA_ATTR_NATIVE_SPECIFICATION,
+	DRMAA_ATTR_EMAIL, /* vector */
+	DRMAA_ATTR_BLOCK_EMAIL,
+	DRMAA_ATTR_START_TIME,
+	DRMAA_ATTR_JOB_NAME,
+	DRMAA_ATTR_INPUT_PATH,
+	DRMAA_ATTR_OUTPUT_PATH,
+	DRMAA_ATTR_ERROR_PATH,
+	DRMAA_ATTR_JOIN_FILES,
+	/* optional DRMAA attributes: */
+	DRMAA_ATTR_TRANSFER_FILES,
+	DRMAA_ATTR_DEADLINE_TIME,
+	DRMAA_ATTR_HARD_WALL_CLOCK_TIME_LIMIT,
+	DRMAA_ATTR_SOFT_WALL_CLOCK_TIME_LIMIT,
+	DRMAA_ATTR_HARD_RUN_DURATION_LIMIT,
+	DRMAA_ATTR_SOFT_RUN_DURATION_LIMIT,
+
+	DRMAA_N_ATTRIBUTES
+};
+
+fsd_template_t *
+drmaa_template_new(void);
+
+#endif /* __DRMAA_UTILS__DRMAA_ATTRIB_H */
+
Index: trunk/drmaa_utils/drmaa_utils/lookup3.h
===================================================================
--- trunk/drmaa_utils/drmaa_utils/lookup3.h	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/lookup3.h	(revision 1)
@@ -0,0 +1,25 @@
+/* $Id: lookup3.h 2 2009-10-12 09:51:22Z mamonski $ */
+
+#ifndef __LOOKUP3_H
+#define __LOOKUP3_H
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <drmaa_utils/compat.h>
+
+uint32_t hashword( const uint32_t *k, size_t length, uint32_t initval );
+uint32_t hashlittle( const void *key, size_t length, uint32_t initval );
+uint32_t hashbig( const void *key, size_t length, uint32_t initval );
+
+#if BYTEORDER == 1234 /* little endian */
+#	define hashstr hashlittle
+#endif
+
+#if BYTEORDER == 4321  /* big endian */
+#	define hashstr hashbig
+#endif
+
+#endif /* __LOOKUP3_H */
+
Index: trunk/drmaa_utils/drmaa_utils/conf_tab.y
===================================================================
--- trunk/drmaa_utils/drmaa_utils/conf_tab.y	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/conf_tab.y	(revision 1)
@@ -0,0 +1,139 @@
+/* $Id: conf_tab.y 2172 2009-02-28 14:26:23Z lukasz $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+%{
+#ifdef HAVE_MALLOC_H
+#       include <malloc.h>
+#endif
+#include <drmaa_utils/conf_impl.h>
+#include <drmaa_utils/conf_tab.h>
+%}
+
+%pure-parser
+%locations
+%name-prefix="fsd_conf_"
+%parse-param { fsd_conf_parser_t *parser }
+%parse-param { fsd_conf_lexer_t *lexer }
+%lex-param { fsd_conf_lexer_t *lexer }
+
+
+%union {
+	int integer;
+	char *string;
+	fsd_conf_option_t *option;
+	fsd_conf_dict_t *dictionary;
+	fsd_conf_pair_t pair;
+}
+
+%type<option> value
+%destructor { fsd_conf_option_destroy($$); } value
+%type<dictionary> start conf dict dict_body pair_list
+%destructor { fsd_conf_dict_destroy($$); } conf dict dict_body pair_list
+%type<pair> pair
+%token<integer> INTEGER
+%token<string> STRING
+%destructor { free($$); } STRING
+%token LEXER_ERROR
+
+
+%%
+
+start
+	: conf { parser->result = $1;  $$ = NULL; }
+	;
+
+conf
+	: dict
+	| dict_body
+	;
+
+dict
+	: '{' dict_body '}' { $$ = $2; }
+	;
+
+dict_body
+	: pair_list  { $$ = $1; }
+	| pair_list ','  { $$ = $1; }
+	| {
+		$$ = fsd_conf_dict_create_noraise();
+		if( $$ == NULL )  YYABORT;
+	}
+	;
+
+pair_list
+	: pair
+		 {
+			fsd_conf_dict_t *dict = NULL;
+			int rc;
+			dict = fsd_conf_dict_create_noraise();
+			if( dict == NULL )
+				YYABORT;
+			rc = fsd_conf_dict_set_noraise( dict, $1.key, $1.value );
+			if( rc )
+			 {
+				fsd_conf_dict_destroy( dict );
+				YYABORT;
+			 }
+			$$ = dict;
+		 }
+	| pair_list ',' pair
+		 {
+			int rc;
+			rc = fsd_conf_dict_set_noraise( $1, $3.key, $3.value );
+			if( rc )
+				YYABORT;
+			$$ = $1; /* explicit no op */
+		 }
+	;
+
+pair
+	: STRING ':' value { $$.key = $1;  $$.value = $3; }
+	;
+
+value
+	: INTEGER
+		 {
+			fsd_conf_option_t *o;
+			o = fsd_conf_option_create_noraise( FSD_CONF_INTEGER, &$1 );
+			if( o )
+				$$ = o;
+			else
+				YYABORT;
+		 }
+	| STRING
+		 {
+			fsd_conf_option_t *o;
+			o = fsd_conf_option_create_noraise( FSD_CONF_STRING, $1 );
+			if( o )
+				$$ = o;
+			else
+				YYABORT;
+		 }
+	| dict
+		 {
+			fsd_conf_option_t *o;
+			o = fsd_conf_option_create_noraise( FSD_CONF_DICT, $1 );
+			if( o )
+				$$ = o;
+			else
+				YYABORT;
+		 }
+	;
+
+%%
Index: trunk/drmaa_utils/drmaa_utils/datetime.h
===================================================================
--- trunk/drmaa_utils/drmaa_utils/datetime.h	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/datetime.h	(revision 1)
@@ -0,0 +1,116 @@
+/* $Id: datetime.h 296 2010-09-15 13:21:14Z mmatloka $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+/**
+ * @file datetime.h
+ * DRMAA and ISO-8601 date/time parser.
+ */
+
+#ifndef __DRMAA_UTILS__DATETIME_H
+#define __DRMAA_UTILS__DATETIME_H
+
+#include <drmaa_utils/common.h>
+
+/**
+ * @defgroup datetime  DRMAA date/time parser.
+ *
+ * It parses date/time string in format of
+ * drmaa_start_time and drmaa_deadline_time attributes.
+ * In other words it accepts time in following format:
+ *
+ * <tt>  [[[[CC]YY/]MM/]DD] hh:mm[:ss] [{-|+}UU:uu]  </tt>
+ *
+ * where
+ *    CC is the first two digits of the year (century-1),
+ *    YY is the last two digits of the year,
+ *    MM is the two digits of the month [01,12],
+ *    DD is the two-digit day of the month [01,31],
+ *    hh is the two-digit hour of the day [00,23],
+ *    mm is the two-digit minute of the day [00,59],
+ *    ss is the two-digit second of the minute [00,61],
+ *    UU is the two-digit hours since (before) UTC,
+ *    uu is the two-digit minutes since (before) UTC.
+ */
+/* @{ */
+
+typedef struct fsd_datetime_s fsd_datetime_t;
+
+/**
+ * Parses date/time.
+ * @param string  Textual representation to date/time.
+ * @return Absolute time according to string.
+ */
+time_t fsd_datetime_parse( const char *string );
+
+/**
+ * Return first timestamp after \a t
+ * which match date/time pattern \a dt.
+ */
+time_t fsd_datetime_after( fsd_datetime_t *dt, time_t t );
+
+/**
+ * Fill unset fields of fsd_datetime_t structure according to timestamp.
+ * @param dt   Will be filled with local time representation of filler.
+ * @param filler  Seconds since epoch.
+ */
+void fsd_datetime_fill( fsd_datetime_t *dt, time_t filler );
+
+/** Makes UTC datetime from (possibly not absolute) fsd_datetime_t. */
+time_t fsd_datetime_mktime( const fsd_datetime_t *dt );
+
+enum{
+	FSD_DT_YEAR         = 1<<0,
+	FSD_DT_MONTH        = 1<<1,
+	FSD_DT_DAY          = 1<<2,
+	FSD_DT_HOUR         = 1<<3,
+	FSD_DT_MINUTE       = 1<<4,
+	FSD_DT_SECOND       = 1<<5,
+	FSD_DT_TZ_DELTA     = 1<<6,
+	FSD_DT_ALL = FSD_DT_YEAR | FSD_DT_MONTH | FSD_DT_DAY
+		| FSD_DT_HOUR | FSD_DT_MINUTE | FSD_DT_SECOND | FSD_DT_TZ_DELTA
+};
+
+/** Intermediate result of parsing date/time string (may be incomplete). */
+struct fsd_datetime_s {
+	unsigned mask;  /**< Bit-set of fields which were set. */
+	int year;       /**< Year. */
+	int month;      /**< Month. */
+	int day;        /**< Day. */
+	int hour;       /**< Hour. */
+	int minute;     /**< Minute. */
+	int second;     /**< Second. */
+	long tz_delta;  /**< Timezone; Number of seconds ahead of UTC. */
+};
+
+
+/**
+ * Guess local timezone for given UTC time
+ * @param t UTC timestamp (time from epoch).
+ * @return Numbef of seconds east (since/before) UTC.  For example in CET
+ * +3600 is returned (UTC + 1 hour).
+ */
+long fsd_timezone( time_t t );
+
+/* @} */
+
+void
+fsd_datetime_dump( const fsd_datetime_t *dt, char *s, size_t len );
+
+#endif /* __DRMAA_UTILS__DATETIME_H */
+
Index: trunk/drmaa_utils/drmaa_utils/exception.h
===================================================================
--- trunk/drmaa_utils/drmaa_utils/exception.h	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/exception.h	(revision 1)
@@ -0,0 +1,257 @@
+/* $Id: exception.h 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+#ifndef __DRMAA_UTILS__EXCEPTION_H
+#define __DRMAA_UTILS__EXCEPTION_H
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <stdarg.h>
+#include <setjmp.h>
+
+#include <drmaa_utils/compat.h>
+
+#if defined(__GNUC__) && defined(DEBUGGING)
+extern int setjmp( jmp_buf __env )
+		__attribute__(( returns_twice ));
+#endif
+
+
+/** Exception type. */
+typedef struct fsd_exc_s fsd_exc_t;
+
+fsd_exc_t *
+fsd_exc_new( int code, char *message, bool own_message );
+
+/** Exception structure. */
+struct fsd_exc_s {
+	int (*code)( const fsd_exc_t* );
+	const char* (*message)( const fsd_exc_t* );
+	void (*destroy)( fsd_exc_t* );
+
+	int _code;
+	char *_message;
+	bool _own_message;
+	bool _own_self;
+};
+
+void
+fsd_exc_raise( fsd_exc_t *exc )
+		__attribute__(( noreturn ));
+
+void
+fsd_exc_raise_code( int error_code )
+		__attribute__(( noreturn ));
+
+void
+fsd_exc_raise_msg( int error_code, const char *message )
+		__attribute__(( noreturn ));
+
+void
+fsd_exc_raise_fmt( int error_code, const char *fmt, ... )
+		__attribute__(( noreturn, format( printf, 2, 3 ) ));
+
+void
+fsd_exc_raise_fmtv( int error_code, const char *fmt, va_list args )
+		__attribute__(( noreturn ));
+
+void
+fsd_exc_raise_sys( int errno_code )
+		__attribute__(( noreturn ));
+
+void
+fsd_exc_reraise(void)
+		__attribute__(( noreturn ));
+
+const fsd_exc_t *
+fsd_exc_get(void);
+
+void
+fsd_exc_clear(void);
+
+
+#define TRY \
+	 { \
+		fsd_exc_try_block_t* volatile _fsd_exc_try_block = NULL; \
+		int _fsd_exc_rc; \
+		_fsd_exc_try_block = fsd_exc_try( __FUNCTION__, __LINE__ ); \
+		if( _fsd_exc_try_block != NULL ) \
+			_fsd_exc_rc = setjmp( _fsd_exc_try_block->env ); \
+		else \
+			_fsd_exc_rc = FSD_ERRNO_EXC_END; \
+		while(1) \
+		 { \
+			bool _fsd_exc_handled = false; \
+			fsd_exc_control( _fsd_exc_try_block, &_fsd_exc_rc ); \
+			if( _fsd_exc_rc == FSD_ERRNO_EXC_END ) \
+				break; \
+			switch( _fsd_exc_rc ) \
+			 { \
+				case 0: {
+#define EXCEPT(error_code) \
+				 } break; \
+				case error_code: { \
+					_fsd_exc_handled = true;
+#define EXCEPT_DEFAULT \
+				 } break; \
+				default: \
+					if( _fsd_exc_rc > 0 ) \
+					 { \
+						_fsd_exc_handled = true;
+#define FINALLY \
+				 } break; \
+				case FSD_ERRNO_EXC_FINALLY: {
+#define ELSE \
+				 } break; \
+				case FSD_ERRNO_EXC_ELSE: {
+#define END_TRY \
+				 } break; \
+			 } \
+			if( _fsd_exc_handled ) \
+			 { \
+				fsd_assert( _fsd_exc_try_block->handled_exc != NULL ); \
+				_fsd_exc_try_block->handled_exc->destroy( \
+						_fsd_exc_try_block->handled_exc ); \
+				_fsd_exc_try_block->handled_exc = NULL; \
+			 } \
+		 } \
+	 }
+
+
+/** The state of exception handling block. */
+typedef enum {
+	FSD_EXC_ENTER, /**< Before try. */
+	FSD_EXC_TRY_BLOCK, /**< Insidie try-block. */
+	FSD_EXC_EXCEPTION_HANDLE, /**< Inside exception handling block. */
+	FSD_EXC_ELSE_BLOCK, /**< Inside else-block. */
+	FSD_EXC_FINALLY_BLOCK, /**< Inside finally block. */
+	FSD_EXC_LEAVE /**< Leaving try/except/finally block (after finally). */
+} fsd_exc_try_block_state_t;
+
+/**
+ * Try/except/else/finally block data structure.
+ * Holds the state for exception handling module.
+ *
+ * It also represents a point on the stack and other state of
+ * thread to wich it can be restored during "stack rollback"
+ * process after exception is raised.
+ */
+typedef struct fsd_exc_try_block_s {
+	jmp_buf env;  /**< Stack restore point for \c longjmp. */
+	fsd_exc_t *handled_exc; /**< Exception handled within block */
+	fsd_exc_try_block_state_t state;
+	const char *function; /**< Name of function */
+	int lineno; /**< Line number where try-block starts */
+} fsd_exc_try_block_t;
+
+
+fsd_exc_try_block_t *
+fsd_exc_try( const char *function, int lineno );
+
+void
+fsd_exc_control( fsd_exc_try_block_t *block, int *rc );
+
+
+const char *
+fsd_strerror( int error_code );
+
+/** Error codes. */
+typedef enum {
+	FSD_ERRNO_SUCCESS                    =  0,
+
+	FSD_ERRNO_EXC_ELSE                   = -1,
+	FSD_ERRNO_EXC_FINALLY                = -2,
+	FSD_ERRNO_EXC_END                    = -3,
+
+	/* _FSD_ERRNO_START = 1000, */
+
+	FSD_ERRNO_INTERNAL_ERROR             = 1001,
+	FSD_ERRNO_NO_MEMORY                  = 1002,
+	FSD_ERRNO_INVALID_ARGUMENT           = 1003,
+	FSD_ERRNO_INVALID_VALUE              = 1004,
+	FSD_ERRNO_INVALID_VALUE_FORMAT       = 1005,
+	FSD_ERRNO_STOP_ITERATION             = 1006,
+	FSD_ERRNO_NOT_IMPLEMENTED            = 1007,
+	FSD_ERRNO_NOT_INITIALIZED            = 1008,
+	FSD_ERRNO_TIMEOUT                    = 1009,
+	FSD_ERRNO_AUTH_FAILURE               = 1010,
+	FSD_ERRNO_AUTHZ_FAILURE              = 1011,
+	FSD_ERRNO_TRY_LATER                  = 1012,
+
+	FSD_ERRNO_DRM_COMMUNICATION_FAILURE  = 1013,
+	FSD_ERRNO_DRMS_INIT_FAILED           = 1014,
+	FSD_ERRNO_DRMS_EXIT_ERROR            = 1015,
+	FSD_ERRNO_DENIED_BY_DRM              = 1016,
+
+	/* DRMAA specific error codes: */
+	FSD_DRMAA_ERRNO_NO_ACTIVE_SESSION                    = 1032,
+	FSD_DRMAA_ERRNO_INVALID_CONTACT_STRING               = 1033,
+	FSD_DRMAA_ERRNO_DEFAULT_CONTACT_STRING_ERROR         = 1034,
+	FSD_DRMAA_ERRNO_NO_DEFAULT_CONTACT_STRING_SELECTED   = 1035,
+	FSD_DRMAA_ERRNO_ALREADY_ACTIVE_SESSION               = 1036,
+	FSD_DRMAA_ERRNO_INVALID_ATTRIBUTE_FORMAT             = 1037,
+	FSD_DRMAA_ERRNO_INVALID_ATTRIBUTE_VALUE              = 1038,
+	FSD_DRMAA_ERRNO_CONFLICTING_ATTRIBUTE_VALUES         = 1039,
+	FSD_DRMAA_ERRNO_INVALID_JOB                          = 1040,
+	FSD_DRMAA_ERRNO_RESUME_INCONSISTENT_STATE            = 1041,
+	FSD_DRMAA_ERRNO_SUSPEND_INCONSISTENT_STATE           = 1042,
+	FSD_DRMAA_ERRNO_HOLD_INCONSISTENT_STATE              = 1043,
+	FSD_DRMAA_ERRNO_RELEASE_INCONSISTENT_STATE           = 1044,
+	FSD_DRMAA_ERRNO_EXIT_TIMEOUT                         = 1045,
+	FSD_DRMAA_ERRNO_NO_RUSAGE                            = 1046,
+
+	/* ARes specific error codes: */
+	FSD_ARES_ERRNO_INVALID_CONTACT_STRING                = 1052,
+	FSD_ARES_ERRNO_INVALID_ATTRIBUTE_FORMAT              = 1053,
+	FSD_ARES_ERRNO_INVALID_ATTRIBUTE_VALUE               = 1054,
+	FSD_ARES_ERRNO_CONFLICTING_ATTRIBUTE_VALUES          = 1055,
+	FSD_ARES_ERRNO_INVALID_ARES                          = 1056,
+
+	FSD_MIN_ERRNO = FSD_ERRNO_INTERNAL_ERROR,
+	FSD_MAX_ERRNO = FSD_ARES_ERRNO_INVALID_ARES
+} fsd_errno_t;
+
+
+#ifndef NDEBUG
+#	define fsd_assert( precondition ) \
+		do { \
+			if( ! (precondition) ) \
+				fsd_assertion_failed( __FILE__, __LINE__, \
+						__FUNCTION__, #precondition ); \
+		} while(0)
+#else
+#	define fsd_assert( precondition )  do{/* nothing */}while(0)
+#endif
+
+void
+fsd_assertion_failed( const char *file, int lineno,
+		const char *function, const char *precondition )
+		__attribute__(( noreturn ));
+
+void *
+fsd_exc_try_except(
+		void*(*f)(void*), void *data,
+		int *error_code,
+		char **error_message
+		);
+
+#endif /* __DRMAA_UTILS__EXCEPTION_H */
+
Index: trunk/drmaa_utils/drmaa_utils/iter.c
===================================================================
--- trunk/drmaa_utils/drmaa_utils/iter.c	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/iter.c	(revision 1)
@@ -0,0 +1,145 @@
+/* $Id: iter.c 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ * FedStage DRMAA utilities library
+ * Copyright (C) 2006-2008  FedStage Systems
+ *
+ * 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 <drmaa_utils/iter.h>
+
+#ifndef lint
+static char rcsid[]
+#	ifdef __GNUC__
+		__attribute__ ((unused))
+#	endif
+	= "$Id: iter.c 2 2009-10-12 09:51:22Z mamonski $";
+#endif
+
+
+static const char *
+fsd_iter_next( fsd_iter_t *self )
+{
+	if( self->_position < self->_length )
+		return self->_list[ self->_position++ ];
+	else
+		fsd_exc_raise_code( FSD_ERRNO_STOP_ITERATION );
+}
+
+static void
+fsd_iter_reset( fsd_iter_t *self )
+{
+	self->_length = 0;
+}
+
+static int
+fsd_iter_len( fsd_iter_t *self )
+{
+	return self->_length;
+}
+
+static void
+fsd_iter_append( fsd_iter_t *self, char *string )
+{
+	TRY
+	 {
+		if( !self->_own_list )
+			fsd_exc_raise_msg(
+					FSD_ERRNO_INTERNAL_ERROR,
+					"iter::append called on constant list" );
+		fsd_realloc( self->_list, self->_length+1, char* );
+		self->_list[ self->_length++ ] = string;
+	 }
+	EXCEPT_DEFAULT
+	 {
+		fsd_free( string );
+		fsd_exc_reraise();
+	 }
+	END_TRY
+}
+
+static void
+fsd_iter_destroy( fsd_iter_t *self )
+{
+	int i;
+	if( self->_own_list  &&  self->_list )
+	 {
+		for( i = 0;  i < self->_length;  i++ )
+			fsd_free( self->_list[i] );
+		fsd_free( self->_list );
+	 }
+	fsd_free( self );
+}
+
+static fsd_iter_t *
+fsd_iter_new_impl( char **list, int length, bool own )
+{
+	fsd_iter_t *volatile self = NULL;
+	TRY
+	 {
+		fsd_malloc( self, fsd_iter_t );
+		self->next = fsd_iter_next;
+		self->reset = fsd_iter_reset;
+		self->len = fsd_iter_len;
+		self->append = fsd_iter_append;
+		self->destroy = fsd_iter_destroy;
+		self->_list = list;
+		self->_position = 0;
+		if( list == NULL )
+			self->_length = 0;
+		else if( length >= 0 )
+			self->_length = length;
+		else
+		 {
+			char **i;
+			int cnt = 0;
+			for( i = self->_list;  *i != NULL;  i++ )
+				cnt++;
+			self->_length = cnt;
+		 }
+		self->_own_list = own;
+	 }
+	EXCEPT_DEFAULT
+	 {
+		if( own  &&  list )
+		 {
+			if( length >= 0 )
+			 {
+				int i;
+				for( i = 0;  i < length;  i++ )
+					fsd_free( list[i] );
+				fsd_free( list );
+			 }
+			else
+				fsd_free_vector( list );
+		 }
+		fsd_exc_reraise();
+	 }
+	END_TRY
+	return self;
+}
+
+fsd_iter_t *
+fsd_iter_new( char **list, int length )
+{
+	return fsd_iter_new_impl( list, length, true );
+}
+
+fsd_iter_t *
+fsd_iter_new_const( const char *const *list, int length )
+{
+	return fsd_iter_new_impl( (char**)list, length, false );
+}
+
Index: trunk/drmaa_utils/drmaa_utils/timedelta.rl
===================================================================
--- trunk/drmaa_utils/drmaa_utils/timedelta.rl	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/timedelta.rl	(revision 1)
@@ -0,0 +1,79 @@
+/* $Id: timedelta.rl 1452 2008-10-02 12:09:09Z lukasz $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <string.h>
+
+#include <drmaa_utils/common.h>
+
+#ifndef lint
+static char rcsid[]
+#	ifdef __GNUC__
+		__attribute__ ((unused))
+#	endif
+	= "$Id: timedelta.rl 1452 2008-10-02 12:09:09Z lukasz $";
+#endif
+
+int
+fsd_parse_timedelta( const char *string )
+{
+	%%{
+		machine fsd_timedelta;
+		action error {
+			fsd_exc_raise_fmt(
+					FSD_ERRNO_INVALID_VALUE_FORMAT,
+					"time delta syntax error: %s", string );
+		}
+		action next_field {
+			fields[ n_fields++ ] = v;
+		}
+		integer = [0-9]+ >{ v = 0; } ${ v *= 10;  v += fc - '0'; };
+		timedelta = integer %next_field (':' integer %next_field){1,2};
+		main := timedelta @eof(error) $err(error);
+	}%%
+
+	%%write data;
+	int v = 0;
+	int fields[3];
+	int n_fields = 0;
+	int timedelta;
+	int i;
+
+	const char *p = string;
+	const char *pe = p + strlen(p);
+	const char *eof = pe;
+	int cs;
+
+	fsd_log_enter(( "(%s)", string ));
+	%%write init;
+	%%write exec;
+	timedelta = 0;
+	for( i = 0;  i < n_fields;  i++ )
+	 {
+		timedelta *= 60;
+		timedelta += fields[i];
+	 }
+	fsd_log_return(( " =%d", timedelta ));
+	return timedelta;
+}
+
+/* vim: set ft=ragel: */
Index: trunk/drmaa_utils/drmaa_utils/iter.h
===================================================================
--- trunk/drmaa_utils/drmaa_utils/iter.h	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/iter.h	(revision 1)
@@ -0,0 +1,49 @@
+/* $Id: iter.h 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ * FedStage DRMAA utilities library
+ * Copyright (C) 2006-2008  FedStage Systems
+ *
+ * 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/>.
+ */
+
+#ifndef __DRMAA_UTILS__ITER_H
+#define __DRMAA_UTILS__ITER_H
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <drmaa_utils/common.h>
+
+fsd_iter_t *
+fsd_iter_new( char **list, int length );
+
+fsd_iter_t *
+fsd_iter_new_const( const char *const *list, int length );
+
+struct fsd_iter_s {
+	const char* (*next)( fsd_iter_t *self );
+	void (*reset)( fsd_iter_t *self );
+	int (*len)( fsd_iter_t *self );
+	void (*append)( fsd_iter_t *self, char *string );
+	void (*destroy)( fsd_iter_t *self );
+	
+	char **_list;
+	int _position;
+	int _length;
+	bool _own_list;
+};
+
+#endif /* __DRMAA_UTILS__ITER_H */
+
Index: trunk/drmaa_utils/drmaa_utils/template.c
===================================================================
--- trunk/drmaa_utils/drmaa_utils/template.c	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/template.c	(revision 1)
@@ -0,0 +1,180 @@
+/* $Id: template.c 284 2010-09-13 08:39:55Z mmatloka $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <drmaa_utils/compat.h>
+#include <drmaa_utils/template.h>
+#include <drmaa_utils/util.h>
+
+#ifndef lint
+static char rcsid[]
+#	ifdef __GNUC__
+		__attribute__ ((unused))
+#	endif
+	= "$Id: template.c 284 2010-09-13 08:39:55Z mmatloka $";
+#endif
+
+
+static const char*
+fsd_template_get_attr( const fsd_template_t *self, const char *name )
+{
+	const fsd_attribute_t *attr = NULL;
+	if( name == NULL )
+		fsd_exc_raise_code( FSD_ERRNO_INVALID_ARGUMENT );
+	attr = self->by_name( self, name );
+	if( attr == NULL  ||  attr->is_vector )
+		fsd_exc_raise_fmt(
+				FSD_ERRNO_INVALID_ARGUMENT,
+				"invalid scalar attribute name: %s", name
+				);
+	return (const char*) self->attributes[ attr->code ];
+}
+
+
+static void
+fsd_template_set_attr( fsd_template_t *self,
+		const char *name, const char *value )
+{
+	const fsd_attribute_t *attr = NULL;
+	fsd_log_enter(("(%s=%s)", name, value));
+	if( name == NULL )
+		fsd_exc_raise_code( FSD_ERRNO_INVALID_ARGUMENT );
+	attr = self->by_name( self, name );
+	if( attr == NULL  ||  attr->is_vector )
+		fsd_exc_raise_fmt(
+				FSD_ERRNO_INVALID_ARGUMENT,
+				"invalid scalar attribute name: %s", name
+				);
+	if( value != NULL ) {
+		if( self->attributes[ attr->code ] != NULL ) {
+			fsd_free(self->attributes[ attr->code ]);
+		}
+		self->attributes[ attr->code ] = fsd_strdup( value );
+	}
+	else
+		self->attributes[ attr->code ] = NULL;
+}
+
+
+static const char* const*
+fsd_template_get_v_attr( const fsd_template_t *self, const char *name )
+{
+	const fsd_attribute_t *attr = NULL;
+	if( name == NULL )
+		fsd_exc_raise_code( FSD_ERRNO_INVALID_ARGUMENT );
+	attr = self->by_name( self, name );
+	if( attr == NULL  ||  ! attr->is_vector )
+		fsd_exc_raise_fmt(
+				FSD_ERRNO_INVALID_ARGUMENT,
+				"invalid vector attribute name: %s", name
+				);
+	return (const char* const*) self->attributes[ attr->code ];
+}
+
+
+static void
+fsd_template_set_v_attr( fsd_template_t *self,
+		const char *name, const char **value )
+{
+	const fsd_attribute_t *attr = NULL;
+	char **volatile v = NULL;
+
+	if( name == NULL )
+		fsd_exc_raise_code( FSD_ERRNO_INVALID_ARGUMENT );
+	attr = self->by_name( self, name );
+	if( attr == NULL  ||  ! attr->is_vector )
+		fsd_exc_raise_fmt(
+				FSD_ERRNO_INVALID_ARGUMENT,
+				"invalid vector attribute name: %s", name
+				);
+
+	TRY
+	 {
+		int code = attr->code;
+		if( value != NULL )
+			v = fsd_copy_vector( value );
+		if( self->attributes[code] != NULL )
+			fsd_free_vector( self->attributes[code] );
+		self->attributes[code] = v;  v = NULL;
+	 }
+	FINALLY
+	 { fsd_free_vector( v ); }
+	END_TRY
+}
+
+
+static void
+fsd_template_destroy( fsd_template_t *self )
+{
+	unsigned i;
+	for( i = 0;  i < self->n_attributes;  i++ )
+		if( self->attributes[i] != NULL )
+		 {
+			const fsd_attribute_t *attr;
+			attr = self->by_code( self, i );
+			if( attr )
+			 {
+				if( attr->is_vector )
+					fsd_free_vector( self->attributes[i] );
+				else
+					fsd_free( self->attributes[i] );
+			 }
+		 }
+	fsd_free( self->attributes );
+	fsd_free( self );
+}
+
+
+fsd_template_t *
+fsd_template_new(
+		fsd_template_by_name_method *by_name_method,
+		fsd_template_by_code_method *by_code_method,
+		unsigned n_attributes
+		)
+{
+	fsd_template_t *volatile self = NULL;
+	TRY
+	 {
+		fsd_malloc( self, fsd_template_t );
+		self->attributes = NULL;
+		self->n_attributes = 0;
+		self->get_attr = fsd_template_get_attr;
+		self->set_attr = fsd_template_set_attr;
+		self->get_v_attr = fsd_template_get_v_attr;
+		self->set_v_attr = fsd_template_set_v_attr;
+		self->by_name = by_name_method;
+		self->by_code = by_code_method;
+		self->destroy = fsd_template_destroy;
+
+		fsd_calloc( self->attributes, n_attributes, void* );
+		self->n_attributes = n_attributes;
+	 }
+	EXCEPT_DEFAULT
+	 {
+		if( self )
+			self->destroy( self );
+		fsd_exc_reraise();
+	 }
+	END_TRY
+	return self;
+}
+
Index: trunk/drmaa_utils/drmaa_utils/job.h
===================================================================
--- trunk/drmaa_utils/drmaa_utils/job.h	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/job.h	(revision 1)
@@ -0,0 +1,246 @@
+/* $Id: job.h 255 2010-08-05 15:53:36Z mamonski $ */
+/*
+ * FedStage DRMAA utilities library
+ * Copyright (C) 2006-2008  FedStage Systems
+ *
+ * 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/>.
+ */
+
+/**
+ * @file job.h
+ * Job managing functions.
+ */
+
+#ifndef __DRMAA_UTILS__JOB_H
+#define __DRMAA_UTILS__JOB_H
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <sys/time.h>
+
+#include <drmaa_utils/common.h>
+#include <drmaa_utils/thread.h>
+
+/**
+ * Create new job structure.
+ * @return Sole reference to newly created job.
+ */
+fsd_job_t *
+fsd_job_new( char *job_id );
+
+/** Job state flags. */
+typedef enum {
+	/**
+	 * Job is in queued state (either active or hold in queue).
+	 */
+	FSD_JOB_QUEUED             = 1<<0,
+	/** Job is hold in queue. */
+	FSD_JOB_HOLD               = 1<<1,
+	/** Job is running (suspended or not). */
+	FSD_JOB_RUNNING            = 1<<2,
+	/**
+	 * Set when job was suspended within session by
+	 * drmaa_control(DRMAA_CONTROL_SUSPEND).
+	 */
+	FSD_JOB_SUSPENDED          = 1<<3,
+	/**
+	 * Whether we know that job terminated and its status
+	 * is waiting to rip.
+	 */
+	FSD_JOB_TERMINATED         = 1<<4,
+	/**
+	 * It is known that job was aborted by user.
+	 */
+	FSD_JOB_ABORTED            = 1<<5,
+
+	/**
+	 * Job was submitted in current session.
+	 * It is set for all jobs which are or was
+	 * in fsd_drmaa_session_t#jobs set.
+	 */
+	FSD_JOB_CURRENT_SESSION    = 1<<6,
+
+	/**
+	 * Job is removed from session (but references to job still
+	 * exist).  No such job shall exist in session's submited
+	 * jobs set.
+	 */
+	FSD_JOB_DISPOSED           = 1<<7,
+
+	FSD_JOB_MISSING            = 1<<8,
+
+	FSD_JOB_QUEUED_MASK      = FSD_JOB_QUEUED | FSD_JOB_HOLD,
+	FSD_JOB_RUNNING_MASK     = FSD_JOB_RUNNING | FSD_JOB_SUSPENDED,
+	FSD_JOB_TERMINATED_MASK  = FSD_JOB_TERMINATED | FSD_JOB_ABORTED,
+	FSD_JOB_STATE_MASK       = FSD_JOB_HOLD | FSD_JOB_RUNNING
+		| FSD_JOB_SUSPENDED | FSD_JOB_TERMINATED
+} fsd_job_flag_t;
+
+
+/** Submitted job data. */
+struct fsd_job_s {
+	/** Release reference to job. */
+	void (*release)( fsd_job_t *self );
+
+	/** Destroy job data. */
+	void (*destroy)( fsd_job_t *self );
+
+	/** Implements drmaa_control(). */
+	void (*control)( fsd_job_t *self, int action );
+
+	/** Fetch job state from DRM. */
+	void (*update_status)( fsd_job_t *self );
+
+	/** Return job termination status and resource usage for drmaa_wait(). */
+	void (*get_termination_status)( fsd_job_t *self,
+			int *status, fsd_iter_t **rusage_out );
+
+	/**
+	 * Called whenever job is detected to be missing from DRM queue
+	 * while stil being within DRMAA session.
+	 */
+	void (*on_missing)( fsd_job_t *self );
+
+	/**
+	 * Points to next job in list.
+	 * Used by #fsd_job_set_t.
+	 */
+	fsd_job_t *next;
+
+	/** Number of references. */
+	int ref_cnt;
+
+	/** Job identifier (as null terminated string). */
+	char *job_id;
+
+	/** DRMAA session which job was submitted in. */
+	fsd_drmaa_session_t *session;
+
+	/**
+	 * Time of last update of job status and rusage information
+	 * (when status, exit_status, cpu_usage, mem_usage and flags
+	 * fields was updated according to DRM).
+	 */
+	time_t last_update_time;
+
+	/** Job state flags.  @see job_flag_t */
+	unsigned flags;
+
+	/**
+	 * State of job (as returned by drmaa_job_ps())
+	 * from last retrieval from DRM.
+	 */
+	int state;
+
+	/** Exit status of job as from <tt>wait(2)</tt>. */
+	int exit_status;
+	/** Time of job submission (local). */
+	time_t submit_time;
+	/** Time when job started execution (taken from DRM). */
+	time_t start_time;
+	/** Time when job ended execution (taken from DRM). */
+	time_t end_time;
+	/** CPU time usage in seconds. */
+	long cpu_usage;
+	/** Resident memory usage in bytes. */
+	long mem_usage;
+	/** Virtual memory usage in bytes. */
+	long vmem_usage;
+	/** Total run time in seconds. */
+	long walltime;
+	/** List of space separated execution host names. */
+	char *execution_hosts;
+	/** Batch queue name */
+	char *queue;
+	/** Account string */
+	char *project;
+
+	/** Mutex for accessing fsd_job_s structure (beside #next pointer). */
+	fsd_mutex_t  mutex;
+	/** Job status changed condition. */
+	fsd_cond_t   status_cond;
+	/** Able to destroy condition variable (ref_cnt==1). */
+	fsd_cond_t   destroy_cond;
+};
+
+
+
+/** Create empty set of jobs. */
+fsd_job_set_t *
+fsd_job_set_new(void);
+
+struct fsd_job_set_s {
+	/** Destroy set of jobs (including contained job handles). */
+	void (*
+	destroy)( fsd_job_set_t *self );
+
+	/** Adds job to set. */
+	void (*
+	add)( fsd_job_set_t *self, fsd_job_t *job );
+
+	/** Remove job from set. */
+	void (*
+	remove)( fsd_job_set_t *self, fsd_job_t *job );
+
+	/**
+	 * Finds job with given job_id.
+	 * @param job_set Set of jobs to search in.
+	 * @param job_id Job identifier.
+	 * @return If successful job handle is returned
+	 * and caller have exclusive access right to it.
+	 * It should be released by #release().
+	 * \c NULL is returned when job was not found.
+	 */
+	fsd_job_t* (*
+	get)( fsd_job_set_t *self, const char *job_id );
+
+	/** Whether the set is empty. */
+	bool (*
+	empty)( fsd_job_set_t *self );
+
+	/**
+	 * Find any job in set which was terminated (either successfully or not).
+	 * It is usefull for drmaa_wait( DRMAA_JOB_IDS_ANY ) implementation.
+	 * @param job_set Set of jobs to search in.
+	 * @return New reference to terminated job
+	 *   or \c NULL if no such job is present in set.
+	 * @see fsd_job_find
+	 */
+	fsd_job_t* (*
+	find_terminated)( fsd_job_set_t *self );
+
+	/**
+	 * Return idenetifiers of all jobs in set.
+	 * @param job_set Set of jobs.
+	 * @return Vector of job idenetifiers
+	 *   when done free it with fsd_free_vector.
+	 */
+	char** (*
+	get_all_job_ids)( fsd_job_set_t *self );
+
+	void (*
+	signal_all)( fsd_job_set_t *self );
+
+	fsd_job_t    **tab;
+	size_t         tab_size;
+	uint32_t       tab_mask;
+	/** Number of jobs in set. */
+	unsigned       n_jobs;
+	/** Mutex for job set data (e.g. for adding/removing job from set). */
+	fsd_mutex_t    mutex;
+};
+
+#endif /* __DRMAA_UTILS__JOB_H */
Index: trunk/drmaa_utils/drmaa_utils/template.h
===================================================================
--- trunk/drmaa_utils/drmaa_utils/template.h	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/template.h	(revision 1)
@@ -0,0 +1,77 @@
+/* $Id: template.h 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+#ifndef __DRMAA_UTILS__TEMPLATE_H
+#define __DRMAA_UTILS__TEMPLATE_H
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <drmaa_utils/common.h>
+
+typedef const fsd_attribute_t *
+fsd_template_by_name_method( const fsd_template_t *self, const char *name );
+
+typedef const fsd_attribute_t *
+fsd_template_by_code_method( const fsd_template_t *self, int code );
+
+
+fsd_template_t *
+fsd_template_new(
+		fsd_template_by_name_method *by_name_method,
+		fsd_template_by_code_method *by_code_method,
+		unsigned n_attributes
+		);
+
+struct fsd_template_s {
+	const char* (*
+	get_attr)( const fsd_template_t *self, const char *name );
+
+	void (*
+	set_attr)( fsd_template_t *self, const char *name, const char *value );
+
+	const char* const* (*
+	get_v_attr)( const fsd_template_t *self, const char *name );
+
+	void (*
+	set_v_attr)( fsd_template_t *self, const char *name, const char **value );
+
+	const fsd_attribute_t* (*
+	by_name)( const fsd_template_t *self, const char *name ); 
+
+	const fsd_attribute_t* (*
+	by_code)( const fsd_template_t *self, int code );
+
+	void (*
+	destroy)( fsd_template_t *self );
+
+	void **attributes;
+	unsigned n_attributes;
+};
+
+struct fsd_attribute_s {
+	const char *name;
+	int code;
+	bool is_vector;
+};
+
+
+#endif /* __DRMAA_UTILS__TEMPLATE_H */
+
Index: trunk/drmaa_utils/drmaa_utils/util.h
===================================================================
--- trunk/drmaa_utils/drmaa_utils/util.h	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/util.h	(revision 1)
@@ -0,0 +1,155 @@
+/* $Id: util.h 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+/**
+ * @file util.h
+ * Various functions.
+ */
+
+#ifndef __DRMAA_UTILS__UTIL_H
+#define __DRMAA_UTILS__UTIL_H
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <time.h>
+
+#include <drmaa_utils/common.h>
+#include <drmaa_utils/compat.h>
+
+char *fsd_explode( const char *const *vector, char glue, int n );
+void fsd_free_vector( char **vector );
+char **fsd_copy_vector( const char *const * vector );
+char *fsd_replace( char *input, const char *placeholder, const char *value );
+
+char *fsd_strdup( const char *s );
+char *fsd_strndup( const char *s, size_t n );
+
+int fsd_atoi( const char *s );
+
+void
+fsd_str_append(
+		bool *truncated,
+		char **p, char *end,
+		const char *fmt, ...
+		)
+		__attribute__(( format( printf, 4, 5 ) ));
+
+size_t
+fsd_snprintf(
+		bool *truncated,
+		char *str, size_t size,
+		const char *fmt, ...
+		)
+		__attribute__(( format( printf, 4, 5 ) ));
+
+size_t
+fsd_vsnprintf(
+		bool *truncated,
+		char *str, size_t size,
+		const char *fmt, va_list args
+		);
+
+/**
+ * Behaves like asprintf function from standard C library
+ * except any errors are marked in error context structure.
+ *
+ * It substitutes `%m` format string as in glibc
+ * (with `strerror(errno)`).
+ */
+char *fsd_asprintf( const char *fmt, ... )
+		__attribute__(( format( __printf__, 1, 2 ) ));
+
+/**
+ * Behaves like vasprintf function from standard C library
+ * except any errors are marked in error context structure.
+ */
+char *fsd_vasprintf( const char *fmt, va_list args );
+
+/**
+ * Implements GNU version of strerror_r function - thread-safe
+ * function returning message describing error code.
+ *
+ * From Linux Programmer's Manual:
+ *
+ * <code> char *strerror_r(int errnum, char *buf, size_t buflen); </code>
+ *
+ * The GNU-specific strerror_r() returns a pointer to a string containing
+ * the error message.  This may be either a pointer to a string that the
+ * function stores in buf, or a pointer to some (immutable) static string
+ * (in which case buf is unused).  If the function stores a string in
+ * buf, then at most buflen bytes are stored (the string may be truncated
+ * if buflen is too small) and the string always includes a terminating
+ * null byte.
+ */
+const char *
+fsd_strerror_r( int errnum, char *buffer, size_t buffer_size );
+
+char *
+fsd_astrerror( int errnum, bool *malloced );
+
+/** Retrievs current system timestamp. */
+void fsd_get_time( struct timespec *ts );
+
+/** Add delta to timestamp. */
+void fsd_ts_add( struct timespec *a, const struct timespec *b );
+
+/**
+ * Compares two timestamps.
+ * @return Negative integer when a < b (a represents earlier timestamp),
+ *   positive integer when a > b or 0 when timestamps are equal.
+ */
+int fsd_ts_cmp( const struct timespec *a, const struct timespec *b );
+
+/**
+ * Reads file contents.
+ * @param filename  Path to the file.
+ * @param must_exist  Controls behaviour when file not exist
+ *   (or is not readable).  If set to \c true DRMAA_ERRNO_INTERNAL_ERROR
+ *   is raised on such occasion.  If set to \c false only
+ *   \a content is set to \c NULL and no error is raised.
+ * @param content  Filled with pointer to buffer with file contents
+ *   or \c NULL when error is encoureged.  Caller is responsible
+ *   for free()'ing it.
+ * @param length  Filled with length of \a content buffer.
+ */
+void
+fsd_read_file(
+		const char *filename, bool must_exist,
+		char **content, size_t *length
+		);
+
+/**
+ * Gets path to current working directory.
+ * @return  Path to process's current working directory
+ *   in malloc'ed '\0' terminated buffer
+ *   or \c NULL in case of error.
+ */
+char *
+fsd_getcwd(void);
+
+/**
+ * Returns signal name.
+ * @param signum  Valid signal number.
+ */
+const char *
+fsd_strsignal( int signum );
+
+#endif /* __DRMAA_UTILS__UTIL_H */
Index: trunk/drmaa_utils/drmaa_utils/conf.c
===================================================================
--- trunk/drmaa_utils/drmaa_utils/conf.c	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/conf.c	(revision 1)
@@ -0,0 +1,579 @@
+/* $Id: conf.c 226 2010-05-25 10:47:18Z mamonski $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <ctype.h>
+#include <stdarg.h>
+#include <string.h>
+
+#include <drmaa_utils/common.h>
+#include <drmaa_utils/conf_impl.h>
+#include <drmaa_utils/conf_tab.h>
+#include <drmaa_utils/logging.h>
+#include <drmaa_utils/util.h>
+
+#ifndef lint
+static char rcsid[]
+#	ifdef __GNUC__
+		__attribute__ ((unused))
+#	endif
+	= "$Id: conf.c 226 2010-05-25 10:47:18Z mamonski $";
+#endif
+
+
+fsd_conf_dict_t *
+fsd_conf_read(
+	        fsd_conf_dict_t  * volatile configuration,
+		const char *filename, bool must_exist,
+		const char *content, size_t content_len
+		)
+{
+	fsd_conf_dict_t *volatile result = NULL;
+	fsd_conf_parser_t *parser = NULL;
+	fsd_conf_lexer_t *lexer = NULL;
+	char *file_content = NULL;
+	size_t file_content_len = 0;
+
+	fsd_log_enter((
+		"(filename=%s, must_exist=%s, content=%s)",
+		filename, must_exist ? "true" : "false", content
+		));
+
+	TRY
+	 {
+		fsd_malloc( parser, fsd_conf_parser_t );
+		fsd_malloc( lexer, fsd_conf_lexer_t );
+
+		parser->lexer = lexer;
+		parser->result = NULL;
+		parser->n_errors = 0;
+		parser->errors = NULL;
+
+		lexer->parser = parser;
+		lexer->filename = filename;
+		lexer->buffer = NULL;
+		lexer->buflen = 0;
+		lexer->pos = NULL;
+		lexer->lineno = 0;
+		lexer->cline = NULL;
+
+		if( filename )
+			TRY
+			 {
+				fsd_read_file(
+						filename, must_exist,
+						&file_content, &file_content_len
+						);
+			 }
+			EXCEPT_DEFAULT
+			 {
+				const fsd_exc_t *e = fsd_exc_get();
+				if( must_exist )
+					fsd_exc_raise_fmt( e->code(e), "%s: %s", filename, e->message(e) );
+				else
+				 {
+					fsd_log_warning(( "%s: %s", filename, e->message(e) ));
+				 }
+			 }
+			END_TRY
+
+		if( file_content )
+		 {
+			lexer->buffer = (const uchar*)file_content;
+			lexer->buflen = file_content_len;
+			fsd_log_trace(( "content from file" ));
+		 }
+		else if( content )
+		 {
+			lexer->buffer = (const uchar*)content;
+			lexer->buflen = content_len;
+			fsd_log_trace(( "content from memory" ));
+		 }
+
+		if( lexer->buffer )
+		 {
+			lexer->pos = lexer->cline = lexer->buffer;
+			lexer->lineno = 1;
+
+			fsd_conf_parse( parser, lexer );
+			result = parser->result;
+		 }
+
+		if( parser->n_errors > 0 )
+		 {
+			fsd_exc_raise(
+					fsd_exc_new(
+							FSD_ERRNO_INTERNAL_ERROR,
+							fsd_explode( (const char*const*)parser->errors, '\n',
+								parser->n_errors ),
+							true
+							)
+					);
+		 }
+	 }
+	ELSE
+	 {
+		configuration = fsd_conf_dict_merge( configuration, result );
+		result = NULL;
+	 }
+	FINALLY
+	 {
+		if( parser )
+		 {
+			if( parser->errors )
+			 {
+				int i;
+				for( i=0;  i < parser->n_errors;  i++ )
+					fsd_free( parser->errors[i] );
+				fsd_free( parser->errors );
+			 }
+			fsd_free( parser );
+		 }
+		fsd_free( lexer );
+		fsd_free( file_content );
+		fsd_conf_dict_destroy( result );
+	 }
+	END_TRY
+
+	fsd_log_return(( "" ));
+	return configuration;
+}
+
+
+
+int
+fsd_conf_lex(
+		union YYSTYPE *lvalp, struct YYLTYPE *locp,
+		fsd_conf_lexer_t *lexer
+		)
+{
+	const uchar *c = lexer->pos;
+	const uchar *end = lexer->buffer + lexer->buflen;
+	const char *error = NULL;
+	int result;
+
+	while( c<end )
+		switch( *c )
+		 {
+			case '#':  /* a comment */
+				while( c<end && *c != '\n' )
+					c++;
+			case '\n':  /* no break */
+				lexer->lineno++;
+				lexer->cline = c+1;
+			case ' ':  case '\t':  case '\r':  /* no break */
+				c++;
+				break;
+			default:
+				goto token_begin;
+		 }
+
+token_begin:
+	locp->first_line = lexer->lineno;
+	locp->first_column = c - lexer->cline + 1;
+
+	if( c == end )
+		result = 0;
+	else
+		switch( *c )
+		 {
+			case ':':  case ',':  case '{':  case '}':
+				result = *c++;
+				break;
+
+			case '0':  case '1':  case '2':  case '3':  case '4':
+			case '5':  case '6':  case '7':  case '8':  case '9':
+			 {
+				int v = 0;
+				while( c < end  &&  '0' <= *c  &&  *c <= '9' )
+				 {
+					v *= 10;
+					v += *c - '0';
+					c++;
+				 }
+				lvalp->integer = v;
+				result = INTEGER;
+				break;
+			 }
+
+			case '"':  case '\'':
+			 {
+				uchar delimiter;
+				const uchar *begin;
+				delimiter = *c++;
+				begin = c;
+                                
+				while( c < end  &&  *c != delimiter )
+					c++;
+				if( c == end )
+				 {
+					error = "expected string delimiter but EOF found";
+					result = LEXER_ERROR;
+				 }
+				else
+				 {
+					lvalp->string = fsd_strndup( (const char*)begin, c-begin );
+					result = STRING;
+					c++;
+				 }
+				break;
+			 }
+
+			default:
+			 {
+				const uchar *begin = c;
+				while( c<end  &&  !isspace(*c) )
+					switch( *c )
+					 {
+						case ':':  case ',':  case '{':  case '}':
+							goto end_of_string;
+						default:
+							c++;
+							break;
+					 }
+			end_of_string:
+				lvalp->string = fsd_strndup( (const char*)begin, c-begin );
+				result = STRING;
+				break;
+			 }
+		 }
+
+	locp->last_line = lexer->lineno;
+	locp->last_column = c - lexer->cline;
+	if( locp->last_column < locp->first_column )
+		locp->last_column = locp->first_column;
+	lexer->pos = c;
+
+	if( error )
+		fsd_conf_error( locp, lexer->parser, lexer, error );
+
+	return result;
+}
+
+
+
+void
+fsd_conf_error(
+		struct YYLTYPE *locp,
+		fsd_conf_parser_t *parser, fsd_conf_lexer_t *lexer,
+		const char *fmt, ...
+		)
+{
+	char *volatile message = NULL;
+	va_list args;
+
+	TRY
+	 {
+		va_start( args, fmt );
+		message = fsd_vasprintf( fmt, args );
+		va_end( args );
+
+		fsd_realloc( parser->errors, parser->n_errors+1, char* );
+		parser->errors[ parser->n_errors ] = fsd_asprintf(
+				"%s:%d:%d: %s",
+				parser->lexer->filename, locp->first_line, locp->first_column,
+				message );
+		fsd_log_error(("Parser error: %s:%d:%d: %s", parser->lexer->filename, locp->first_line, locp->first_column, message ));
+		parser->n_errors ++;
+	 }
+	FINALLY
+	 { fsd_free( message ); }
+	END_TRY
+}
+
+
+
+fsd_conf_option_t *
+fsd_conf_option_create( fsd_conf_type_t type, void *value )
+{
+	fsd_conf_option_t *o = NULL;
+
+	fsd_malloc( o, fsd_conf_option_t );
+	o->type = type;
+	switch( type )
+	 {
+		case FSD_CONF_INTEGER:
+			o->val.integer = *(int*)value;
+			break;
+		case FSD_CONF_STRING:
+			o->val.string = (char*)value;
+			break;
+		case FSD_CONF_DICT:
+			o->val.dict = (fsd_conf_dict_t*)value;
+			break;
+		default:
+			fsd_assert(false);
+			break;
+	 }
+	return o;
+}
+
+
+void
+fsd_conf_option_destroy( fsd_conf_option_t *option )
+{
+	if( option == NULL )
+		return;
+	switch( option->type )
+	 {
+		case FSD_CONF_INTEGER:
+			break;
+		case FSD_CONF_STRING:
+			fsd_free( option->val.string );
+			break;
+		case FSD_CONF_DICT:
+			fsd_conf_dict_destroy( option->val.dict );
+			break;
+		default:
+			fsd_assert( false );
+	 }
+	fsd_free( option );
+}
+
+
+fsd_conf_option_t *
+fsd_conf_option_merge( fsd_conf_option_t *lhs, fsd_conf_option_t *rhs )
+{
+	if( lhs->type == rhs->type  &&  rhs->type == FSD_CONF_DICT )
+	 {
+		lhs->val.dict = fsd_conf_dict_merge( lhs->val.dict, rhs->val.dict );
+		fsd_free( rhs );
+		return lhs;
+	 }
+	else
+	 {
+		fsd_conf_option_destroy( lhs );
+		return rhs;
+	 }
+}
+
+
+void
+fsd_conf_option_dump( fsd_conf_option_t *option )
+{
+	if( option == NULL )
+	 {
+		printf( "(null)" );
+		return;
+	 }
+	switch( option->type )
+	 {
+		case FSD_CONF_STRING:
+			printf( "\"%s\"", option->val.string );
+			break;
+		case FSD_CONF_INTEGER:
+			printf( "%d", option->val.integer );
+			break;
+		case FSD_CONF_DICT:
+			fsd_conf_dict_dump( option->val.dict );
+			break;
+	 }
+}
+
+
+
+struct fsd_conf_dict_s {
+	fsd_conf_dict_t *next;
+	char *key;
+	fsd_conf_option_t *value;
+};
+
+
+fsd_conf_dict_t *
+fsd_conf_dict_create(void)
+{
+	fsd_conf_dict_t *dict = NULL;
+	fsd_malloc( dict, fsd_conf_dict_t );
+	dict->next = NULL;
+	dict->key = NULL;
+	dict->value = NULL;
+	return dict;
+}
+
+
+void
+fsd_conf_dict_destroy( fsd_conf_dict_t *dict )
+{
+	fsd_conf_dict_t *i;
+	for( i = dict;  i != NULL;  )
+	 {
+		fsd_conf_dict_t *c = i;
+		i = i->next;
+		fsd_free( c->key );
+		fsd_conf_option_destroy( c->value );
+		fsd_free( c );
+	 }
+}
+
+
+fsd_conf_option_t *
+fsd_conf_dict_get(
+		fsd_conf_dict_t *dict, const char *key )
+{
+	fsd_conf_dict_t *i;
+	if( dict == NULL  ||  key == NULL )
+		return NULL;
+	for( i = dict->next;  i != NULL;  i = i->next )
+	 {
+		if( !strcmp( i->key, key ) )
+			return i->value;
+	 }
+	return NULL;
+}
+
+
+void
+fsd_conf_dict_set(
+		fsd_conf_dict_t *dict, const char *key, fsd_conf_option_t *value
+		)
+{
+	fsd_conf_dict_t *i;
+	for( i = dict->next;  i != NULL;  i = i->next )
+	 {
+		if( !strcmp( i->key, key ) )
+			break;
+	 }
+
+	if( i != NULL )
+	 {
+		fsd_conf_option_destroy( i->value );
+		i->value = value;
+	 }
+	else
+	 {
+		fsd_conf_dict_t* volatile n = NULL;
+		TRY
+		 {
+			fsd_malloc( n, fsd_conf_dict_t );
+			n->key = fsd_strdup( key );
+			n->value = value;
+		 }
+		EXCEPT_DEFAULT
+		 {
+			fsd_free( n );
+			fsd_exc_reraise();
+		 }
+		ELSE
+		 {
+			n->next = dict->next;
+			dict->next = n;
+		 }
+		END_TRY
+	 }
+}
+
+
+fsd_conf_dict_t *
+fsd_conf_dict_merge( fsd_conf_dict_t *lhs, fsd_conf_dict_t *rhs )
+{
+	fsd_conf_dict_t *i, *j;
+
+	if( lhs == NULL )
+		return rhs;
+
+	if( rhs == NULL )
+		return lhs;
+
+	for( j = rhs->next;  j != NULL;  )
+	 {
+		fsd_conf_dict_t *r = j;
+		j = j->next;
+
+		for( i = lhs->next;  i != NULL;  i = i->next )
+			if( !strcmp( i->key, r->key ) )
+				break;
+
+		if( i != NULL )
+		 {
+			i->value = fsd_conf_option_merge( i->value, r->value );
+			fsd_free( r->key );
+			fsd_free( r );
+		 }
+		else
+		 {
+			r->next = lhs->next;
+			lhs->next = r;
+		 }
+	 }
+
+	fsd_free( rhs );
+	return lhs;
+}
+
+
+void
+fsd_conf_dict_dump( fsd_conf_dict_t *dict )
+{
+	fsd_conf_dict_t *i;
+
+	if( dict == NULL )
+	 {
+		printf( "(null)" );
+		return;
+	 }
+	printf( "{" );
+	for( i=dict->next;  i;  i = i->next )
+	 {
+		if( i != dict->next )
+			printf( "," );
+		printf( " %s=", i->key );
+		fsd_conf_option_dump( i->value );
+	 }
+	printf( " }" );
+}
+
+
+fsd_conf_option_t *
+fsd_conf_option_create_noraise( fsd_conf_type_t type, void *value )
+{
+	fsd_conf_option_t *volatile result = NULL;
+	TRY{ result = fsd_conf_option_create( type, value ); }
+	EXCEPT_DEFAULT{}
+	END_TRY
+	return result;
+}
+
+fsd_conf_dict_t *
+fsd_conf_dict_create_noraise(void)
+{
+	fsd_conf_dict_t *volatile result = NULL;
+	TRY{ result = fsd_conf_dict_create(); }
+	EXCEPT_DEFAULT{}
+	END_TRY
+	return result;
+}
+
+int
+fsd_conf_dict_set_noraise(
+		fsd_conf_dict_t *dict, const char *key, fsd_conf_option_t *value )
+{
+	volatile int rc = FSD_ERRNO_SUCCESS;
+	TRY{ fsd_conf_dict_set( dict, key, value ); }
+	EXCEPT_DEFAULT
+	 {
+		const fsd_exc_t *e = fsd_exc_get();
+		rc = e->code(e);
+	 }
+	END_TRY
+	return rc;
+}
+
Index: trunk/drmaa_utils/drmaa_utils/logging.c
===================================================================
--- trunk/drmaa_utils/drmaa_utils/logging.c	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/logging.c	(revision 1)
@@ -0,0 +1,250 @@
+/* $Id: logging.c 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <sys/time.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <unistd.h>
+#ifdef HAVE_EXECINFO_H
+#	include <execinfo.h>
+#endif
+
+#include <drmaa_utils/common.h>
+#include <drmaa_utils/logging.h>
+#include <drmaa_utils/lookup3.h>
+#include <drmaa_utils/thread.h>
+
+#ifndef lint
+static char rcsid[]
+#	ifdef __GNUC__
+		__attribute__ ((unused))
+#	endif
+	= "$Id: logging.c 2 2009-10-12 09:51:22Z mamonski $";
+#endif
+
+
+static int fsd_logging_output = 2;
+
+fsd_verbose_level_t fsd_verbose_level =
+#ifdef DEBUGGING
+	FSD_LOG_TRACE
+#else
+	FSD_LOG_WARNING
+#endif
+;
+
+static struct timeval fsd_logging_start = {0, 0};
+
+
+void
+fsd_set_verbosity_level( fsd_verbose_level_t level )
+{
+	fsd_verbose_level = level;
+}
+
+void
+fsd_set_logging_fd( int fd )
+{
+	fsd_logging_output = fd;
+}
+
+
+void
+fsd_color( char *output, size_t len, int n )
+{
+	uint32_t k = n;
+	k = hashword( &k, 1, 0 );
+	k %= 12;
+	snprintf( output, len, "\033[0;%d;%dm", k>=6, 31+k%6 );
+}
+
+
+char
+fsd_log_level_char( int level )
+{
+	switch( level )
+	 {
+		case FSD_LOG_TRACE:    return 't';
+		case FSD_LOG_DEBUG:    return 'd';
+		case FSD_LOG_INFO:     return 'I';
+		case FSD_LOG_WARNING:  return 'W';
+		case FSD_LOG_ERROR:    return 'E';
+		case FSD_LOG_FATAL:    return 'F';
+		default:               return '?';
+	 }
+}
+
+
+void
+_fsd_log( int level, const char *file, const char *function,
+		int kind, char *message )
+{
+	const bool color = false;
+	char colorbeg[16];
+	const char *colorend;
+	int tid;
+	long int seconds, microseconds;
+	const char *prefix;
+	const char *p;
+
+	if( level < (int)fsd_verbose_level )
+		return;
+
+	if( message == NULL )
+		return;
+
+	tid = fsd_thread_id();
+	if( color )
+	 {
+		fsd_color( colorbeg, sizeof(colorbeg), tid );
+		colorend = "\033[0m";
+	 }
+	else
+	 {
+		colorbeg[0] = '\0';
+		colorend = "";
+	 }
+
+	 {
+		struct timeval tv;
+		gettimeofday( &tv, NULL );
+		seconds = tv.tv_sec;
+		microseconds = tv.tv_usec;
+	 }
+	if( fsd_logging_start.tv_sec == 0 )
+	 {
+		time_t t;
+		struct tm utc;
+		char rep[32];
+		fsd_logging_start.tv_sec = seconds;
+		fsd_logging_start.tv_usec = microseconds;
+		t = seconds;
+		gmtime_r( &t, &utc );
+		strftime( rep, sizeof(rep), "%Y-%m-%d %H:%M:%S", &utc );
+		fsd_log_debug(( "logging started at: %s.%02ld Z",
+					rep, microseconds/10000 ));
+	 }
+	if( microseconds < fsd_logging_start.tv_usec )
+	 {
+		seconds --;
+		microseconds += 1000000;
+	 }
+	seconds -= fsd_logging_start.tv_sec;
+	microseconds -= fsd_logging_start.tv_usec;
+
+	switch( kind )
+	 {
+		case _FSD_LOG_ENTER:   prefix = "->";  break;
+		case _FSD_LOG_RETURN:  prefix = "<-";  break;
+		default:
+			prefix = " *";
+			function = "";
+			break;
+	 }
+
+	p = message;
+	do {
+		if( *p == '\n' )
+		 {
+			prefix = " |";
+			function = "";
+			p++;
+		 }
+		else
+		 {
+			const char *end;
+			char *line = NULL;
+			int rc;
+			end = strchr( p, '\n' );
+			if( end == NULL )
+				end = p + strlen(p);
+			rc = asprintf( &line, "%c #%s%04x%s [%6ld.%02ld] %s %s%.*s\n",
+					fsd_log_level_char(level), colorbeg, tid, colorend,
+					seconds, microseconds/10000, prefix, function, (int)(end-p), p
+					);
+			if( rc != -1 )
+				write( fsd_logging_output, line, strlen(line) );
+			else
+				return;
+			free( line );
+			p = end;
+		 }
+	} while( *p != '\0' );
+
+	free( message );
+}
+
+
+void
+fsd_log_fmt( int level, const char *fmt, ... )
+{
+	va_list args;
+	va_start( args, fmt );
+	fsd_log_fmtv( level, fmt, args );
+	va_end( args );
+}
+
+
+void
+fsd_log_fmtv( int level, const char *fmt, va_list args )
+{
+	_fsd_log( level, NULL, NULL, _FSD_LOG_MSG, fsd_vasprintf(fmt, args) );
+}
+
+
+#if defined(__GNUC__) && defined(HAVE_EXECINFO_H)
+#define MAX_STACKTRACE 128
+void
+fsd_log_stacktrace( int skip, int limit )
+{
+	void **ptr_buf = NULL;
+	const char **symbols = NULL;
+	int i, n;
+
+	if( limit == 0 )
+		limit = 128;
+	skip++; /* without fsd_log_stacktrace() frame */
+	n = skip + limit;
+
+	ptr_buf = (void**)calloc( n, sizeof(void*) );
+	if( ptr_buf == NULL )
+		return;
+	n = backtrace( ptr_buf, n );
+	symbols = (const char**)backtrace_symbols( ptr_buf, n );
+	if( symbols != NULL )
+	 {
+		fsd_log_debug(( "Stacktrace (most recent call last):" ));
+		for( i = n-skip;  i >= 0;  i-- )
+			fsd_log_debug(( "\n  %s", symbols[i] ));
+		free( symbols );
+	 }
+}
+#else
+void fsd_log_stacktrace( int skip, int limit ) {}
+#endif
+
+
+
Index: trunk/drmaa_utils/drmaa_utils/session.h
===================================================================
--- trunk/drmaa_utils/drmaa_utils/session.h	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/session.h	(revision 1)
@@ -0,0 +1,331 @@
+/* $Id: session.h 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+/**
+ * @file session.h
+ * DRMAA session.
+ */
+
+#ifndef __DRMAA_UTILS__SESSION_H
+#define __DRMAA_UTILS__SESSION_H
+
+#include <sys/time.h>
+
+#include <drmaa_utils/common.h>
+#include <drmaa_utils/thread.h>
+
+/** Creates new DRMAA session. */
+fsd_drmaa_session_t *
+fsd_drmaa_session_new( const char *contact );
+
+/**
+ * Get current (global) DRMAA session
+ * and increase it's reference count.
+ */
+fsd_drmaa_session_t *
+fsd_drmaa_session_get(void);
+
+/**
+ * An action to be taken when job is missing from queue.
+ */
+typedef enum {
+	/**
+	 * Always raise #FSD_ERRNO_INTERNAL_ERROR (one per job)
+	 * in drmaa_wait() or drmaa_synchronize()
+	 * when job disappearance is spotted.
+	 */
+	FSD_REVEAL_MISSING_JOBS,
+	/**
+	 * Treat missing jobs as terminated with status
+	 * depending on last known state and action (drmaa_control()).
+	 */
+	FSD_IGNORE_MISSING_JOBS,
+	/**
+	 * Treat missing jobs as terminated
+	 * but only before they enter into running state.
+	 */
+	FSD_IGNORE_QUEUED_MISSING_JOBS
+} fsd_missing_jobs_behaviour_t;
+
+
+/** DRMAA session data. */
+struct fsd_drmaa_session_s {
+	/** Release one reference to DRMAA session. */
+	void (*
+	release)( fsd_drmaa_session_t *self );
+
+	/**
+	 * Destroy session after ensuring no other references to it are held.
+	 *
+	 * May block until reference count decreases to 1.
+	 * May return before actual session destruction if another thread
+	 * have already taken responsibility for freeing session.
+	 */
+	void (*
+	destroy)(
+			fsd_drmaa_session_t *self );
+
+	/**
+	 * Destroy session without waiting for releasing references.
+	 */
+	void (*
+	destroy_nowait)( fsd_drmaa_session_t *self );
+
+
+	/** Implements drmaa_run_job(). */
+	char* (*
+	run_job)(
+			fsd_drmaa_session_t *self,
+			const fsd_template_t *jt
+			);
+
+	/** Implements drmaa_run_bulk_jobs(). */
+	fsd_iter_t* (*
+	run_bulk)(
+			fsd_drmaa_session_t *self,
+			const fsd_template_t *jt,
+			int start, int end, int incr
+			);
+
+	/** Implements drmaa_control(). */
+	void (*
+	control_job)(
+			fsd_drmaa_session_t *self,
+			const char *job_id, int action
+			);
+
+	/** Implements drmaa_job_ps(). */
+	void (*
+	job_ps)(
+			fsd_drmaa_session_t *self,
+			const char *job_id, int *remote_ps
+			);
+
+	/** Implements drmaa_synchronize(). */
+	void (*
+	synchronize)(
+			fsd_drmaa_session_t *self,
+			const char **input_job_ids, const struct timespec *timeout,
+			bool dispose
+			);
+
+	/**
+	 * Implements drmaa_wait() call.
+	 * @param self     DRMAA session.
+	 * @param job_id   Job identifer to wait for or #DRMAA_JOB_IDS_SESSION_ANY
+	 * @param timeout  Timeout after which call shall raise
+	 *   #FSD_DRMAA_ERRNO_EXIT_TIMEOUT if job not terminated or \c NULL.
+	 * @param status   Terminated job status (output only).
+	 * @param rusage   Job resource usage (output only).
+	 * @see drmaa_wait()
+	 * @see #wait_for_single_job  #wait_for_any_job
+	 */
+	char* (*
+	wait)(
+			fsd_drmaa_session_t *self,
+			const char *job_id, const struct timespec *timeout,
+			int *status, fsd_iter_t **rusage
+			);
+
+	/**
+	 * Construct new job object.
+	 * @return Reference to newly created job.
+	 */
+	fsd_job_t* (*
+	new_job)( fsd_drmaa_session_t *self, const char *job_id );
+
+	char* (*
+	run_impl)(
+			fsd_drmaa_session_t *self,
+			const fsd_template_t *jt, int bulk_incr
+			);
+
+	/**
+	 * Wait until given job terminates (either successfuly or not).
+	 * @param self     DRMAA session.
+	 * @param job_id   Identifier of job to wait for.
+	 * @param timeout  If not \c NULL and job does not terminate
+	 *   in given amount of time function returns and
+	 *   #FSD_DRMAA_ERRNO_EXIT_TIMEOUT is raised.
+	 * @param status   If not \c NULL job status code is stored here.
+	 * @param rusage   If not \c NULL list of used resources is returned.
+	 * @param dispose  If \c true job information is removed from session
+	 *   at the end of call and further accesses to this job_id will
+	 *   raise #FSD_DRMAA_ERRNO_INVALID_JOB.  Otherwise job data is held.
+	 * @see #wait_for_any_job #wait
+	 */
+	void (*
+	wait_for_single_job)(
+			fsd_drmaa_session_t *self,
+			const char *job_id, const struct timespec *timeout,
+			int *status, fsd_iter_t **rusage, bool dispose
+			);
+
+	/**
+	 * Wait until and job left in session terminates.
+	 * @return  Identifier of waited job.
+	 *   Freeing responsobility is left to the callee.
+	 * @see #wait_for_single_job #wait
+	 */
+	char* (*
+	wait_for_any_job)(
+			fsd_drmaa_session_t *self,
+			const struct timespec *timeout,
+			int *status, fsd_iter_t **rusage,
+			bool dispose
+			);
+
+	void (*
+	wait_for_job_status_change)(
+			fsd_drmaa_session_t *self,
+			fsd_cond_t *wait_condition,
+			fsd_mutex_t *mutex,
+			const struct timespec *timeout
+			);
+
+	void* (*
+	wait_thread)( fsd_drmaa_session_t *self );
+
+	void (*
+	stop_wait_thread)( fsd_drmaa_session_t *self );
+
+	/**
+	 * Make status of all jobs held in session up to date.
+	 */
+	void (*
+	update_all_jobs_status)( fsd_drmaa_session_t *self );
+
+	/** Return list of all jobs within session. */
+	char** (*
+	get_submited_job_ids)(
+			fsd_drmaa_session_t *self
+			);
+
+	/**
+	 * Get job with given identifier.
+	 * @return New reference to job or \c NULL
+	 *   if no job found.
+	 */
+	fsd_job_t* (*
+	get_job)(
+			fsd_drmaa_session_t *self, const char *job_id
+			);
+
+	/**
+	 * Tries to load configuration from following locations in order
+	 * (configuration settings from later locations override
+	 * those from earlier):
+	 * /etc/basename.conf, ~/.basename.conf, $basename_CONF.
+	 */
+	void (*
+	load_configuration)(
+			fsd_drmaa_session_t *self, const char *basename
+			);
+
+	void (*
+	read_configuration)(
+			fsd_drmaa_session_t *self,
+			const char *filename, bool must_exist,
+			const char *configuration, size_t config_len
+			);
+
+	void (*
+	apply_configuration)(
+			fsd_drmaa_session_t *self
+			);
+
+	/** Reference counter. */
+	int ref_cnt;
+
+	/**
+	 * Whether #destroy was called and waits for releasing
+	 * references.  If set pending #wait calls shall
+	 * return with #FSD_DRMAA_ERRNO_NO_ACTIVE_SESSION error.
+	 */
+	bool destroy_requested;
+
+	/**
+	 * Copy of contact string passed to drmaa_init()
+	 * or default contact if drmaa_init() was called with \c NULL.
+	 */
+	char *contact;
+
+	/**
+	 * Jobs submitted within this DRMAA session
+	 * and not disposed yet.
+	 */
+	fsd_job_set_t *jobs;
+
+	/** DRMAA configuration. */
+	fsd_conf_dict_t *configuration;
+
+	/** Queue pooling delay (time delta). */
+	struct timespec pool_delay;
+
+	/**
+	 * Cache job state for number of seconds.
+	 * If positive drmaa_job_ps() returns remembered state without
+	 * communicating with DRM for \a cache_job_state seconds since last
+	 * update.
+	 */
+	int cache_job_state;
+
+	/** Whether to wait for jobs in separate thread. */
+	bool enable_wait_thread;
+
+	/**
+	 * Configuration dictionary which maps
+	 * job categories to native specification.
+	 */
+	fsd_conf_dict_t *job_categories;
+
+	/**
+	 * How to behave when submitted job disappears from DRM queue.
+	 */
+	fsd_missing_jobs_behaviour_t missing_jobs;
+
+	fsd_mutex_t mutex; /**< Mutex for accessing session data. */
+	fsd_cond_t wait_condition;  /**< Conditional for drmaa_wait() */
+	fsd_cond_t destroy_condition;  /**< Conditional for ref_cnt==1 */
+
+	/**
+	 * Mutex for accessing connection to DRM.
+	 *
+	 * To prevent deadlocks #mutex should be acquired first
+	 * when both session data and DRM connection are needed.
+	 */
+	fsd_mutex_t drm_connection_mutex;
+
+	fsd_thread_t wait_thread_handle;
+	bool wait_thread_started;
+	bool wait_thread_run_flag;
+};
+
+
+typedef struct fsd_drmaa_ctx_s {
+	fsd_drmaa_session_t *session;
+	fsd_mutex_t session_mutex;
+	
+} fsd_drmaa_ctx_t;
+
+
+extern fsd_drmaa_ctx_t fsd_drmaa_ctx;
+
+#endif /* __DRMAA_UTILS__SESSION_H */
+
Index: trunk/drmaa_utils/drmaa_utils/Makefile.am
===================================================================
--- trunk/drmaa_utils/drmaa_utils/Makefile.am	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/Makefile.am	(revision 1)
@@ -0,0 +1,82 @@
+# $Id: Makefile.am 1656 2008-11-18 17:11:58Z lukasz $
+#
+# FedStage DRMAA utilities library
+# Copyright (C) 2006-2008  FedStage Systems
+#
+# 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/>.
+#
+
+GPERF = @GPERF@
+GPERFFLAGS = --readonly-tables
+RAGEL = @RAGEL@
+RAGELFLAGS =
+
+YLWRAP = $(top_srcdir)/m4/bison_ylwrap.sh
+AM_YFLAGS = -d
+
+noinst_LTLIBRARIES = libdrmaa_utils.la
+
+libdrmaa_utils_la_SOURCES = \
+ compat.c compat.h \
+ common.h \
+ conf.c conf.h \
+ conf_impl.h conf_tab.y \
+ datetime.c datetime.h \
+ datetime_impl.h datetime_tab.y \
+ drmaa_attrib.c drmaa_attrib.h \
+ environ.c environ.h \
+ exception.c exception.h \
+ iter.c iter.h \
+ fsd_job.c job.h \
+ logging.c logging.h \
+ lookup3.c lookup3.h \
+ fsd_session.c session.h \
+ template.c template.h \
+ timedelta.c \
+ thread.c thread.h \
+ fsd_util.c util.h \
+ drmaa_util.c drmaa_util.h \
+ xmalloc.c xmalloc.h \
+ drmaa_base.c drmaa_base.h
+
+libdrmaa_utils_la_LDFLAGS = -static
+libdrmaa_utils_la_CPPFLAGS = -fPIC
+
+if GCC 
+if !DEVELOPER_MODE
+# allow `%m` in printf-like format string
+# Bison and Ragel generated code have many unused symbols
+libdrmaa_utils_la_CPPFLAGS +=  -Wno-unused
+endif
+endif
+
+include_HEADERS = drmaa.h
+
+BUILT_SOURCES = \
+ datetime_tab.c datetime_tab.h \
+ conf_tab.c conf_tab.h \
+ drmaa_attrib.c \
+ timedelta.c
+
+EXTRA_DIST = drmaa_attrib.gperf timedelta.rl
+
+if DEVELOPER_MODE
+CLEANFILES = $(BUILT_SOURCES)
+endif
+
+drmaa_attrib.c: drmaa_attrib.gperf
+	$(GPERF) $(GPERFFLAGS) --output-file=drmaa_attrib.c drmaa_attrib.gperf
+timedelta.c: timedelta.rl
+	$(RAGEL) $(RAGELFLAGS) -o timedelta.c timedelta.rl
+
Index: trunk/drmaa_utils/drmaa_utils/drmaa.h
===================================================================
--- trunk/drmaa_utils/drmaa_utils/drmaa.h	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/drmaa.h	(revision 1)
@@ -0,0 +1,568 @@
+/* $Id: drmaa.h 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+/*
+ * Documentation taken from:
+ *
+ *  Distributed Resource Management Application API C Bindings v1.0
+ *
+ *  Copyright (C) Global Grid Forum (2003). All Rights Reserved.
+ *
+ *  This document and translations of it may be copied and furnished to
+ *  others, and derivative works that comment on or otherwise explain it
+ *  or assist in its implementation may be prepared, copied, published
+ *  and distributed, in whole or in part, without restriction of any kind,
+ *  provided that the above copyright notice and this paragraph are included
+ *  on all such copies and derivative works.  However, this document itself
+ *  may not be modified in any way, such as by removing the copyright notice
+ *  or references to the GGF or other organizations, except as needed for the
+ *  purpose of developing Grid Recommendations in which case the procedures
+ *  for copyrights defined in the GGF Document process must be followed,
+ *  or as required to translate it into languages other than English.
+ *
+ *  The limited permissions granted above are perpetual and will not be
+ *  revoked by the GGF or its successors or assigns.
+ *  This document and the information contained herein is provided on an
+ *  "AS IS" basis and THE GLOBAL GRID FORUM DISCLAIMS ALL WARRANTIES, EXPRESS
+ *  OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE
+ *  INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES
+ *  OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+ */
+
+/**
+ * @file drmaa.h
+ * DRMAA interface functions.
+ * @author Åukasz CieÅnik <lukasz.ciesnik@fedstage.com>
+ */
+
+#ifndef __DRMAA_H
+#define __DRMAA_H
+
+#include <stddef.h>
+#include <stdio.h>
+
+/** @defgroup drmaa_jobt Job template operations. */
+
+/** @defgroup drmaa  DRMAA interface. */
+/* @{ */
+
+typedef struct drmaa_job_template_s  drmaa_job_template_t;
+typedef struct drmaa_attr_names_s    drmaa_attr_names_t;
+typedef struct drmaa_attr_values_s   drmaa_attr_values_t;
+typedef struct drmaa_job_ids_s       drmaa_job_ids_t;
+
+#define DRMAA_ATTR_BUFFER         1024
+#define DRMAA_CONTACT_BUFFER      1024
+#define DRMAA_DRM_SYSTEM_BUFFER   1024
+#define DRMAA_DRMAA_IMPL_BUFFER   1024
+#define DRMAA_ERROR_STRING_BUFFER 4096
+#define DRMAA_JOBNAME_BUFFER       128
+#define DRMAA_SIGNAL_BUFFER         32
+
+#define DRMAA_TIMEOUT_NO_WAIT            0
+#define DRMAA_TIMEOUT_WAIT_FOREVER       -1
+#define DRMAA_PS_UNDETERMINED            0x00
+#define DRMAA_PS_QUEUED_ACTIVE           0x10
+#define DRMAA_PS_SYSTEM_ON_HOLD          0x11
+#define DRMAA_PS_USER_ON_HOLD            0x12
+#define DRMAA_PS_USER_SYSTEM_ON_HOLD     0x13
+#define DRMAA_PS_RUNNING                 0x20
+#define DRMAA_PS_SYSTEM_SUSPENDED        0x21
+#define DRMAA_PS_USER_SUSPENDED          0x22
+#define DRMAA_PS_USER_SYSTEM_SUSPENDED   0x23
+#define DRMAA_PS_DONE                    0x30
+#define DRMAA_PS_FAILED                  0x40
+#define DRMAA_CONTROL_SUSPEND            0
+#define DRMAA_CONTROL_RESUME             1
+#define DRMAA_CONTROL_HOLD               2
+#define DRMAA_CONTROL_RELEASE            3
+#define DRMAA_CONTROL_TERMINATE          4
+#define DRMAA_JOB_IDS_SESSION_ALL        "DRMAA_JOB_IDS_SESSION_ALL"
+#define DRMAA_JOB_IDS_SESSION_ANY        "DRMAA_JOB_IDS_SESSION_ANY"
+
+#define DRMAA_BLOCK_EMAIL             "drmaa_block_email"
+#define DRMAA_DEADLINE_TIME           "drmaa_deadline_time"
+#define DRMAA_DURATION_HLIMIT         "drmaa_duration_hlimit"
+#define DRMAA_DURATION_SLIMIT         "drmaa_duration_slimit"
+#define DRMAA_ERROR_PATH              "drmaa_error_path"
+#define DRMAA_INPUT_PATH              "drmaa_input_path"
+#define DRMAA_JOB_CATEGORY            "drmaa_job_category"
+#define DRMAA_JOB_NAME                "drmaa_job_name"
+#define DRMAA_JOIN_FILES              "drmaa_join_files"
+#define DRMAA_JS_STATE                "drmaa_js_state"
+#define DRMAA_NATIVE_SPECIFICATION    "drmaa_native_specification"
+#define DRMAA_OUTPUT_PATH             "drmaa_output_path"
+#define DRMAA_REMOTE_COMMAND          "drmaa_remote_command"
+#define DRMAA_START_TIME              "drmaa_start_time"
+#define DRMAA_TRANSFER_FILES          "drmaa_transfer_files"
+#define DRMAA_V_ARGV                  "drmaa_v_argv"
+#define DRMAA_V_EMAIL                 "drmaa_v_email"
+#define DRMAA_V_ENV                   "drmaa_v_env"
+#define DRMAA_WCT_HLIMIT              "drmaa_wct_hlimit"
+#define DRMAA_WCT_SLIMIT              "drmaa_wct_slimit"
+#define DRMAA_WD                      "drmaa_wd"
+
+#define DRMAA_SUBMISSION_STATE_ACTIVE "drmaa_active"
+#define DRMAA_SUBMISSION_STATE_HOLD   "drmaa_hold"
+#define DRMAA_PLACEHOLDER_HD          "$drmaa_hd_ph$"
+#define DRMAA_PLACEHOLDER_WD          "$drmaa_wd_ph$"
+#define DRMAA_PLACEHOLDER_INCR        "$drmaa_incr_ph$"
+
+#define DRMAA_ERRNO_SUCCESS                               0
+#define DRMAA_ERRNO_INTERNAL_ERROR                        1
+#define DRMAA_ERRNO_DRM_COMMUNICATION_FAILURE             2
+#define DRMAA_ERRNO_AUTH_FAILURE                          3
+#define DRMAA_ERRNO_INVALID_ARGUMENT                      4
+#define DRMAA_ERRNO_NO_ACTIVE_SESSION                     5
+#define DRMAA_ERRNO_NO_MEMORY                             6
+#define DRMAA_ERRNO_INVALID_CONTACT_STRING                7
+#define DRMAA_ERRNO_DEFAULT_CONTACT_STRING_ERROR          8
+#define DRMAA_ERRNO_NO_DEFAULT_CONTACT_STRING_SELECTED    9
+#define DRMAA_ERRNO_DRMS_INIT_FAILED                     10
+#define DRMAA_ERRNO_ALREADY_ACTIVE_SESSION               11
+#define DRMAA_ERRNO_DRMS_EXIT_ERROR                      12
+#define DRMAA_ERRNO_INVALID_ATTRIBUTE_FORMAT             13
+#define DRMAA_ERRNO_INVALID_ATTRIBUTE_VALUE              14
+#define DRMAA_ERRNO_CONFLICTING_ATTRIBUTE_VALUES         15
+#define DRMAA_ERRNO_TRY_LATER                            16
+#define DRMAA_ERRNO_DENIED_BY_DRM                        17
+#define DRMAA_ERRNO_INVALID_JOB                          18
+#define DRMAA_ERRNO_RESUME_INCONSISTENT_STATE            19
+#define DRMAA_ERRNO_SUSPEND_INCONSISTENT_STATE           20
+#define DRMAA_ERRNO_HOLD_INCONSISTENT_STATE              21
+#define DRMAA_ERRNO_RELEASE_INCONSISTENT_STATE           22
+#define DRMAA_ERRNO_EXIT_TIMEOUT                         23
+#define DRMAA_ERRNO_NO_RUSAGE                            24
+#define DRMAA_ERRNO_NO_MORE_ELEMENTS                     25
+
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+
+/**
+ * The drmaa_init() function SHALL initialize DRMAA library and create
+ * a new DRMAA session, using the contact parameter, if provided, to
+ * determine to which DRMS to connect.  This function MUST be called
+ * before any other DRMAA function, except for drmaa_get_DRM_system(),
+ * drmaa_get_DRMAA_implementation(), drmaa_get_contact(), and
+ * drmaa_strerror().  If @a contact is @c NULL, the default DRM system
+ * SHALL be used, provided there is only one DRMAA implementation
+ * in the provided binary module.  When there is more than one DRMAA
+ * implementation in the binary module, drmaa_init() SHALL return
+ * the DRMAA_ERRNO_NO_DEFAULT_CONTACT_STRING_SELECTED error code.
+ * The drmaa_init() function SHOULD be called by only one of the threads.
+ * The main thread is RECOMMENDED.  A call by another thread SHALL return
+ * the DRMAA_ERRNO_ALREADY_ACTIVE_SESSION error code.
+ */
+int drmaa_init(
+	const char *contact,
+	char *error_diagnosis, size_t error_diag_len
+	);
+
+/**
+ * The drmaa_exit() function SHALL disengage from DRMAA library and
+ * allow the DRMAA library to perform any necessary internal cleanup.
+ * This routine SHALL end the current DRMAA session but SHALL NOT
+ * affect any jobs (e.g, queued and running jobs SHALL remain queued and
+ * running).  drmaa_exit() SHOULD be called by only one of the threads.
+ * The first call to call drmaa_exit() by a thread will operate normally.
+ * All other calls from the same and other threads SHALL fail, returning
+ * a DRMAA_ERRNO_NO_ACTIVE_SESSION error code.
+ */
+int drmaa_exit( char *error_diagnosis, size_t error_diag_len );
+
+
+
+/**
+ * The function drmaa_allocate_job_template() SHALL allocate a new job
+ * template, returned in @a jt.  This template is used to describe the
+ * job to be submitted.  This description is accomplished by setting the
+ * desired scalar and vector attributes to their appropriate values. This
+ * template is then used in the job submission process.
+ * @addtogroup drmaa_jobt
+ */
+int drmaa_allocate_job_template(
+	drmaa_job_template_t **jt,
+	char *error_diagnosis, size_t error_diag_len
+	);
+
+/**
+ * The function drmaa_delete_job_template() SHALL free the job template
+ * pointed to by @a jt.
+ * @addtogroup drmaa_jobt
+ */
+int drmaa_delete_job_template(
+	drmaa_job_template_t *jt,
+	char *error_diagnosis, size_t error_diag_len
+	);
+
+/**
+ * The function drmaa_set_attribute() SHALL set the value of the scalar
+ * attribute, @a name, in the job template, @a jt, to the value, @a value.
+ * @addtogroup drmaa_jobt
+ */
+int drmaa_set_attribute(
+	drmaa_job_template_t *jt,
+	const char *name, const char *value,
+	char *error_diagnosis, size_t error_diag_len
+	);
+
+/**
+ * The function drmaa_get_attribute() SHALL fill the @a value buffer with
+ * up to @a value_len characters of the scalar attribute, @a name's, value
+ * in the given job template.
+ * @addtogroup drmaa_jobt
+ */
+int drmaa_get_attribute(
+	drmaa_job_template_t *jt,
+	const char *name, char *value, size_t value_len,
+	char *error_diagnosis, size_t error_diag_len
+	);
+
+/**
+ * The function drmaa_set_vector_attribute() SHALL set the vector attribute,
+ * @a name, in the job template, @a jt, to the value(s), @a value.  The DRMAA
+ * implementation MUST accept value values that are arrays of one or more
+ * strings terminated by a @c NULL entry.
+ * @addtogroup drmaa_jobt
+ */
+int drmaa_set_vector_attribute(
+	drmaa_job_template_t *jt,
+	const char *name, const char *value[],
+	char *error_diagnosis, size_t error_diag_len
+	);
+
+/**
+ * The function drmaa_get_vector_attribute() SHALL store in @a values an
+ * opaque values string vector containing the values of the vector attribute,
+ * @a name's, value in the given job template.
+ * @addtogroup drmaa_jobt
+ */
+int drmaa_get_vector_attribute(
+	drmaa_job_template_t *jt,
+	const char *name, drmaa_attr_values_t **values,
+	char *error_diagnosis, size_t error_diag_len
+	);
+
+
+
+/**
+ * The function drmaa_get_attribute_names() SHALL return the set of supported
+ * scalar attribute names in an opaque names string vector stored in
+ * @a values.  This vector SHALL include all required scalar attributes, all
+ * supported optional scalar attributes, all DRM-specific scalar attributes,
+ * and no unsupported optional attributes.
+ */
+int drmaa_get_attribute_names(
+	drmaa_attr_names_t **values,
+	char *error_diagnosis, size_t error_diag_len
+	);
+
+/**
+ * The function drmaa_get_vector_attribute_names() SHALL return the set
+ * of supported vector attribute names in an opaque names string vector
+ * stored in @a values.  This vector SHALL include all required vector
+ * attributes, all supported optional vector attributes, all DRM-specific
+ * vector attributes, and no unsupported optional attributes.
+ */
+int drmaa_get_vector_attribute_names(
+	drmaa_attr_names_t **values,
+	char *error_diagnosis, size_t error_diag_len
+	);
+
+/**
+ * @defgroup drmaa_viter  Vector iteration functions.
+ * @ingroup drmaa
+ *
+ * The drmaa_get_next_<i>X</i>() functions SHALL store up to @a value_len
+ * bytes of the next attribute name / attribute value / job identifier
+ * from the @a values opaque string vector in the @a value buffer.
+ * The opaque string vector's internal iterator SHALL then be moved forward
+ * to the next entry.  If there are no more values those functions return
+ * @ref DRMAA_ERRNO_INVALID_ARGUMENT (but this is outside DRMAA specification).
+ *
+ * The drmaa_get_num_<i>X</i>() functions SHALL store the number of elements
+ * in the space provided by @a size.
+ *
+ * The drmaa_release_<i>X</i>() functions free the memory used by the
+ * @a values opaque string vector.  All memory used by strings contained
+ * therein is also freed.
+ */
+/* @addtogroup drmaa_viter @{ */
+int drmaa_get_next_attr_name( drmaa_attr_names_t* values,
+	char *value, size_t value_len	);
+int drmaa_get_next_attr_value( drmaa_attr_values_t* values,
+	char *value, size_t value_len );
+int drmaa_get_next_job_id( drmaa_job_ids_t* values,
+	char *value, size_t value_len );
+int drmaa_get_num_attr_names( drmaa_attr_names_t* values, size_t *size );
+int drmaa_get_num_attr_values(drmaa_attr_values_t* values, size_t *size );
+int drmaa_get_num_job_ids( drmaa_job_ids_t* values, size_t *size );
+void drmaa_release_attr_names( drmaa_attr_names_t* values );
+void drmaa_release_attr_values( drmaa_attr_values_t* values );
+void drmaa_release_job_ids( drmaa_job_ids_t* values );
+/* @} */
+
+/**
+ * The drmaa_run_job() function submits a single job with the attributes
+ * defined in the job template, @a jt.  Upon success, up to @a job_id_len
+ * characters of the submitted job's job identifier are stored in the buffer,
+ * @a job_id.
+ */
+int drmaa_run_job(
+	char *job_id, size_t job_id_len, const drmaa_job_template_t *jt,
+	char *error_diagnosis, size_t error_diag_len
+	);
+
+/**
+ * The drmaa_run_bulk_jobs() function submits a set of parametric jobs which
+ * can be run concurrently.  The attributes defined in the job template,
+ * @a jt are used for every parametric job in the set.  Each job in the
+ * set is identical except for it's index.  The first parametric job has an
+ * index equal to @a start.  The next job has an index equal to @a start +
+ * @a incr, and so on.  The last job has an index equal to <code>start + n *
+ * incr</code>, where @c n is equal to <code>(end - start) / incr</code>.
+ * Note that the value of the last job's index may not be equal to end if the
+ * difference between @a start and @a end is not evenly divisble by @a incr.
+ * The smallest valid value for @a start is 1.  The largest valid value for
+ * @a end is 2147483647 (2^31-1).  The @a start value must be less than or
+ * equal to the @a end value, and only positive index numbers are allowed.
+ * The index number can be determined by the job in an implementation
+ * specific fashion.  On success, an opaque job id string vector containing
+ * job identifiers for all submitted jobs SHALL be returned into @a job_ids.
+ * The job identifiers in the opaque job id string vector can be extracted
+ * using the drmaa_get_next_job_id() function. The caller is responsible
+ * for releasing the opaque job id string vector returned into @a job_ids
+ * using the drmaa_release_job_ids() function.
+ */
+int drmaa_run_bulk_jobs(
+	drmaa_job_ids_t **jobids,
+	const drmaa_job_template_t *jt,
+	int start, int end, int incr,
+	char *error_diagnosis, size_t error_diag_len
+	);
+
+/**
+ * The drmaa_control() function SHALL enact the action indicated
+ * by @a action on the job specified by the job identifier, @a jobid.
+ * The action parameter's value may be one of the following:
+ *   - DRMAA_CONTROL_SUSPEND
+ *   - DRMAA_CONTROL_RESUME
+ *   - DRMAA_CONTROL_HOLD
+ *   - DRMAA_CONTROL_RELEASE
+ *   - DRMAA_CONTROL_TERMINATE
+ * The drmaa_control() function SHALL return after the DRM system has
+ * acknowledged the command, not necessarily after the desired action has
+ * been performed.  If @a jobid is DRMAA_JOB_IDS_SESSION_ALL, this function
+ * SHALL perform the specified action on all jobs submitted during this
+ * session as of this function is called.
+ */
+int drmaa_control(
+	const char *job_id, int action,
+	char *error_diagnosis, size_t error_diag_len
+	);
+
+/**
+ * The drmaa_job_ps() function SHALL store in @a remote_ps the program
+ * status of the job identified by @a job_id. The possible values of
+ * a program's staus are:
+ *   - DRMAA_PS_UNDETERMINED
+ *   - DRMAA_PS_QUEUED_ACTIVE
+ *   - DRMAA_PS_SYSTEM_ON_HOLD
+ *   - DRMAA_PS_USER_ON_HOLD
+ *   - DRMAA_PS_USER_SYSTEM_ON_HOLD
+ *   - DRMAA_PS_RUNNING
+ *   - DRMAA_PS_SYSTEM_SUSPENDED
+ *   - DRMAA_PS_USER_SUSPENDED
+ *   - DRMAA_PS_DONE
+ *   - DRMAA_PS_FAILED
+ * Terminated jobs have a status of DRMAA_PS_FAILED.
+ */
+int drmaa_job_ps(
+	const char *job_id, int *remote_ps,
+	char *error_diagnosis, size_t error_diag_len
+	);
+
+/**
+ * The drmaa_synchronize() function SHALL cause the calling thread to
+ * block until all jobs specified by @a job_ids have finished execution.
+ * If @a job_ids contains DRMAA_JOB_IDS_SESSION_ALL, then this function
+ * SHALL wait for all jobs submitted during this DRMAA session as of the
+ * point in time when drmaa_synchronize() is called.  To avoid thread race
+ * conditions in multithreaded applications, the DRMAA implementation user
+ * should explicitly synchronize this call with any other job submission
+ * calls or control calls that may change the number of remote jobs.
+ *
+ * The @a timeout parameter value indicates how many seconds to remain
+ * blocked in this call waiting for results to become available, before
+ * returning with a DRMAA_ERRNO_EXIT_TIMEOUT error code.  The value,
+ * DRMAA_TIMEOUT_WAIT_FOREVER, MAY be specified to wait indefinitely for
+ * a result.  The value, DRMAA_TIMEOUT_NO_WAIT, MAY be specified to return
+ * immediately with a DRMAA_ERRNO_EXIT_TIMEOUT error code if no result is
+ * available.  If the call exits before the timeout has elapsed, all the
+ * jobs have been waited on or there was an interrupt.  The caller should
+ * check system time before and after this call in order to be sure of how
+ * much time has passed.  The @a dispose parameter specifies how to treat
+ * the reaping of the remote job's internal data record, which includes a
+ * record of the job's consumption of system resources during its execution
+ * and other statistical information.  If the @a dispose parameter's value
+ * is 1, the DRMAA implementation SHALL dispose of the job's data record at
+ * the end of the drmaa_synchroniize() call.  If the @a dispose parameter's
+ * value is 0, the data record SHALL be left for future access via the
+ * drmaa_wait() method.
+ */
+int drmaa_synchronize(
+	const char *job_ids[], signed long timeout, int dispose,
+	char *error_diagnosis, size_t error_diag_len
+	);
+
+/**
+ * The drmaa_wait() function SHALL wait for a job identified by @a job_id
+ * to finish execution or fail. If the special string, JOB_IDS_SESSION_ANY,
+ * is provided as the job_id, this function will wait for any job from the
+ * session to finish execution or fail.  In this case, any job for which exit
+ * status information is available will satisfy the requirement, including
+ * jobs which preivously finished but have never been the subject of a
+ * drmaa_wait() call.  This routine is modeled on the @c wait3 POSIX routine.
+ *
+ * The @a timeout parameter value indicates how many seconds
+ * to remain blocked in this call waiting for a result, before
+ * returning with a DRMAA_ERRNO_EXIT_TIMEOUT error code.  The value,
+ * DRMAA_TIMEOUT_WAIT_FOREVER, MAY be specified to wait indefinitely for
+ * a result.  The value, DRMAA_TIMEOUT_NO_WAIT, MAY be specified to return
+ * immediately with a DRMAA_ERRNO_EXIT_TIMEOUT error code if no result is
+ * available.  If the call exits before the timeout has elapsed, the job
+ * has been successfully waited on or there was an interrupt.  The caller
+ * should check system time before and after this call in order to be sure
+ * of how much time has passed.
+ *
+ * Upon success, drmaa_wait() fills @a job_id_out with up to @a
+ * job_id_out_len characters of the waited job's id, stat with the
+ * a code that includes information about the conditions under which
+ * the job terminated, and @a rusage with an array of <name>=<value>
+ * strings that describe the amount of resources consumed by the job
+ * and are implementation defined.  The @a stat parameter is further
+ * described below.  The @a rusage parameter's values may be accessed via
+ * drmaa_get_next_attr_value().
+ *
+ * The drmaa_wait() function reaps job data records on a successful
+ * call, so any subsequent calls to drmaa_wait() will fail, returning
+ * a DRMAA_ERRNO_INVALID_JOB error code, meaning that the job's data
+ * record has already been reaped.  This error code is the same as
+ * if the job were unknown.  If drmaa_wait() exists due to a timeout,
+ * DRMAA_ERRNO_EXIT_TIMEOUT is returned and no rusage information is reaped.
+ * (The only case where drmaa_wait() can be successfully called on a single
+ * job more than once is when the previous call(s) to drmaa_wait() returned
+ * DRMAA_ERRNO_EXIT_TIMEOUT.)
+ *
+ * The stat parameter, set by a successful call to drmaa_wait(), is used
+ * to retrieve further input about the exit condition of the waited
+ * job, identified by job_id_out, through the following functions:
+ * drmaa_wifexited(), drmaa_wexitstatus(), drmaa_wifsignaled(),
+ * drmaa_wtermsig(),drmaa_wcoredump() and drmaa_wifaborted().
+ */
+int drmaa_wait(
+	const char *job_id,
+	char *job_id_out, size_t job_id_out_len, int *stat,
+	signed long timeout, drmaa_attr_values_t **rusage,
+	char *error_diagnosis, size_t error_diag_len
+	);
+
+int drmaa_wifexited( int *exited, int stat,
+	char *error_diagnosis, size_t error_diag_len );
+int drmaa_wexitstatus( int *exit_status, int stat,
+	char *error_diagnosis, size_t error_diag_len );
+int drmaa_wifsignaled( int *signaled, int stat,
+	char *error_diagnosis, size_t error_diag_len );
+int drmaa_wtermsig( char *signal, size_t signal_len, int stat,
+	char *error_diagnosis, size_t error_diag_len );
+int drmaa_wcoredump( int *core_dumped, int stat,
+	char *error_diagnosis, size_t error_diag_len );
+int drmaa_wifaborted( int *aborted, int stat,
+	char *error_diagnosis, size_t error_diag_len );
+
+/**
+ * The drmaa_strerror() function SHALL return the error string describing
+ * the DRMAA error number @a drmaa_errno.
+ */
+const char *drmaa_strerror( int drmaa_errno );
+
+/**
+ * The drmaa_get_contact() function, if called before drmaa_init(), SHALL
+ * return a string containing a comma-delimited list of default DRMAA
+ * implementation contacts strings, one per DRM implementation provided.
+ * If called after drmaa_init(), drmaa_get_contacts() SHALL return the
+ * contact string for the DRM system for which the library has been
+ * initialized.
+ */
+int drmaa_get_contact( char *contact, size_t contact_len,
+	char *error_diagnosis, size_t error_diag_len );
+
+/**
+ * The drmaa_version() function SHALL set major and minor to the major and
+ * minor versions of the DRMAA C binding specification implemented by the
+ * DRMAA implementation.
+ */
+int drmaa_version( unsigned int *major, unsigned int *minor,
+	char *error_diagnosis, size_t error_diag_len );
+
+/**
+ * The drmaa_get_DRM_system() function, if called before drmaa_init(),
+ * SHALL return a string containing a comma-delimited list of DRM system
+ * identifiers, one per DRM system implementation provided.  If called after
+ * drmaa_init(), drmaa_get_DRM_system() SHALL return the selected DRM system.
+ */
+int drmaa_get_DRM_system( char *drm_system, size_t drm_system_len,
+	char *error_diagnosis, size_t error_diag_len );
+
+/**
+ * The drmaa_get_DRMAA_implementation() function, if called before
+ * drmaa_init(), SHALL return a string containing a comma-delimited list of
+ * DRMAA implementations, one per DRMAA implementation provided.  If called
+ * after drmaa_init(), drmaa_get_DRMAA_implementation() SHALL return the
+ * selected DRMAA implementation.
+ */
+int drmaa_get_DRMAA_implementation( char *drmaa_impl, size_t drmaa_impl_len,
+	char *error_diagnosis, size_t error_diag_len );
+
+/* @} */
+
+
+
+
+int
+drmaa_read_configuration_file(
+		const char *filename, int must_exist,
+		char *error_diagnosis, size_t error_diag_len
+		);
+
+int
+drmaa_read_configuration(
+		const char *configuration, size_t conf_len,
+		char *error_diagnosis, size_t error_diag_len
+		);
+
+
+#if defined(__cplusplus)
+} /* extern "C" */
+#endif
+
+#endif /* __DRMAA_H */
+
Index: trunk/drmaa_utils/drmaa_utils/conf.h
===================================================================
--- trunk/drmaa_utils/drmaa_utils/conf.h	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/conf.h	(revision 1)
@@ -0,0 +1,110 @@
+/* $Id: conf.h 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+#ifndef __DRMAA_UTILS__CONF_H
+#define __DRMAA_UTILS__CONF_H
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <drmaa_utils/common.h>
+
+typedef enum {
+	FSD_CONF_INTEGER,
+	FSD_CONF_STRING,
+	FSD_CONF_DICT
+} fsd_conf_type_t;
+
+struct fsd_conf_option_s {
+	fsd_conf_type_t type;
+	union {
+		int integer;
+		char *string;
+		fsd_conf_dict_t *dict;
+	} val;
+};
+
+
+/**
+ * Read configuration.
+ */
+fsd_conf_dict_t *
+fsd_conf_read(
+		fsd_conf_dict_t *configuration,
+		const char *filename, bool must_exist,
+		const char *content, size_t content_len
+		);
+
+
+fsd_conf_dict_t *
+fsd_conf_load( const char *filename );
+
+fsd_conf_option_t *
+fsd_conf_option_create( fsd_conf_type_t type, void *value );
+
+void
+fsd_conf_option_destroy( fsd_conf_option_t *option );
+
+fsd_conf_option_t *
+fsd_conf_option_merge( fsd_conf_option_t *lhs, fsd_conf_option_t *rhs );
+
+void
+fsd_conf_option_dump( fsd_conf_option_t *option );
+
+
+
+fsd_conf_dict_t *
+fsd_conf_dict_create(void);
+
+void
+fsd_conf_dict_destroy( fsd_conf_dict_t *dict );
+
+fsd_conf_option_t *
+fsd_conf_dict_get( fsd_conf_dict_t *dict, const char *key );
+
+void
+fsd_conf_dict_set(
+		fsd_conf_dict_t *dict, const char *key, fsd_conf_option_t *value
+		);
+
+fsd_conf_dict_t *
+fsd_conf_dict_merge( fsd_conf_dict_t *lhs, fsd_conf_dict_t *rhs );
+
+void
+fsd_conf_dict_dump( fsd_conf_dict_t *dict );
+
+
+/*
+ * Versions of functions above which do not raise exceptions.
+ * Needed in conf_tab.y
+ */
+
+fsd_conf_option_t *
+fsd_conf_option_create_noraise( fsd_conf_type_t type, void *value );
+
+fsd_conf_dict_t *
+fsd_conf_dict_create_noraise(void);
+
+int
+fsd_conf_dict_set_noraise(
+		fsd_conf_dict_t *dict, const char *key, fsd_conf_option_t *value );
+
+#endif /* __DRMAA_UTILS__CONF_H */
+
Index: trunk/drmaa_utils/drmaa_utils/logging.h
===================================================================
--- trunk/drmaa_utils/drmaa_utils/logging.h	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/logging.h	(revision 1)
@@ -0,0 +1,102 @@
+/* $Id: logging.h 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+#ifndef __DRMAA_UTILS__LOGGING_H
+#define __DRMAA_UTILS__LOGGING_H
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <stdio.h>
+
+#include <drmaa_utils/compat.h>
+#include <drmaa_utils/util.h>
+
+#define _log_fmt(level, kind, args) \
+	do { \
+		if( (int)fsd_verbose_level <= level ) \
+			_fsd_log( level, __FILE__, __FUNCTION__, kind, \
+					fsd_asprintf args ); \
+	} while(0)
+
+#define _log_empty(level, kind) \
+	do { \
+		if( (int)fsd_verbose_level <= level ) \
+			_fsd_log( level, __FILE__, __FUNCTION__, kind, NULL ); \
+	} while(0)
+
+#define _log_nop \
+	do { /* nothing */ } while(0)
+
+#ifdef DEBUGGING
+#	define fsd_log_trace(args)   _log_fmt(FSD_LOG_TRACE, _FSD_LOG_MSG, args)
+#	define fsd_log_debug(args)   _log_fmt(FSD_LOG_DEBUG, _FSD_LOG_MSG, args)
+#	define fsd_log_enter(args)   _log_fmt(FSD_LOG_TRACE, _FSD_LOG_ENTER, args)
+# define fsd_log_return(args)  _log_fmt(FSD_LOG_TRACE, _FSD_LOG_RETURN, args)
+#else /* ! DEBUGGING */
+#	define fsd_log_trace(args)   _log_nop
+#	define fsd_log_debug(args)   _log_nop
+#	define fsd_log_enter(args)   _log_nop
+#	define fsd_log_return(args)  _log_nop
+#endif
+
+#define fsd_log_info(args)     _log_fmt(FSD_LOG_INFO, _FSD_LOG_MSG, args)
+#define fsd_log_warning(args)  _log_fmt(FSD_LOG_WARNING, _FSD_LOG_MSG, args)
+#define fsd_log_error(args)    _log_fmt(FSD_LOG_ERROR, _FSD_LOG_MSG, args)
+#define fsd_log_fatal(args)    _log_fmt(FSD_LOG_FATAL, _FSD_LOG_MSG, args)
+
+enum{ _FSD_LOG_MSG, _FSD_LOG_ENTER, _FSD_LOG_RETURN };
+void _fsd_log( int level, const char *file, const char *function,
+	int kind, char *message );
+
+void fsd_log_fmt( int level, const char *fmt, ... )
+	__attribute__(( format( printf, 2, 3 ) ));
+
+void fsd_log_fmtv( int level, const char *fmt, va_list args );
+
+void fsd_log_stacktrace( int skip, int limit );
+
+
+/**
+ * Specify place where log messages shall be written.
+ * By default they are written to standard error stream (2).
+ * @param fd   File descriptor to write to.
+ */
+void
+fsd_set_logging_fd( int fd );
+
+typedef enum {
+	FSD_LOG_ALL,
+	FSD_LOG_TRACE,
+	FSD_LOG_DEBUG,
+	FSD_LOG_INFO,
+	FSD_LOG_WARNING,
+	FSD_LOG_ERROR,
+	FSD_LOG_FATAL,
+	FSD_LOG_NONE
+} fsd_verbose_level_t;
+
+void
+fsd_set_verbosity_level( fsd_verbose_level_t level );
+
+extern fsd_verbose_level_t fsd_verbose_level;
+
+#endif /* __DRMAA_UTILS__LOGGING_H */
+
Index: trunk/drmaa_utils/drmaa_utils/xmalloc.c
===================================================================
--- trunk/drmaa_utils/drmaa_utils/xmalloc.c	(revision 1)
+++ trunk/drmaa_utils/drmaa_utils/xmalloc.c	(revision 1)
@@ -0,0 +1,190 @@
+/* $Id: xmalloc.c 289 2010-09-14 14:13:17Z mmatloka $ */
+/*
+ *  FedStage DRMAA utilities library
+ *  Copyright (C) 2006-2008  FedStage Systems
+ *
+ *  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/>.
+ */
+
+/**
+ * @file xmalloc.c
+ * Memory allocation/deallocation routines.
+ */
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <errno.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <drmaa_utils/xmalloc.h>
+#include <drmaa_utils/compat.h>
+#include <drmaa_utils/exception.h>
+#include <drmaa_utils/logging.h>
+
+#ifndef SIZE_T_MAX
+#  define SIZE_T_MAX ((size_t) -1)
+#endif
+
+#ifndef lint
+static char rcsid[]
+#	ifdef __GNUC__
+		__attribute__ ((unused))
+#	endif
+	= "$Id: xmalloc.c 289 2010-09-14 14:13:17Z mmatloka $";
+#endif
+
+
+void *
+fsd_malloc_( void **p, size_t size )
+{
+	void *ptr = NULL;
+	if( size )
+	 {
+		ptr = malloc( size );
+		if( ptr )
+			memset( ptr, 0, size );
+		else
+		 {
+			*p = NULL;
+			fsd_exc_raise_sys( errno=ENOMEM );
+		 }
+	 }
+	*p = ptr;
+	return ptr;
+}
+
+
+void *
+fsd_calloc_( void **p, size_t n, size_t size )
+{
+	void *ptr = NULL;
+
+	/*fsd_log_enter(("%d", (int)n));*/
+
+	if( n && size )
+	 {
+		if( n <= SIZE_T_MAX / size )
+			ptr = calloc( n, size );
+		if( !ptr )
+		 {
+			*p = NULL;
+			fsd_exc_raise_sys( errno=ENOMEM );
+		 }
+	 }
+	*p = ptr;
+	return ptr;
+}
+
+
+void *
+fsd_realloc_( void **p, size_t size )
+{
+	void *ptr = *p;
+
+	if( size )
+	 {
+		if( ptr )
+			ptr = realloc( ptr, size );
+		else
+			ptr = malloc( size );
+
+		if( ptr != NULL )
+			*p = ptr;
+		else
+			fsd_exc_raise_sys( errno=ENOMEM );
+	 }
+	else if( ptr != NULL )
+	 {
+		free( ptr );
+		*p = ptr = NULL;
+	 }
+
+	return ptr;
+}
+
+
+void
+fsd_free( void *p )
+{
+	if( p )
+		free( p );
+}
+
+
+int
+fsd_malloc_noraise_( void **p, size_t size )
+{
+	int result = 0;
+	void *ptr = NULL;
+	if( size )
+	 {
+		ptr = malloc( size );
+		if( ptr )
+			memset( ptr, 0, size );
+		else
+			result = ENOMEM;
+	 }
+	*p = ptr;
+	return result;
+}
+
+
+int
+fsd_calloc_noraise_( void **p, size_t n, size_t size )
+{
+	int result = 0;
+	void *ptr = NULL;
+	if( n && size )
+	 {
+		if( n <= SIZE_T_MAX / size )
+			ptr = calloc( n, size );
+		if( !ptr )
+			result = ENOMEM;
+	 }
+	*p = ptr;
+	return result;
+}
+
+
+int
+fsd_realloc_noraise_( void **p, size_t size )
+{
+	int result = 0;
+	void *ptr = *p;
+
+	if( size )
+	 {
+		if( ptr )
+			ptr = realloc( ptr, size );
+		else
+			ptr = malloc( size );
+
+		if( ptr != NULL )
+			*p = ptr;
+		else
+			result = ENOMEM;
+	 }
+	else if( ptr != NULL )
+	 {
+		free( ptr );
+		*p = ptr = NULL;
+	 }
+
+	return result;
+}
+
Index: trunk/drmaa_utils/INSTALL
===================================================================
--- trunk/drmaa_utils/INSTALL	(revision 1)
+++ trunk/drmaa_utils/INSTALL	(revision 1)
@@ -0,0 +1,237 @@
+Installation Instructions
+*************************
+
+Copyright (C) 1994, 1995, 1996, 1999, 2000, 2001, 2002, 2004, 2005,
+2006, 2007 Free Software Foundation, Inc.
+
+This file is free documentation; the Free Software Foundation gives
+unlimited permission to copy, distribute and modify it.
+
+Basic Installation
+==================
+
+Briefly, the shell commands `./configure; make; make install' should
+configure, build, and install this package.  The following
+more-detailed instructions are generic; see the `README' file for
+instructions specific to this package.
+
+   The `configure' shell script attempts to guess correct values for
+various system-dependent variables used during compilation.  It uses
+those values to create a `Makefile' in each directory of the package.
+It may also create one or more `.h' files containing system-dependent
+definitions.  Finally, it creates a shell script `config.status' that
+you can run in the future to recreate the current configuration, and a
+file `config.log' containing compiler output (useful mainly for
+debugging `configure').
+
+   It can also use an optional file (typically called `config.cache'
+and enabled with `--cache-file=config.cache' or simply `-C') that saves
+the results of its tests to speed up reconfiguring.  Caching is
+disabled by default to prevent problems with accidental use of stale
+cache files.
+
+   If you need to do unusual things to compile the package, please try
+to figure out how `configure' could check whether to do them, and mail
+diffs or instructions to the address given in the `README' so they can
+be considered for the next release.  If you are using the cache, and at
+some point `config.cache' contains results you don't want to keep, you
+may remove or edit it.
+
+   The file `configure.ac' (or `configure.in') is used to create
+`configure' by a program called `autoconf'.  You need `configure.ac' if
+you want to change it or regenerate `configure' using a newer version
+of `autoconf'.
+
+The simplest way to compile this package is:
+
+  1. `cd' to the directory containing the package's source code and type
+     `./configure' to configure the package for your system.
+
+     Running `configure' might take a while.  While running, it prints
+     some messages telling which features it is checking for.
+
+  2. Type `make' to compile the package.
+
+  3. Optionally, type `make check' to run any self-tests that come with
+     the package.
+
+  4. Type `make install' to install the programs and any data files and
+     documentation.
+
+  5. You can remove the program binaries and object files from the
+     source code directory by typing `make clean'.  To also remove the
+     files that `configure' created (so you can compile the package for
+     a different kind of computer), type `make distclean'.  There is
+     also a `make maintainer-clean' target, but that is intended mainly
+     for the package's developers.  If you use it, you may have to get
+     all sorts of other programs in order to regenerate files that came
+     with the distribution.
+
+  6. Often, you can also type `make uninstall' to remove the installed
+     files again.
+
+Compilers and Options
+=====================
+
+Some systems require unusual options for compilation or linking that the
+`configure' script does not know about.  Run `./configure --help' for
+details on some of the pertinent environment variables.
+
+   You can give `configure' initial values for configuration parameters
+by setting variables in the command line or in the environment.  Here
+is an example:
+
+     ./configure CC=c99 CFLAGS=-g LIBS=-lposix
+
+   *Note Defining Variables::, for more details.
+
+Compiling For Multiple Architectures
+====================================
+
+You can compile the package for more than one kind of computer at the
+same time, by placing the object files for each architecture in their
+own directory.  To do this, you can use GNU `make'.  `cd' to the
+directory where you want the object files and executables to go and run
+the `configure' script.  `configure' automatically checks for the
+source code in the directory that `configure' is in and in `..'.
+
+   With a non-GNU `make', it is safer to compile the package for one
+architecture at a time in the source code directory.  After you have
+installed the package for one architecture, use `make distclean' before
+reconfiguring for another architecture.
+
+Installation Names
+==================
+
+By default, `make install' installs the package's commands under
+`/usr/local/bin', include files under `/usr/local/include', etc.  You
+can specify an installation prefix other than `/usr/local' by giving
+`configure' the option `--prefix=PREFIX'.
+
+   You can specify separate installation prefixes for
+architecture-specific files and architecture-independent files.  If you
+pass the option `--exec-prefix=PREFIX' to `configure', the package uses
+PREFIX as the prefix for installing programs and libraries.
+Documentation and other data files still use the regular prefix.
+
+   In addition, if you use an unusual directory layout you can give
+options like `--bindir=DIR' to specify different values for particular
+kinds of files.  Run `configure --help' for a list of the directories
+you can set and what kinds of files go in them.
+
+   If the package supports it, you can cause programs to be installed
+with an extra prefix or suffix on their names by giving `configure' the
+option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'.
+
+Optional Features
+=================
+
+Some packages pay attention to `--enable-FEATURE' options to
+`configure', where FEATURE indicates an optional part of the package.
+They may also pay attention to `--with-PACKAGE' options, where PACKAGE
+is something like `gnu-as' or `x' (for the X Window System).  The
+`README' should mention any `--enable-' and `--with-' options that the
+package recognizes.
+
+   For packages that use the X Window System, `configure' can usually
+find the X include and library files automatically, but if it doesn't,
+you can use the `configure' options `--x-includes=DIR' and
+`--x-libraries=DIR' to specify their locations.
+
+Specifying the System Type
+==========================
+
+There may be some features `configure' cannot figure out automatically,
+but needs to determine by the type of machine the package will run on.
+Usually, assuming the package is built to be run on the _same_
+architectures, `configure' can figure that out, but if it prints a
+message saying it cannot guess the machine type, give it the
+`--build=TYPE' option.  TYPE can either be a short name for the system
+type, such as `sun4', or a canonical name which has the form:
+
+     CPU-COMPANY-SYSTEM
+
+where SYSTEM can have one of these forms:
+
+     OS KERNEL-OS
+
+   See the file `config.sub' for the possible values of each field.  If
+`config.sub' isn't included in this package, then this package doesn't
+need to know the machine type.
+
+   If you are _building_ compiler tools for cross-compiling, you should
+use the option `--target=TYPE' to select the type of system they will
+produce code for.
+
+   If you want to _use_ a cross compiler, that generates code for a
+platform different from the build platform, you should specify the
+"host" platform (i.e., that on which the generated programs will
+eventually be run) with `--host=TYPE'.
+
+Sharing Defaults
+================
+
+If you want to set default values for `configure' scripts to share, you
+can create a site shell script called `config.site' that gives default
+values for variables like `CC', `cache_file', and `prefix'.
+`configure' looks for `PREFIX/share/config.site' if it exists, then
+`PREFIX/etc/config.site' if it exists.  Or, you can set the
+`CONFIG_SITE' environment variable to the location of the site script.
+A warning: not all `configure' scripts look for a site script.
+
+Defining Variables
+==================
+
+Variables not defined in a site shell script can be set in the
+environment passed to `configure'.  However, some packages may run
+configure again during the build, and the customized values of these
+variables may be lost.  In order to avoid this problem, you should set
+them in the `configure' command line, using `VAR=value'.  For example:
+
+     ./configure CC=/usr/local2/bin/gcc
+
+causes the specified `gcc' to be used as the C compiler (unless it is
+overridden in the site shell script).
+
+Unfortunately, this technique does not work for `CONFIG_SHELL' due to
+an Autoconf bug.  Until the bug is fixed you can use this workaround:
+
+     CONFIG_SHELL=/bin/bash /bin/bash ./configure CONFIG_SHELL=/bin/bash
+
+`configure' Invocation
+======================
+
+`configure' recognizes the following options to control how it operates.
+
+`--help'
+`-h'
+     Print a summary of the options to `configure', and exit.
+
+`--version'
+`-V'
+     Print the version of Autoconf used to generate the `configure'
+     script, and exit.
+
+`--cache-file=FILE'
+     Enable the cache: use and save the results of the tests in FILE,
+     traditionally `config.cache'.  FILE defaults to `/dev/null' to
+     disable caching.
+
+`--config-cache'
+`-C'
+     Alias for `--cache-file=config.cache'.
+
+`--quiet'
+`--silent'
+`-q'
+     Do not print messages saying which checks are being made.  To
+     suppress all normal output, redirect it to `/dev/null' (any error
+     messages will still be shown).
+
+`--srcdir=DIR'
+     Look for the package's source code in directory DIR.  Usually
+     `configure' can determine that directory automatically.
+
+`configure' also accepts some other, not widely useful, options.  Run
+`configure --help' for more details.
+
Index: trunk/drmaa_utils/project/project.tmpl
===================================================================
--- trunk/drmaa_utils/project/project.tmpl	(revision 1)
+++ trunk/drmaa_utils/project/project.tmpl	(revision 1)
@@ -0,0 +1,137 @@
+## $Id$
+#encoding utf-8
+#extends project_template.templates.Autotools
+
+#def generated_files
+#return (Autotools.generated_files(self)
+  | set([
+		"m4/ac_c_bigendian_cross.m4",
+		"m4/acx_pthread.m4",
+		"m4/ax_docutils.m4",
+		"m4/ax_func_gettid.m4",
+		"m4/ax_func_va_copy.m4",
+		"m4/ax_gperf.m4",
+		"m4/bison_ylwrap.sh",
+		"Makefile.am",
+		]))
+#end def
+
+#block ac_arguments
+${Autotools.ac_arguments(self)}
+AC_ARG_WITH(drmaa-utils, AC_HELP_STRING([--with-drmaa-utils=...],
+		[used only to detect that drmaa utils is sub packaged]))
+AM_CONDITIONAL([DRMAA_UTILS_STANDALONE],
+		[test x\$with_drmaa_utils = x])
+#end block ac_arguments
+
+#block ac_programs
+${Autotools.ac_programs(self)}
+
+#raw
+\# code generation tools:
+AC_PROG_YACC
+AX_GPERF
+AC_CHECK_PROGS([RAGEL], [ragel], [sh m4/missing-dev-prog.sh ragel])
+
+\# reStructuredText processing:
+AX_DOCUTILS
+\# documentation generation:
+AC_CHECK_PROGS([DOT], [dot])
+if test x$DOT != x; then
+	HAVE_DOT=yes
+else
+	HAVE_DOT=no
+fi
+AC_SUBST([HAVE_DOT])
+#end raw
+#end block ac_programs
+
+#block ac_system
+${Autotools.ac_system(self)}
+
+AC_C_BIGENDIAN_CROSS
+#end block ac_system
+
+
+#block ac_libraries
+#raw
+ACX_PTHREAD([CFLAGS="$CFLAGS $PTHREAD_CFLAGS" LIBS="$PTHREAD_LIBS $LIBS"],
+		[AC_MSG_ERROR([POSIX threads library is required by DRMAA.])])
+#end raw
+#end block ac_libraries
+
+#block ac_headers
+AC_CHECK_HEADERS([execinfo.h fcntl.h inttypes.h libintl.h limits.h malloc.h stddef.h stdint.h stdlib.h string.h sys/time.h unistd.h])
+AC_HEADER_STDBOOL
+AC_HEADER_TIME
+#end block ac_headers
+
+#block ac_types
+AC_TYPE_PID_T
+AC_TYPE_SIZE_T
+AC_TYPE_SSIZE_T
+AC_TYPE_MODE_T
+AC_TYPE_UINT16_T
+AC_TYPE_UINT32_T
+AC_TYPE_UINT8_T
+#end block ac_types
+
+#block ac_structures
+AC_STRUCT_TM
+#end block ac_structures
+
+#block ac_functions
+AC_FUNC_ALLOCA
+AC_FUNC_MALLOC
+AC_FUNC_REALLOC
+AC_FUNC_STRERROR_R
+AC_FUNC_STRFTIME
+AC_CHECK_FUNCS([ \
+	asprintf \
+	fstat \
+	getcwd \
+	gettimeofday \
+	localtime_r \
+	memset \
+	mkstemp \
+	strchr \
+	strdup \
+	strerror \
+	strlcpy \
+	strndup \
+	strstr \
+	vasprintf])
+AX_FUNC_GETTID
+AX_FUNC_VA_COPY
+AC_SEARCH_LIBS([backtrace], [execinfo])
+#end block ac_functions
+
+#block ac_config_files
+AC_CONFIG_FILES([
+	Makefile
+	drmaa_utils/Makefile
+	test/Makefile
+	Doxyfile
+])
+AC_CONFIG_HEADERS([config.h])
+#end block ac_config_files
+
+## #block ac_success_message
+## ${Autotools.ac_success_message(self)}
+## #end block ac_success_message
+
+
+#block top_makefile_am
+${makefile_am_header}
+${top_makefile_am_specific}
+SUBDIRS = drmaa_utils test
+#end block top_makefile_am
+
+#block boring_project_specific
+^drmaa_utils/conf_tab.c$
+^drmaa_utils/conf_tab.h$
+^drmaa_utils/datetime_tab.c$
+^drmaa_utils/datetime_tab.h$
+^drmaa_utils/drmaa_attrib.c$
+^test/test_exception$
+#end block boring_project_specific
Index: trunk/drmaa_utils/project/project.yaml
===================================================================
--- trunk/drmaa_utils/project/project.yaml	(revision 1)
+++ trunk/drmaa_utils/project/project.yaml	(revision 1)
@@ -0,0 +1,42 @@
+full_name: FedStage DRMAA utilities library
+short_name: drmaa_utils
+version: "2.0.1"
+copyright: Copyright (C) 2006-2008  FedStage Systems
+license: GNU General Public License (GPL) v. 3
+license_note: |
+  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/>.
+author: Åukasz CieÅnik
+author_email: Åukasz CieÅnik <lukasz.ciesnik@fedstage.com>
+maintainer: FedStage Systems
+# maintainer_email: FedStage DRMAA for PBS Pro users <drmaa-pbspro-users@lists.fedstage.com>
+organization: FedStage Systems
+url: http://www.fedstage.com/wiki/FedStage_DRMAA
+# download_url: http://sourceforge.net/project/showfiles.php?group_id=207998
+contact_address: drmaa-pbspro-users@lists.fedstage.com
+# description: short description
+# long_description: |
+#   multi-line description
+# keywords:
+#   - foo
+#   - bar
+classifiers:
+  - "Development Status :: 2 - Beta"
+  - "Intended Audience :: Developers"
+  - "License :: OSI Approved :: GNU General Public License (GPL)"
+  - "Operating System :: POSIX"
+  - "Programming Language :: C"
+  - "Topic :: System :: Distributed Computing"
+
+ac_config_srcdir: drmaa_utils/xmalloc.c
+darcs: false
Index: trunk/doc/rst.css
===================================================================
--- trunk/doc/rst.css	(revision 1)
+++ trunk/doc/rst.css	(revision 1)
@@ -0,0 +1,279 @@
+/*
+:Author: David Goodger
+:Contact: goodger@users.sourceforge.net
+:Date: $Date$
+:Revision: $Revision$
+:Copyright: This stylesheet has been placed in the public domain.
+
+Default cascading style sheet for the HTML output of Docutils.
+
+See http://docutils.sf.net/docs/howto/html-stylesheets.html for how to
+customize this style sheet.
+*/
+
+/* used to remove borders from tables and images */
+.borderless, table.borderless td, table.borderless th {
+  border: 0 }
+
+table.borderless td, table.borderless th {
+  /* Override padding for "table.docutils td" with "! important".
+     The right padding separates the table cells. */
+  padding: 0 0.5em 0 0 ! important }
+
+.first {
+  /* Override more specific margin styles with "! important". */
+  margin-top: 0 ! important }
+
+.last, .with-subtitle {
+  margin-bottom: 0 ! important }
+
+.hidden {
+  display: none }
+
+a.toc-backref {
+  text-decoration: none ;
+  color: black }
+
+blockquote.epigraph {
+  margin: 2em 5em ; }
+
+dl.docutils dd {
+  margin-bottom: 0.5em }
+
+/* Uncomment (and remove this text!) to get bold-faced definition list terms
+dl.docutils dt {
+  font-weight: bold }
+*/
+
+div.abstract {
+  margin: 2em 5em }
+
+div.abstract p.topic-title {
+  font-weight: bold ;
+  text-align: center }
+
+div.admonition, div.attention, div.caution, div.danger, div.error,
+div.hint, div.important, div.note, div.tip, div.warning {
+  margin: 2em ;
+  border: medium outset ;
+  padding: 1em }
+
+div.admonition p.admonition-title, div.hint p.admonition-title,
+div.important p.admonition-title, div.note p.admonition-title,
+div.tip p.admonition-title {
+  font-weight: bold ;
+  font-family: sans-serif }
+
+div.attention p.admonition-title, div.caution p.admonition-title,
+div.danger p.admonition-title, div.error p.admonition-title,
+div.warning p.admonition-title {
+  color: red ;
+  font-weight: bold ;
+  font-family: sans-serif }
+
+/* Uncomment (and remove this text!) to get reduced vertical space in
+   compound paragraphs.
+div.compound .compound-first, div.compound .compound-middle {
+  margin-bottom: 0.5em }
+
+div.compound .compound-last, div.compound .compound-middle {
+  margin-top: 0.5em }
+*/
+
+div.dedication {
+  margin: 2em 5em ;
+  text-align: center ;
+  font-style: italic }
+
+div.dedication p.topic-title {
+  font-weight: bold ;
+  font-style: normal }
+
+div.figure {
+  margin-left: 2em ;
+  margin-right: 2em }
+
+div.footer, div.header {
+  clear: both;
+  font-size: smaller }
+
+div.line-block {
+  display: block ;
+  margin-top: 1em ;
+  margin-bottom: 1em }
+
+div.line-block div.line-block {
+  margin-top: 0 ;
+  margin-bottom: 0 ;
+  margin-left: 1.5em }
+
+div.sidebar {
+  margin-left: 1em ;
+  border: medium outset ;
+  padding: 1em ;
+  background-color: #ffffee ;
+  width: 40% ;
+  float: right ;
+  clear: right }
+
+div.sidebar p.rubric {
+  font-family: sans-serif ;
+  font-size: medium }
+
+div.system-messages {
+  margin: 5em }
+
+div.system-messages h1 {
+  color: red }
+
+div.system-message {
+  border: medium outset ;
+  padding: 1em }
+
+div.system-message p.system-message-title {
+  color: red ;
+  font-weight: bold }
+
+div.topic {
+  margin: 2em }
+
+h1.section-subtitle, h2.section-subtitle, h3.section-subtitle,
+h4.section-subtitle, h5.section-subtitle, h6.section-subtitle {
+  margin-top: 0.4em }
+
+h1.title {
+  text-align: center }
+
+h2.subtitle {
+  text-align: center }
+
+hr.docutils {
+  width: 75% }
+
+img.align-left {
+  clear: left }
+
+img.align-right {
+  clear: right }
+
+ol.simple, ul.simple {
+  margin-bottom: 1em }
+
+ol.arabic {
+  list-style: decimal }
+
+ol.loweralpha {
+  list-style: lower-alpha }
+
+ol.upperalpha {
+  list-style: upper-alpha }
+
+ol.lowerroman {
+  list-style: lower-roman }
+
+ol.upperroman {
+  list-style: upper-roman }
+
+p.attribution {
+  text-align: right ;
+  margin-left: 50% }
+
+p.caption {
+  font-style: italic }
+
+p.credits {
+  font-style: italic ;
+  font-size: smaller }
+
+p.label {
+  white-space: nowrap }
+
+p.rubric {
+  font-weight: bold ;
+  font-size: larger ;
+  color: maroon ;
+  text-align: center }
+
+p.sidebar-title {
+  font-family: sans-serif ;
+  font-weight: bold ;
+  font-size: larger }
+
+p.sidebar-subtitle {
+  font-family: sans-serif ;
+  font-weight: bold }
+
+p.topic-title {
+  font-weight: bold }
+
+pre.address {
+  margin-bottom: 0 ;
+  margin-top: 0 ;
+  font-family: serif ;
+  font-size: 100% }
+
+pre.literal-block, pre.doctest-block {
+  margin-left: 2em ;
+  margin-right: 2em ;
+  background-color: #eeeeee }
+
+span.classifier {
+  font-family: sans-serif ;
+  font-style: oblique }
+
+span.classifier-delimiter {
+  font-family: sans-serif ;
+  font-weight: bold }
+
+span.interpreted {
+  font-family: sans-serif }
+
+span.option {
+  white-space: nowrap }
+
+span.pre {
+  white-space: pre }
+
+span.problematic {
+  color: red }
+
+span.section-subtitle {
+  /* font-size relative to parent (h1..h6 element) */
+  font-size: 80% }
+
+table.citation {
+  border-left: solid 1px gray;
+  margin-left: 1px }
+
+table.docinfo {
+  margin: 2em 4em }
+
+table.docutils {
+  margin-top: 0.5em ;
+  margin-bottom: 0.5em }
+
+table.footnote {
+  border-left: solid 1px black;
+  margin-left: 1px }
+
+table.docutils td, table.docutils th,
+table.docinfo td, table.docinfo th {
+  padding-left: 0.5em ;
+  padding-right: 0.5em ;
+  vertical-align: top }
+
+table.docutils th.field-name, table.docinfo th.docinfo-name {
+  font-weight: bold ;
+  text-align: left ;
+  white-space: nowrap ;
+  padding-left: 0 }
+
+h1 tt.docutils, h2 tt.docutils, h3 tt.docutils,
+h4 tt.docutils, h5 tt.docutils, h6 tt.docutils {
+  font-size: 100% }
+
+tt.docutils {
+  background-color: #eeeeee }
+
+ul.auto-toc {
+  list-style-type: none }
Index: trunk/doc/stylesheet.css
===================================================================
--- trunk/doc/stylesheet.css	(revision 1)
+++ trunk/doc/stylesheet.css	(revision 1)
@@ -0,0 +1,4 @@
+@import url("rst.css");
+table.docutils { 
+	border-collapse: collapse;
+}
Index: trunk/doc/.gitignore
===================================================================
--- trunk/doc/.gitignore	(revision 1)
+++ trunk/doc/.gitignore	(revision 1)
@@ -0,0 +1,10 @@
+doxy
+Doxyfile
+doxy-timestamp
+*.aux
+*.html
+*.log
+*.out
+*.pdf
+*.tex
+*.toc
Index: trunk/doc/Makefile.am
===================================================================
--- trunk/doc/Makefile.am	(revision 1)
+++ trunk/doc/Makefile.am	(revision 1)
@@ -0,0 +1,67 @@
+# $Id: Makefile.am 2623 2009-08-05 12:05:49Z mmamonski $
+# 
+# FedStage DRMAA for PBS Pro
+# Copyright (C) 2006-2009  FedStage Systems
+#
+# 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/>.
+#
+
+docdir=$(datadir)/doc
+pkgdocdir=$(docdir)/@PACKAGE@-@VERSION@
+
+plaintext_doc = \
+ $(top_srcdir)/README \
+ $(top_srcdir)/AUTHORS \
+ $(top_srcdir)/COPYING
+generated_doc = \
+ readme.html \
+ readme.pdf \
+ stylesheet.css \
+ rst.css
+
+EXTRA_DIST = $(generated_doc) readme.tex
+pkgdoc_DATA = $(plaintext_doc) $(generated_doc)
+
+DOCUTILSFLAGS = \
+ -i utf-8 \
+ -o utf-8 \
+ --language=en \
+ --file-insertion-enabled \
+ --no-generator \
+ --tab-width=4
+RST2HTMLFLAGS = $(DOCUTILSFLAGS) \
+ --stylesheet=stylesheet.css \
+ --link-stylesheet
+RST2LATEXFLAGS = $(DOCUTILSFLAGS) \
+ --documentclass=article \
+ --documentoptions=a4paper,10pt \
+ --font-encoding=OT4 \
+ --graphicx-option=pdftex \
+ --use-latex-footnotes \
+ --footnote-references=superscript \
+ --use-latex-citations \
+ --use-latex-toc
+
+readme.html: $(top_srcdir)/README
+	$(RST2HTML) $(RST2HTMLFLAGS) $< $@
+readme.tex: $(top_srcdir)/README
+	$(RST2LATEX) $(RST2LATEXFLAGS) $< $@
+.tex.pdf:
+	pdflatex $< && pdflatex $<
+
+clean-local:
+	-rm -rf *.log *.aux *.toc *.out
+
+MAINTAINERCLEANFILES = readme.html readme.tex readme.pdf drmaa.pdf
+
Index: trunk/project/project.tmpl
===================================================================
--- trunk/project/project.tmpl	(revision 1)
+++ trunk/project/project.tmpl	(revision 1)
@@ -0,0 +1,107 @@
+## $Id: project.tmpl 2420 2009-06-24 14:40:21Z lukasz $
+#encoding utf-8
+#extends project_template.templates.Autotools
+
+#def generated_files
+#return (Autotools.generated_files(self)
+  | set([
+		'm4/acx_pthread.m4',
+		'm4/ax_docutils.m4',
+        'm4/ax_gperf.m4',
+		'm4/ax_drmaa_utils.m4',
+		'm4/ax_pbs.m4',
+	]))
+#end def
+
+#block ac_programs
+${Autotools.ac_programs(self)}
+\# code generation tools:
+AX_GPERF
+## AC_CHECK_PROGS([RAGEL], [ragel], [sh m4/missing-dev-prog.sh ragel])
+
+\# reStructuredText processing:
+AX_DOCUTILS()
+if test x\$RST2HTML = x; then
+	RST2HTML="sh m4/missing-dev-prog.sh docutils"
+fi
+if test x\$RST2LATEX = x; then
+	RST2LATEX="sh m4/missing-dev-prog.sh docutils"
+fi
+#end block ac_programs
+
+#block ac_libraries
+#raw
+ACX_PTHREAD([CFLAGS="$CFLAGS $PTHREAD_CFLAGS" LIBS="$PTHREAD_LIBS $LIBS"],
+		[AC_MSG_ERROR([POSIX threads library is required.])])
+#end raw
+
+AX_DRMAA_UTILS([builtin], [:], [AC_MSG_ERROR([
+drmaa_utils libraries/headers not found]) ])
+
+AX_PBS([:], [AC_MSG_ERROR([
+PBS libraries/headers not found;
+add --with-pbs to set PBS installation root.]) ])
+#raw
+if test ${sysconfdir} == '${prefix}/etc' -a "$prefix" == 'NONE'; then
+	sysconfdir='/etc'
+	ac_configure_args="${ac_configure_args} --sysconfdir=${sysconfdir}"
+fi
+CPPFLAGS="${CPPFLAGS} -DCONFDIR=${sysconfdir}"
+#end raw
+#end block ac_libraries
+
+#block ac_headers
+AC_HEADER_STDC
+AC_HEADER_TIME
+AC_CHECK_HEADERS([stddef.h stdlib.h string.h strings.h sys/time.h unistd.h])
+#end block ac_headers
+
+#block ac_types
+AC_TYPE_SIZE_T
+#end block ac_types
+#block ac_structures
+AC_STRUCT_TM
+#end block ac_structures
+
+#block ac_functions
+AC_FUNC_MALLOC
+AC_FUNC_STRFTIME
+AC_FUNC_VPRINTF
+AC_CHECK_FUNCS([ \
+	asprintf \
+	fstat \
+	getcwd \
+	gettimeofday \
+	localtime_r \
+	memset \
+	mkstemp \
+	setenv \
+	strcasecmp \
+	strchr \
+	strdup \
+	strerror \
+	strlcpy \
+	strndup \
+	strstr \
+	strtol \
+	vasprintf \
+	])
+#end block ac_functions
+
+#block ac_config_files
+AC_CONFIG_FILES([
+	Makefile
+	pbs_drmaa/Makefile
+	doc/Makefile
+])
+AC_CONFIG_HEADERS([config.h])
+AC_CONFIG_SUBDIRS([drmaa_utils])
+#end block ac_config_files
+
+
+#block top_makefile_am
+${makefile_am_header}
+${top_makefile_am_specific}
+SUBDIRS = drmaa_utils pbs_drmaa doc
+#end block top_makefile_am
+
Index: trunk/project/project.yaml
===================================================================
--- trunk/project/project.yaml	(revision 1)
+++ trunk/project/project.yaml	(revision 1)
@@ -0,0 +1,49 @@
+full_name: FedStage DRMAA for PBS Pro
+short_name: pbs_drmaa
+version: "1.0.1"
+copyright: Copyright (C) 2006-2009  FedStage Systems
+license: GNU General Public License v. 3
+license_note: |
+  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/>.
+author: Åukasz CieÅnik
+author_email: Åukasz CieÅnik <lukasz.ciesnik@fedstage.com>
+maintainer: FedStage Systems
+maintainer_email: FedStage DRMAA for PBS users <drmaa-pbspro-users@lists.fedstage.com>
+organization: FedStage Systems
+url: http://www.fedstage.com/wiki/FedStage_DRMAA_for_PBS_Pro
+# download_url: http://example.com/downloads/lalamido
+contact_address: drmaa-pbspro-users@lists.fedstage.com
+description: DRMAA implementation for PBS Pro
+# long_description: |
+#   multi-line description
+keywords:
+  - DRMAA
+  - Distributed Resource Management Application API
+  - PBS Pro
+  - PBS
+  - Torque
+  - OpenPBS
+  - FedStage Systems
+classifiers:
+  - "Development Status :: 3 - Alpha"
+  - "Intended Audience :: Developers"
+  - "License :: OSI Approved :: GNU General Public License (GPL)"
+  - "Operating System :: POSIX"
+  - "Programming Language :: C"
+  - "Topic :: System :: Distributed Computing"
+
+ac_config_srcdir: pbs_drmaa/drmaa.c
+subproject_dirs:
+  - drmaa_utils
+
Index: trunk/Makefile.am
===================================================================
--- trunk/Makefile.am	(revision 12)
+++ trunk/Makefile.am	(revision 1)
@@ -1,3 +1,3 @@
-# $Id$
+# $Id: Makefile.am 2420 2009-06-24 14:40:21Z lukasz $
 #
 # FedStage DRMAA for PBS Pro
@@ -24,3 +24,3 @@
  m4/missing-dev-prog.sh
 
-SUBDIRS = drmaa_utils pbs_drmaa
+SUBDIRS = drmaa_utils pbs_drmaa  doc
Index: trunk/test/example.c
===================================================================
--- trunk/test/example.c	(revision 51)
+++ trunk/test/example.c	(revision 1)
@@ -1,3 +1,3 @@
-/* $Id$ */
+/* $Id: example.c 2 2009-10-12 09:51:22Z mamonski $ */
 /*
  *  DRMAA library for Torque/PBS
@@ -41,5 +41,5 @@
 #define EXPORT_ENVS   0
 #define DEBUG         1
-#define N_JOBS        8
+#define N_JOBS        1
 
 #define ERR_LEN      DRMAA_ERROR_STRING_BUFFER
@@ -107,7 +107,7 @@
 		printf( "constructing %d\n", i );
 		sprintf( arg, "%d", i );
-		sprintf( job_path, "/bin/sleep" );
+		sprintf( job_path, "./test_job" );
 		argv[0] = job_path;
-		argv[1] = "5";
+		argv[1] = arg;
 		argv[2] = NULL;
 		for( j = 0;  j < 3;  j++ )
@@ -127,5 +127,5 @@
 #endif
 	 }
-#if ! WITH_BULK
+
 	for( i = 0;  i < N_JOBS;  i++ )
 	 {
@@ -145,12 +145,12 @@
 	 }
 
-#else
-	 {
-		char *argv[] = { "/bin/sleep", "5", "$drmaa_incr_ph$", NULL };
+#if WITH_BULK
+	 {
+		char *argv[] = { "./job", "bulk", "$drmaa_incr_ph$", NULL };
 		char *fds[]  = { "b.$drmaa_incr_ph$.stdin", "b.$drmaa_incr_ph$.stdout",
 			"b.$drmaa_incr_ph$.stderr" };
-		bulk_job = construct_job( argv, fds, "." );
-	 }
-	rc = drmaa_run_bulk_jobs( &bulk_job_ids, bulk_job, 1, N_JOBS, 2, err_msg, ERR_LEN );
+		bulk_job = construct_job( argv, fds, WD );
+	 }
+	rc = drmaa_run_bulk_jobs( &bulk_job_ids, bulk_job, 1, N_JOBS, 1, err_msg, ERR_LEN );
 	if( rc )  drmaa_error("drmaa_run_bulk_jobs");
 
@@ -197,5 +197,11 @@
 #endif
 	const char *scalar_attrs[] = {
+		DRMAA_WD            , NULL,
 		DRMAA_REMOTE_COMMAND, NULL,
+		DRMAA_JOB_NAME      , NULL,
+		DRMAA_INPUT_PATH    , NULL,
+		DRMAA_OUTPUT_PATH   , NULL,
+		DRMAA_ERROR_PATH    , NULL,
+                DRMAA_NATIVE_SPECIFICATION, "-l host=eeyore,nodes=1 -W x=FLAGS:ADVRES:usecase.0",
 		NULL                , NULL
 	};
@@ -216,5 +222,10 @@
 	int rc;
 
-	scalar_attrs[ 1] = "/bin/sleep";
+	scalar_attrs[ 1] = cwd;
+	scalar_attrs[ 3] = argv[0];
+	scalar_attrs[ 5] = "jobname";
+	scalar_attrs[ 7] = fds[0];
+	scalar_attrs[ 9] = fds[1];
+	scalar_attrs[11] = fds[2];
 
 	printf( "allocaing template\n" );
Index: trunk/test/Makefile
===================================================================
--- trunk/test/Makefile	(revision 51)
+++ trunk/test/Makefile	(revision 1)
@@ -1,7 +1,3 @@
-all: example wait
-
 example : example.c
-	gcc example.c -o example -ldrmaa -L/opt/drmaa/torque/lib  -I/opt/drmaa/torque/include
-wait : wait.c
-	gcc wait.c -o wait -ldrmaa -L/opt/drmaa/torque/lib -Wl,-R/opt/drmaa/torque/lib -I/opt/drmaa/torque/include
+	gcc example.c -o example -ldrmaa -ldrmaa_base
       
Index: trunk/test/wait.c
===================================================================
--- trunk/test/wait.c	(revision 51)
+++ 	(revision )
@@ -1,91 +1,0 @@
-/* $Id: example.c 49 2011-12-08 07:36:40Z mmamonski $ */
-/*
- *  DRMAA library for Torque/PBS
- *  Copyright (C) 2006-2007
- *
- *  FedStage Systems <http://www.fedstage.com/>,
- *  Poznan Supercomputing and Networking Center <http://www.man.poznan.pl/>,
- *  and the OpenDSP project <http://sourceforge.net/projects/opendsp/>
- *
- *  This library is free software; you can redistribute it and/or
- *  modify it under the terms of the GNU Lesser General Public
- *  License as published by the Free Software Foundation; either
- *  version 2.1 of the License, or (at your option) any later version.
- *
- *  This library 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
- *  Lesser General Public License for more details.
- *
- *  You should have received a copy of the GNU Lesser General Public
- *  License along with this library; if not, write to the Free Software
- *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
- */
-/**
- * @file test.c
- * DRMAA library test / usage example.
- */
-
-#include <drmaa.h>
-
-#include <unistd.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <time.h>
-#include <limits.h>
-#include <errno.h>
-
-
-#define ERR_LEN      DRMAA_ERROR_STRING_BUFFER
-#define JOB_ID_LEN   256
-
-#define errno_error( func ) do{                      \
-	 fprintf( stderr, "%s:%d: %s: %s\n",               \
-			 __FILE__, __LINE__, func, strerror(errno) );  \
-	 exit( 1 );                                        \
- } while(0)
-
-#define drmaa_error( func ) do{                      \
-		fprintf( stderr, "%s:%d: %s: %s\n> %s\n",        \
-				__FILE__, __LINE__, func,                    \
-				drmaa_strerror(rc), err_msg );               \
-		exit(1);                                         \
-	}while(0)
-
-void
-test_1(void);
-
-drmaa_job_template_t *
-construct_job( char *argv[], char *fds[3], const char *cwd );
-
-void
-time_fmt( time_t t, char *buf, size_t buflen );
-
-
-int
-main( int argc, char *argv[] )
-{
-	char err_msg[ ERR_LEN ] = "";
-	char job_id[128] = "";
-	drmaa_attr_values_t *rusage;
-	int rc, stat;
-
-
-	rc = drmaa_init( NULL, err_msg, ERR_LEN );
-	if( rc )  
-		drmaa_error("drmaa_init");
-
-	rc = drmaa_wait( argv[1], job_id, sizeof(job_id), &stat, DRMAA_TIMEOUT_WAIT_FOREVER, &rusage, err_msg, ERR_LEN );
-	if( rc )
-		drmaa_error( "drmaa_job_wait" );
-
-	rc = drmaa_exit( err_msg, ERR_LEN );
-	if( rc )  
-		drmaa_error("drmaa_exit");
-
-	printf( "stat=%d\n", stat );
-
-	return 0;
-}
-
Index: trunk/m4/ax_gperf.m4
===================================================================
--- trunk/m4/ax_gperf.m4	(revision 12)
+++ trunk/m4/ax_gperf.m4	(revision 1)
@@ -1,3 +1,3 @@
-# $Id$
+# $Id: ax_gperf.m4 2420 2009-06-24 14:40:21Z lukasz $
 #
 # SYNOPSIS
@@ -22,5 +22,5 @@
 # LICENSE
 #
-#   Written by Åukasz CieÅnik <lukasz.ciesnik@gmail.com>
+#   Written by Åukasz CieÅnik <lukasz.ciesnik@fedstage.com>
 #   and placed under Public Domain
 #
Index: trunk/m4/ax_gcc_warnings.m4
===================================================================
--- trunk/m4/ax_gcc_warnings.m4	(revision 12)
+++ trunk/m4/ax_gcc_warnings.m4	(revision 1)
@@ -1,3 +1,3 @@
-# $Id$
+# $Id: ax_gcc_warnings.m4 2420 2009-06-24 14:40:21Z lukasz $
 #
 # SYNOPSIS
@@ -7,5 +7,5 @@
 # DESCRIPTION
 #
-#   Check for supported gcc options.
+#   Check for LSF libraries and headers.
 #
 #   This macro calls::
@@ -20,5 +20,5 @@
 # LICENSE
 #
-#   Written by Åukasz CieÅnik <lukasz.ciesnik@gmail.com>
+#   Written by Åukasz CieÅnik <lukasz.ciesnik@fedstage.com>
 #   and placed under Public Domain.
 #
Index: trunk/m4/ax_pbs.m4
===================================================================
--- trunk/m4/ax_pbs.m4	(revision 103)
+++ trunk/m4/ax_pbs.m4	(revision 1)
@@ -1,3 +1,3 @@
-# $Id$
+# $Id: ax_pbs.m4 2420 2009-06-24 14:40:21Z lukasz $
 #
 # SYNOPSIS
@@ -21,8 +21,6 @@
 # LICENSE
 #
-#   Written by Åukasz CieÅnik <lukasz.ciesnik@gmail.com>
-#   and placed under Public Domain. 
-#   
-#   Further contribution: Mariusz Mamonski <mamonski@man.poznan.pl> 
+#   Written by Åukasz CieÅnik <lukasz.ciesnik@fedstage.com>
+#   and placed under Public Domain
 #
 
@@ -30,7 +28,4 @@
 AC_ARG_WITH([pbs], [AC_HELP_STRING([--with-pbs=<pbs-prefix>],
 		[Path to existing PBS installation root])])
-AC_ARG_ENABLE([disable-pbs-log], [AC_HELP_STRING([--disable-pbs-log],
-		[Do not use liblog while linking with PBS Professional])])
-		
 AC_SUBST(PBS_INCLUDES)
 AC_SUBST(PBS_LIBS)
@@ -38,5 +33,4 @@
 
 if test x"$with_pbs" != x; then
-	PBS_HOME=$with_pbs
 	PBS_INCLUDES="-I${with_pbs}/include "
 	PBS_LDFLAGS="-L${with_pbs}/lib "
@@ -47,10 +41,8 @@
 		PBS_HOME=`dirname $T2`
 		PBS_INCLUDES="-I${PBS_HOME}/include "
-		PBS_LDFLAGS="-L${PBS_HOME}/lib "
+        	PBS_LDFLAGS="-L${PBS_HOME}/lib "
 	fi
 fi
 
-
-PBS_INCLUDES="$PBS_INCLUDES -I${PBS_HOME}/include/torque "
 LDFLAGS_save="$LDFLAGS"
 CPPFLAGS_save="$CPPFLAGS"
@@ -61,13 +53,4 @@
 
 AH_TEMPLATE([PBS_PROFESSIONAL], [compiling against PBS Professional])
-AH_TEMPLATE([PBS_PROFESSIONAL_NO_LOG], [Do not use liblog while linking with PBS Professional])
-AH_TEMPLATE([HAVE_PBS_SUBMIT_HASH], [Torque 4 pbs_submit_hash function found])
-
-if test x"$enable_pbs_log" != "xno"; then
-	ax_pbs_lib_log=" -llog"
-else
-	ax_pbs_lib_log=""
-	AC_DEFINE(PBS_PROFESSIONAL_NO_LOG,[1])
-fi
 
 if test x"$ax_pbs_ok" = xno; then
@@ -76,5 +59,5 @@
 	AC_CHECK_LIB([log], [pbse_to_txt], [:], [ax_pbs_ok="no"])
 	if test x"$ax_pbs_ok" = xyes; then
-		ax_pbs_libs="-lpbs $ax_pbs_lib_log"
+		ax_pbs_libs="-lpbs -llog"
 	fi
 fi
@@ -88,9 +71,8 @@
 	AC_CHECK_LIB([log], [pbse_to_txt], [:], [ax_pbs_ok="no"], [-lssl -lcrypto] )
 	if test x"$ax_pbs_ok" = xyes; then
-		ax_pbs_libs="-lpbs $ax_pbs_lib_log -lssl -lcrypto"
+		ax_pbs_libs="-lpbs -llog -lssl -lcrypto"
 	fi
 fi
 
-ax_pbs_submit_hash="no"
 
 if test x"$ax_pbs_ok" = xno; then
@@ -98,18 +80,10 @@
  	AC_CHECK_LIB([torque], [pbs_submit], [:], [ax_pbs_ok="no"])
  	AC_CHECK_LIB([torque], [pbse_to_txt], [:], [ax_pbs_ok="no"])
-	AC_CHECK_LIB([torque], [pbs_submit_hash], [AC_DEFINE(HAVE_PBS_SUBMIT_HASH) ax_pbs_submit_hash="yes"], [:])
-
-
  	if test x"$ax_pbs_ok" = xyes; then
  		ax_pbs_libs="-ltorque"
  	fi
-
-	AM_CONDITIONAL([PBS_PROFESSIONAL], [false])
 else
 	AC_DEFINE(PBS_PROFESSIONAL,[1])
-	AM_CONDITIONAL([PBS_PROFESSIONAL], [true])
 fi
-
-AM_CONDITIONAL([TORQUE4], [test x$ax_pbs_submit_hash = xyes])
 
 if test x"$ax_pbs_ok" = xyes; then
Index: trunk/m4/ax_docutils.m4
===================================================================
--- trunk/m4/ax_docutils.m4	(revision 12)
+++ trunk/m4/ax_docutils.m4	(revision 1)
@@ -1,3 +1,3 @@
-# $Id$
+# $Id: ax_docutils.m4 2420 2009-06-24 14:40:21Z lukasz $
 #
 # SYNOPSIS
Index: trunk/m4/acx_pthread.m4
===================================================================
--- trunk/m4/acx_pthread.m4	(revision 12)
+++ trunk/m4/acx_pthread.m4	(revision 1)
@@ -1,3 +1,3 @@
-dnl $Id$
+dnl $Id: acx_pthread.m4 529 2007-12-20 21:04:22Z lukasz $
 
 dnl
Index: trunk/autoclean.sh
===================================================================
--- trunk/autoclean.sh	(revision 12)
+++ trunk/autoclean.sh	(revision 1)
@@ -1,4 +1,4 @@
 #!/bin/sh
-# $Id$
+# $Id: autoclean.sh 2420 2009-06-24 14:40:21Z lukasz $
 
 echo "Removing all generated files. ($PWD)"
Index: trunk/AUTHORS
===================================================================
--- trunk/AUTHORS	(revision 103)
+++ trunk/AUTHORS	(revision 1)
@@ -1,12 +1,7 @@
-$Id$
+$Id: AUTHORS 746 2008-03-06 15:07:58Z lukasz $
 
 Author:
-	Åukasz CieÅnik <lukasz.ciesnik@gmail.com>
-
-Contributors (also current maintainers):
-       MichaÅ MatÅoka <michal.matloka@student.put.poznan.pl>
-       Mariusz MamoÅski <mamonski@man.poznan.pl>
-	   Piotr Kopta <pkopta@man.poznan.pl>
+	Åukasz CieÅnik <lukasz.ciesnik@fedstage.com>
 
 Send bug reports to:
-      qcg@plgrid.pl 
+	drmaa-pbspro-users@lists.fedstage.com
Index: trunk/ChangeLog
===================================================================
--- trunk/ChangeLog	(revision 103)
+++ trunk/ChangeLog	(revision 1)
@@ -1,10 +1,0 @@
-2015-09-11 Piotr Kopta <pkopta@man.poznan.pl>
-
-	* pbs_drmaa/pbs_attrib_pro.gperf: separate definition for PBS Professional
-	* pbs_drmaa/pbs_conn.c (pbsdrmaa_pbs_statjob): 'x' attribute for pbs_stat (PBS Professional)
-	* pbs_drmaa/job.c (pbsdrmaa_job_update): 'F' job state for PBS Professional
-
-2014-11-27 Piotr Kopta <pkopta@man.poznan.pl>
-
-	* pbs_drmaa/submit.c (parse_addition_attr): changed ';' to ',' as
-	parameter separate character of '-W' arguments
Index: trunk/pbs_drmaa/submit.c
===================================================================
--- trunk/pbs_drmaa/submit.c	(revision 99)
+++ trunk/pbs_drmaa/submit.c	(revision 1)
@@ -1,3 +1,3 @@
-/* $Id$ */
+/* $Id: submit.c 386 2011-01-06 18:13:33Z mamonski $ */
 /*
  *  FedStage DRMAA for PBS Pro
@@ -24,5 +24,4 @@
 #include <unistd.h>
 #include <string.h>
-#include <stdlib.h>
 
 #include <pbs_ifl.h>
@@ -30,5 +29,4 @@
 
 #include <drmaa_utils/conf.h>
-#include <drmaa_utils/exec.h>
 #include <drmaa_utils/drmaa.h>
 #include <drmaa_utils/drmaa_util.h>
@@ -48,17 +46,20 @@
 		__attribute__ ((unused))
 #	endif
-	= "$Id$";
+	= "$Id: submit.c 386 2011-01-06 18:13:33Z mamonski $";
 #endif
 
-static void pbsdrmaa_submit_destroy( pbsdrmaa_submit_t *self );
-
-static char *pbsdrmaa_submit_submit( pbsdrmaa_submit_t *self );
-
-static void pbsdrmaa_submit_eval( pbsdrmaa_submit_t *self );
-
-static void pbsdrmaa_submit_set( pbsdrmaa_submit_t *self, const char *pbs_attr, char *value, unsigned placeholders );
-
-static struct attrl *pbsdrmaa_submit_filter(struct attrl *pbs_attr);
-
+static void
+pbsdrmaa_submit_destroy( pbsdrmaa_submit_t *self );
+
+static char *
+pbsdrmaa_submit_submit( pbsdrmaa_submit_t *self );
+
+static void
+pbsdrmaa_submit_eval( pbsdrmaa_submit_t *self );
+
+
+static void
+pbsdrmaa_submit_set( pbsdrmaa_submit_t *self, const char *pbs_attr,
+		char *value, unsigned placeholders );
 
 static void pbsdrmaa_submit_apply_defaults( pbsdrmaa_submit_t *self );
@@ -100,5 +101,6 @@
 		self->apply_job_environment = pbsdrmaa_submit_apply_job_environment;
 		self->apply_email_notification = pbsdrmaa_submit_apply_email_notification;
-		self->apply_native_specification = pbsdrmaa_submit_apply_native_specification;
+		self->apply_native_specification =
+			pbsdrmaa_submit_apply_native_specification;
 
 		self->pbs_job_attributes = pbsdrmaa_pbs_template_new();
@@ -136,75 +138,63 @@
 pbsdrmaa_submit_submit( pbsdrmaa_submit_t *self )
 {
+	volatile bool conn_lock = false;
 	struct attrl *volatile pbs_attr = NULL;
 	char *volatile job_id = NULL;
 	TRY
 	 {
-		fsd_template_t *pbs_tmpl = self->pbs_job_attributes;
-		int i;
-
-		for( i = PBSDRMAA_N_PBS_ATTRIBUTES - 1; i >= 0; i-- ) /* down loop -> start with custom resources */
+		const fsd_template_t *pbs_tmpl = self->pbs_job_attributes;
+		unsigned i;
+
+		for( i = 0;  i < PBSDRMAA_N_PBS_ATTRIBUTES;  i++ )
 		 {
 			const char *name = pbs_tmpl->by_code( pbs_tmpl, i )->name;
-			const char *value = pbs_tmpl->get_attr( pbs_tmpl, name );
-
-			if (!value)
-				continue;
-
-			if ( i == PBSDRMAA_ATTR_CUSTOM_RESOURCES)
+			if( name  &&  name[0] != '!' && pbs_tmpl->get_attr( pbs_tmpl, name ) )
 			 {
-				char *value_copy = fsd_strdup(value);
-				char *tok_comma_ctx = NULL;
-				char *res_token = NULL;
-				/* matlab:2,simulink:1 */
-
-				for (res_token = strtok_r(value_copy, ";", &tok_comma_ctx); res_token; res_token = strtok_r(NULL, ";", &tok_comma_ctx))
+				struct attrl *p;
+				const char *resource;
+				const char *value;
+				value = pbs_tmpl->get_attr( pbs_tmpl, name );
+				fsd_malloc( p, struct attrl );
+				memset( p, 0, sizeof(struct attrl) );
+				p->next = pbs_attr;
+				pbs_attr = p;
+				resource = strchr( name, '.' );
+				if( resource )
 				 {
-					char *value_p = strstr(res_token, ":");
-
-					if (value_p)
-					 {
-						char *name_p = NULL;
-						*value_p = '\0';
-						value_p++;
-						name_p = fsd_asprintf("Resource_List.%s",res_token);
-						pbs_attr = pbsdrmaa_add_attr( pbs_attr, name_p, value_p );
-						fsd_free(name_p);
-					 }
-					else
-					 {
-						fsd_exc_raise_code( FSD_DRMAA_ERRNO_INVALID_ATTRIBUTE_VALUE );
-					 }
-				 }
-
-				fsd_free(value_copy);
-			 }
-			else if (i == PBSDRMAA_ATTR_NODE_PROPERTIES)
-			 {
-				const char *nodes_value = pbs_tmpl->get_attr( pbs_tmpl, PBSDRMAA_NODES );
-				char *final_value = NULL;
-
-				if (nodes_value)
-				 {
-					final_value = fsd_asprintf("%s:%s",nodes_value, value);
+					p->name = fsd_strndup( name, resource-name );
+					p->resource = fsd_strdup( resource+1 );
 				 }
 				else
-				 {
-					final_value = fsd_asprintf("1:%s", value);
-				 }
-
-				pbs_tmpl->set_attr( pbs_tmpl, PBSDRMAA_NODES, final_value);
-				fsd_free(final_value);
+					p->name = fsd_strdup( name );
+				fsd_log_debug(("set attr: %s = %s", name, value));
+				p->value = fsd_strdup( value );
+				p->op = SET;
+			 }
+		 }
+
+		conn_lock = fsd_mutex_lock( &self->session->drm_connection_mutex );
+retry:
+		job_id = pbs_submit( ((pbsdrmaa_session_t*)self->session)->pbs_conn,
+				(struct attropl*)pbs_attr, self->script_filename,
+				self->destination_queue, NULL );
+		if( job_id == NULL )
+		{
+			if (pbs_errno == PBSE_PROTOCOL || pbs_errno == PBSE_EXPIRED)
+			 {
+				pbsdrmaa_session_t *pbsself = (pbsdrmaa_session_t*)self->session;
+				pbs_disconnect( pbsself->pbs_conn );
+				sleep(1);
+				pbsself->pbs_conn = pbs_connect( pbsself->super.contact );
+				if( pbsself->pbs_conn < 0 )
+					pbsdrmaa_exc_raise_pbs( "pbs_connect" );
+				else
+					goto retry;
 			 }
 			else
 			 {
-				pbs_attr = pbsdrmaa_add_attr( pbs_attr, name, value );
+				pbsdrmaa_exc_raise_pbs( "pbs_submit" );
 			 }
-		 }
-
-
-		pbs_attr = pbsdrmaa_submit_filter(pbs_attr);
-
-		job_id = ((pbsdrmaa_session_t *)self->session)->pbs_connection->submit( ((pbsdrmaa_session_t *)self->session)->pbs_connection, (struct attropl*)pbs_attr, self->script_filename, self->destination_queue);
-
+		}
+		conn_lock = fsd_mutex_unlock( &self->session->drm_connection_mutex );
 	 }
 	EXCEPT_DEFAULT
@@ -215,4 +205,6 @@
 	FINALLY
 	 {
+		if( conn_lock )
+			conn_lock = fsd_mutex_unlock( &self->session->drm_connection_mutex );
 		if( pbs_attr )
 			pbsdrmaa_free_attrl( pbs_attr );
@@ -309,6 +301,5 @@
 		if( wd != NULL )
 			script_len += strlen("cd ") + strlen(wd) + strlen("; ");
-		script_len += strlen("touch ") + strlen(((pbsdrmaa_session_t *)self->session)->job_exit_status_file_prefix) + strlen("/$PBS_JOBID.started;");
-		script_len += strlen(executable);
+		script_len += strlen("exec ") + strlen(executable);
 		if( argv != NULL )
 			for( i = argv;  *i != NULL;  i++ )
@@ -316,6 +307,4 @@
 		if( input_path != NULL )
 			script_len += strlen(" <") + strlen(input_path);
-
-		script_len += strlen(";EXIT_CODE=$?; echo $EXIT_CODE >") + strlen(((pbsdrmaa_session_t *)self->session)->job_exit_status_file_prefix) + strlen("/$PBS_JOBID.exitcode; exit $EXIT_CODE");
 	 }
 
@@ -327,6 +316,5 @@
 		if( wd != NULL )
 			s += sprintf( s, "cd %s; ", wd );
-		s += sprintf( s, "touch %s/$PBS_JOBID.started;", ((pbsdrmaa_session_t *)self->session)->job_exit_status_file_prefix);
-		s += sprintf( s, "%s", executable );
+		s += sprintf( s, "exec %s", executable );
 		if( argv != NULL )
 			for( i = argv;  *i != NULL;  i++ )
@@ -334,7 +322,4 @@
 		if( input_path != NULL )
 			s += sprintf( s, " <%s", input_path );
-
-		s += sprintf( s, ";EXIT_CODE=$?; echo $EXIT_CODE >%s/$PBS_JOBID.exitcode; exit $EXIT_CODE", ((pbsdrmaa_session_t *)self->session)->job_exit_status_file_prefix);
-
 		fsd_assert( s == script+script_len );
 	 }
@@ -407,4 +392,5 @@
 	fsd_template_t *pbs_attr = self->pbs_job_attributes;
 	const char *join_files;
+	bool b_join_files;
 	int i;
 
@@ -436,13 +422,6 @@
 
 	join_files = jt->get_attr( jt, DRMAA_JOIN_FILES );
-	if (join_files != NULL && strcmp(join_files, "y") == 0)
-	  {
-		pbs_attr->set_attr( pbs_attr, PBSDRMAA_JOIN_FILES, "oe" ); 
-	  }
-        else if (join_files != NULL && strcmp(join_files, "n") != 0)
-          {
-		fsd_exc_raise_fmt( FSD_ERRNO_INVALID_VALUE, "invalid value of %s attribute. Should be 'y' or 'n'.",
-					DRMAA_JOIN_FILES );
-          }
+	b_join_files = join_files != NULL  &&  !strcmp(join_files,"1");
+	pbs_attr->set_attr( pbs_attr, PBSDRMAA_JOIN_FILES, (b_join_files ? "y" : "n") ); 
 }
 
@@ -474,6 +453,4 @@
 }
 
-
-
 void
 pbsdrmaa_submit_apply_job_environment( pbsdrmaa_submit_t *self )
@@ -481,38 +458,21 @@
 	const fsd_template_t *jt = self->job_template;
 	const char *const *env_v;
-	const char *jt_wd;
-	char *wd;
-	char *env_c = NULL;
-	int ii = 0, len = 0;
 
 	env_v = jt->get_v_attr( jt, DRMAA_V_ENV);
-	jt_wd    = jt->get_attr( jt, DRMAA_WD );
-	
-	if (!jt_wd)
+
+	if (env_v)
 	{
-		wd = fsd_getcwd();
-	}
-	else
-	{
-		wd = fsd_strdup(jt_wd);
-	}
-
-	if (env_v)
-	 {
+		char *env_c = NULL;
+		int ii = 0, len = 0;
+
 		ii = 0;
-		while (env_v[ii])
-		 {
+		while (env_v[ii]) {
 			len += strlen(env_v[ii]) + 1;
 			ii++;
-		 }
-	 }
-	
-	len+= strlen("PBS_O_WORKDIR=") + strlen(wd);
-
-	fsd_calloc(env_c, len + 1, char);
-	env_c[0] = '\0';
-
-	if (env_v)
-	{
+		}
+
+		fsd_calloc(env_c, len + 1, char);
+		env_c[0] = '\0';
+
 		ii = 0;
 		while (env_v[ii]) {
@@ -522,13 +482,10 @@
 		}
 
+		env_c[strlen(env_c) -1 ] = '\0'; /*remove the last ',' */
+
+		self->pbs_job_attributes->set_attr(self->pbs_job_attributes, "Variable_List", env_c);
+
+		fsd_free(env_c);
 	}
-	
-	strcat(env_c, "PBS_O_WORKDIR=");
-	strcat(env_c, wd);
-
-	self->pbs_job_attributes->set_attr(self->pbs_job_attributes, "Variable_List", env_c);
-
-	fsd_free(env_c);
-	fsd_free(wd);
 }
 
@@ -560,24 +517,5 @@
 }
 
-static const char *get_job_env(pbsdrmaa_submit_t *self, const char *env_name)
-{
-	const fsd_template_t *jt = self->job_template;
-	const char *const *env_v = jt->get_v_attr( jt, DRMAA_V_ENV);
-	int ii = 0;
-
-	while (env_v[ii])
-	 {
-		char *eq_p = strstr(env_v[ii], "=");
-
-		if ((eq_p) && (strncmp(env_v[ii], env_name, eq_p - env_v[ii]) == 0))
-				return ++eq_p;
-
-		ii++;
-	 }
-
-	return NULL;
-}
-
-static void parse_resources(pbsdrmaa_submit_t *self, fsd_template_t *pbs_attr,const char *resources)
+static void parse_resources(fsd_template_t *pbs_attr,const char *resources)
 {
 	char * volatile name = NULL;
@@ -598,8 +536,5 @@
 				name = fsd_asprintf("Resource_List.%s", arg);
 				value = ++psep;
-				if (value[0] == '$' && get_job_env(self, value + 1))
-					pbs_attr->set_attr( pbs_attr, name , get_job_env(self, value + 1) ); /*get value from job env variable */
-				else
-					pbs_attr->set_attr( pbs_attr, name , value );
+				pbs_attr->set_attr( pbs_attr, name , value );
 				fsd_free(name);
 				name = NULL;
@@ -607,5 +542,6 @@
 			else
 			{
-				fsd_exc_raise_fmt(FSD_DRMAA_ERRNO_INVALID_ATTRIBUTE_VALUE, "Invalid native specification: %s (Invalid resource specification: %s)", resources, arg);
+                                fsd_exc_raise_fmt(FSD_DRMAA_ERRNO_INVALID_ATTRIBUTE_VALUE, "Invalid native specification: %s (Invalid resource specification: %s)", resources, arg);
+
 			}
 		}
@@ -629,5 +565,5 @@
 	TRY
 	  {
-		for (arg = strtok_r(add_attr_copy, ",", &ctxt); arg; arg = strtok_r(NULL, ",",&ctxt) )
+		for (arg = strtok_r(add_attr_copy, ",", &ctxt); arg; arg = strtok_r(NULL, ":",&ctxt) )
 		{
 			name = fsd_strdup(strtok_r(arg, "=", &ctxt2));
@@ -651,6 +587,4 @@
 		const char *native_specification )
 {
-	fsd_log_enter(( "({native_specification=%s})", native_specification ));
-
 	if( native_specification == NULL )
 		native_specification = self->job_template->get_attr(
@@ -660,4 +594,5 @@
 
 	{
+		fsd_iter_t * volatile args_list = fsd_iter_new(NULL, 0);
 		fsd_template_t *pbs_attr = self->pbs_job_attributes;
 		char *arg = NULL;
@@ -667,29 +602,19 @@
 
 		TRY
-		  {
-			for (arg = strtok_r((char *)native_spec_copy, " \t", &ctxt); arg; arg = strtok_r(NULL, " \t",&ctxt) ) {
-				if (!opt)
-				  {
-					if ( (arg[0] != '-') || (strlen(arg) != 2) )
+		 {
+			for (arg = strtok_r(native_spec_copy, " \t", &ctxt); arg; arg = strtok_r(NULL, " \t",&ctxt) ) {
+				if (!opt) {
+					if ( (arg[0] != '-') || ((strlen(arg) != 2) &&  arg[2] != ' ' && arg[1] !='-' ) )
 						fsd_exc_raise_fmt(FSD_DRMAA_ERRNO_INVALID_ATTRIBUTE_VALUE,
-							"Invalid native specification: -o(ption) expected (arg=%s native=%s).",
-							arg, native_specification);
-
-					opt = arg[1];
-
-					/* handle NO-arg options */
-
-					switch (opt) {
-						case 'h' :
-							pbs_attr->set_attr( pbs_attr, "Hold_Types" , "u" );
-							break;
-						default :
-							continue; /*no NO-ARG option */
+								"Invalid native specification: %s",
+								native_specification);
+					if(arg[1] == '-') {
+						parse_additional_attr(pbs_attr, arg+2);
 					}
-
-					opt = 0;
-				  }
-				else
-				  {
+					else {
+						opt = arg[1];
+					}
+					
+				} else {
 					switch (opt) {
 						
@@ -715,4 +640,7 @@
 							pbs_attr->set_attr( pbs_attr, "Execution_Time" , arg );
 							break;
+						case 'h' :
+							pbs_attr->set_attr( pbs_attr, "Hold_Types" , arg );
+							break;
 						case 'A' :
 							pbs_attr->set_attr( pbs_attr, "Account_Name" , arg );
@@ -728,9 +656,5 @@
 							break;
 						case 'q' :
-							if (self->destination_queue)
-								fsd_free(self->destination_queue);
-
 							self->destination_queue = fsd_strdup( arg );
-							fsd_log_debug(("self->destination_queue = %s", self->destination_queue));
 							break;
 						case 'r' :
@@ -744,4 +668,5 @@
 							break;
 						case 'v' :
+						case 'V' :
 							pbs_attr->set_attr( pbs_attr, "Variable_List" , arg );
 							break;
@@ -750,5 +675,5 @@
 							break;
 						case 'l' :
-							parse_resources( self, pbs_attr, arg);
+							parse_resources(pbs_attr, arg);
 							break;							
 						default :
@@ -758,4 +683,5 @@
 									native_specification, opt);
 					}
+
 					opt = 0;
 				}
@@ -766,4 +692,5 @@
 						"Invalid native specification: %s",
 						native_specification);
+
 		 }
 		FINALLY
@@ -772,5 +699,6 @@
 			pbs_attr->set_attr( pbs_attr, "submit_args", native_specification);
 #endif
-			fsd_free((char *)native_spec_copy);
+			args_list->destroy(args_list);
+			fsd_free(native_spec_copy);
 		 }
 		END_TRY
@@ -778,99 +706,2 @@
 }
 
-struct attrl *
-pbsdrmaa_submit_filter(struct attrl *pbs_attr)
-{
-	fsd_log_enter(( "({pbs_attr=%p})", (void*)pbs_attr));
-
-	if (getenv(PBSDRMAA_SUBMIT_FILTER_ENV) == NULL) 
-	  {
-		return pbs_attr;
-	  } 
-	else 
-	  {
-		struct attrl *ii = NULL;
-		char *empty_args[] = { NULL };
-		int exit_status = -1;
-		const char *submit_filter = getenv(PBSDRMAA_SUBMIT_FILTER_ENV);
-		char *stdin_buf = NULL;
-		int stdin_size = 0;
-		char *stdout_buf = NULL;
-		char *stderr_buf = NULL;
-		char *output_line = NULL;
-		char *ctx = NULL;
-
-		fsd_log_debug(("Executing filter script: %s", submit_filter));
-		
-		
-		for (ii = pbs_attr; ii; ii = ii->next) 
-		  {
-			stdin_size += strlen(ii->name) + strlen(ii->value) + 2 /* '=' and '\n' */;
-			if (ii->resource)
-			  {
-				stdin_size += strlen(ii->resource) +  1; /* '.' */
-			  }
-		  }
-
-		stdin_size+=1; /* '\0' */
-
-		stdin_buf = fsd_calloc(stdin_buf, stdin_size, char);
-		stdin_buf[0] = '\0';
-
-		for (ii = pbs_attr; ii; ii = ii->next) 
-		  {
-			strcat(stdin_buf, ii->name);
-			if (ii->resource)
-			  {
-				strcat(stdin_buf, ".");
-				strcat(stdin_buf, ii->resource);
-			  }
-			strcat(stdin_buf, "=");
-			strcat(stdin_buf, ii->value);
-			strcat(stdin_buf, "\n");
-		  }
-		
-		exit_status = fsd_exec_sync(submit_filter, empty_args, stdin_buf, &stdout_buf, &stderr_buf);
-    fsd_free(stdin_buf);
-
-		if (exit_status != 0)
-		  {
-			fsd_log_error(("Filter script %s exited with non-zero code: %d", submit_filter, exit_status));
-			fsd_exc_raise_fmt(FSD_DRMAA_ERRNO_INVALID_ATTRIBUTE_VALUE, "Submit filter script failed (code: %d, message: %s)", exit_status, stderr_buf);
-		  }
-		
-		fsd_log_debug(("Submit filter exit_status=%d, stderr=%s", exit_status, stderr_buf));
-
-		pbsdrmaa_free_attrl(pbs_attr);
-		pbs_attr = NULL;
-
-		/* exit_status == 0 */
-		for (output_line = strtok_r(stdout_buf, "\n", &ctx);  output_line ; output_line = strtok_r(NULL, "\n", &ctx))
-		  {
-			char *attr_name = NULL;
-			char *attr_value = NULL;
-
-			attr_value = strstr(output_line,"=");
-			attr_name = output_line;
-
-			if (!attr_value)
-			  {
-				fsd_exc_raise_fmt(FSD_DRMAA_ERRNO_INVALID_ATTRIBUTE_FORMAT, "Invalid output line of submit filter: %s", output_line);
-			  }
-			else
-			  {
-				*attr_value = '\0';
-				attr_value++; 
-			  }
-			
-
-			pbs_attr = pbsdrmaa_add_attr( pbs_attr, attr_name, attr_value );
-      }
-
-	  fsd_free(stdout_buf);
-    fsd_free(stderr_buf);	
-
-		return pbs_attr;
-	  }
-
-}
-
Index: trunk/pbs_drmaa/submit.h
===================================================================
--- trunk/pbs_drmaa/submit.h	(revision 72)
+++ trunk/pbs_drmaa/submit.h	(revision 1)
@@ -1,3 +1,3 @@
-/* $Id$ */
+/* $Id: submit.h 338 2010-09-28 14:48:45Z mamonski $ */
 /*
  *  FedStage DRMAA for PBS Pro
@@ -28,6 +28,4 @@
 
 typedef struct pbsdrmaa_submit_s pbsdrmaa_submit_t;
-
-#define PBSDRMAA_SUBMIT_FILTER_ENV "PBSDRMAA_SUBMIT_FILTER"
 
 pbsdrmaa_submit_t *
Index: trunk/pbs_drmaa/job.c
===================================================================
--- trunk/pbs_drmaa/job.c	(revision 103)
+++ trunk/pbs_drmaa/job.c	(revision 1)
@@ -1,3 +1,3 @@
-/* $Id$ */
+/* $Id: job.c 370 2010-11-16 09:51:00Z mamonski $ */
 /*
  *  FedStage DRMAA for PBS Pro
@@ -26,5 +26,4 @@
 #include <string.h>
 #include <unistd.h>
-#include <sys/stat.h>
 
 #include <drmaa_utils/drmaa.h>
@@ -34,5 +33,4 @@
 
 #include <pbs_drmaa/job.h>
-#include <pbs_drmaa/log_reader.h>
 #include <pbs_drmaa/pbs_attrib.h>
 #include <pbs_drmaa/session.h>
@@ -44,19 +42,20 @@
 		__attribute__ ((unused))
 #	endif
-	= "$Id$";
+	= "$Id: job.c 370 2010-11-16 09:51:00Z mamonski $";
 #endif
 
 
-static void pbsdrmaa_job_control( fsd_job_t *self, int action );
-
-static void pbsdrmaa_job_update_status( fsd_job_t *self );
-
-static void pbsdrmaa_job_on_missing( fsd_job_t *self );
-
-static void pbsdrmaa_job_on_missing_standard( fsd_job_t *self );
-
-static void pbsdrmaa_job_update( fsd_job_t *self, struct batch_status* );
-
-static int pbsdrmaa_job_read_exit_status( const char *job_id, const char *job_state_dir_prefix);
+static void
+pbsdrmaa_job_control( fsd_job_t *self, int action );
+
+static void
+pbsdrmaa_job_update_status( fsd_job_t *self );
+
+static void
+pbsdrmaa_job_on_missing( fsd_job_t *self );
+
+static void
+pbsdrmaa_job_update( fsd_job_t *self, struct batch_status* );
+
 
 fsd_job_t *
@@ -68,5 +67,4 @@
 	self->super.update_status = pbsdrmaa_job_update_status;
 	self->super.on_missing = pbsdrmaa_job_on_missing;
-	self->missing_time = 0;
 	self->update = pbsdrmaa_job_update;
 	return (fsd_job_t*)self;
@@ -77,40 +75,93 @@
 pbsdrmaa_job_control( fsd_job_t *self, int action )
 {
+	volatile bool conn_lock = false;
 	pbsdrmaa_session_t *session = (pbsdrmaa_session_t*)self->session;
 	const char *job_id = self->job_id;
-
-	fsd_log_enter(( "({job_id=%s}, action=%d)", self->job_id, action ));
-
-	switch( action )
-	 {
-		/*
-		 * We cannot know whether we did suspend job
-		 * in other way than remembering this inside DRMAA session.
-		 */
-		case DRMAA_CONTROL_SUSPEND:
-			session->pbs_connection->sigjob( session->pbs_connection, (char*)job_id, "SIGSTOP");
-			self->flags |= FSD_JOB_SUSPENDED;
-			break;
-		case DRMAA_CONTROL_RESUME:
-			session->pbs_connection->sigjob( session->pbs_connection, (char*)job_id, "SIGCONT");
-			self->flags &= ~FSD_JOB_SUSPENDED;
-			break;
-		case DRMAA_CONTROL_HOLD:
-			session->pbs_connection->holdjob( session->pbs_connection, (char*)job_id );
-			self->flags |= FSD_JOB_HOLD;
-			break;
-		case DRMAA_CONTROL_RELEASE:
-			session->pbs_connection->rlsjob( session->pbs_connection, (char*)job_id );
-			self->flags &= ~FSD_JOB_HOLD;
-			break;
-		case DRMAA_CONTROL_TERMINATE:
-			session->pbs_connection->deljob( session->pbs_connection, (char*)job_id );
-			/* TODO: make deldelay configurable ???:
-			 * deldelay=N -- delay between SIGTERM and SIGKILL (default 0) */
-			self->flags &= FSD_JOB_TERMINATED_MASK;
-			if( (self->flags & FSD_JOB_TERMINATED) == 0 )
-				self->flags |= FSD_JOB_TERMINATED | FSD_JOB_ABORTED;
-			break;
-	 }
+	const char *apicall = NULL;
+	int rc = PBSE_NONE;
+
+	fsd_log_enter(( "({job_id=%s}, action=%d)",
+			self->job_id, action ));
+
+	TRY
+	 {
+		int try_count;
+		const int max_tries = 3;
+
+		conn_lock = fsd_mutex_lock( &self->session->drm_connection_mutex );
+
+		/*TODO reconnect */
+		for( try_count=0;  try_count < max_tries;  try_count++ )
+		 {
+			switch( action )
+			 {
+				/*
+				 * We cannot know whether we did suspend job
+				 * in other way than remembering this inside DRMAA session.
+				 */
+				case DRMAA_CONTROL_SUSPEND:
+					apicall = "pbs_sigjob";
+					rc = pbs_sigjob( session->pbs_conn, (char*)job_id,
+							"SIGSTOP", NULL );
+					if( rc == PBSE_NONE )
+						self->flags |= FSD_JOB_SUSPENDED;
+					break;
+				case DRMAA_CONTROL_RESUME:
+					apicall = "pbs_sigjob";
+					rc = pbs_sigjob( session->pbs_conn, (char*)job_id,
+							"SIGCONT", NULL );
+					if( rc == PBSE_NONE )
+						self->flags &= ~FSD_JOB_SUSPENDED;
+					break;
+				case DRMAA_CONTROL_HOLD:
+					apicall = "pbs_holdjob";
+					rc = pbs_holdjob( session->pbs_conn, (char*)job_id,
+							USER_HOLD, NULL );
+					if( rc == PBSE_NONE )
+						self->flags |= FSD_JOB_HOLD;
+					break;
+				case DRMAA_CONTROL_RELEASE:
+					apicall = "pbs_rlsjob";
+					rc = pbs_rlsjob( session->pbs_conn, (char*)job_id,
+							USER_HOLD, NULL );
+					if( rc == PBSE_NONE )
+						self->flags &= FSD_JOB_HOLD;
+					break;
+				case DRMAA_CONTROL_TERMINATE:
+					apicall = "pbs_deljob";
+					rc = pbs_deljob( session->pbs_conn, (char*)job_id, NULL );
+					/* Torque:
+					 * deldelay=N -- delay between SIGTERM and SIGKILL (default 0) */
+					if( rc == PBSE_NONE )
+					 {
+						self->flags &= FSD_JOB_TERMINATED_MASK;
+						if( (self->flags & FSD_JOB_TERMINATED) == 0 )
+							self->flags |= FSD_JOB_TERMINATED | FSD_JOB_ABORTED;
+					 }
+					break;
+			 }
+
+			if( rc == PBSE_NONE )
+				break;
+			else if( rc == PBSE_INTERNAL )
+			 {
+				/*
+				 * In PBS Pro pbs_sigjob raises internal server error (PBSE_INTERNAL)
+				 * when job just changed its state to running.
+				 */
+				fsd_log_debug(( "repeating request (%d of %d)",
+							try_count+2, max_tries ));
+				sleep( 1 );
+			 }
+			else
+				pbsdrmaa_exc_raise_pbs( apicall );
+		 } /* end for */
+	 }
+	FINALLY
+	 {
+		if( conn_lock )
+			conn_lock = fsd_mutex_unlock( &self->session->drm_connection_mutex );
+	 }
+	END_TRY
 
 	fsd_log_return((""));
@@ -121,17 +172,53 @@
 pbsdrmaa_job_update_status( fsd_job_t *self )
 {
+	volatile bool conn_lock = false;
 	struct batch_status *volatile status = NULL;
 	pbsdrmaa_session_t *session = (pbsdrmaa_session_t*)self->session;
 
 	fsd_log_enter(( "({job_id=%s})", self->job_id ));
-	
 	TRY
 	 {
-
+		conn_lock = fsd_mutex_lock( &self->session->drm_connection_mutex );
+retry:
 #ifdef PBS_PROFESSIONAL
-		status = session->pbs_connection->statjob( session->pbs_connection, self->job_id, NULL);
+		status = pbs_statjob( session->pbs_conn, self->job_id, NULL, NULL );
 #else
-		status = session->pbs_connection->statjob( session->pbs_connection, self->job_id, session->status_attrl);
+		status = pbs_statjob( session->pbs_conn, self->job_id, session->status_attrl, NULL );
 #endif
+		fsd_log_debug(( "pbs_statjob(fd=%d, job_id=%s, attribs={...}) =%p",
+				 session->pbs_conn, self->job_id, (void*)status ));
+		if( status == NULL )
+		 {
+#ifndef PBS_PROFESSIONAL
+			fsd_log_error(("pbs_statjob error: %d, %s, %s", pbs_errno, pbse_to_txt(pbs_errno), pbs_strerror(pbs_errno)));
+#else
+			fsd_log_error(("pbs_statjob error: %d, %s", pbs_errno, pbse_to_txt(pbs_errno)));
+#endif
+			switch( pbs_errno )
+			 {
+				case PBSE_UNKJOBID:
+					break;
+				case PBSE_PROTOCOL:
+				case PBSE_EXPIRED:
+					pbs_disconnect( session->pbs_conn );
+					sleep(1);
+					session->pbs_conn = pbs_connect( session->super.contact );
+					if( session->pbs_conn < 0 )
+						pbsdrmaa_exc_raise_pbs( "pbs_connect" );
+					else 
+					 {
+						fsd_log_error(("retry:"));
+						goto retry;
+					 }
+				default:
+					pbsdrmaa_exc_raise_pbs( "pbs_statjob" );
+					break;
+				case 0:  /* ? */
+					fsd_exc_raise_code( FSD_ERRNO_INTERNAL_ERROR );
+					break;
+			 }
+		 }
+
+		conn_lock = fsd_mutex_unlock( &self->session->drm_connection_mutex );
 
 		if( status != NULL )
@@ -139,13 +226,13 @@
 			((pbsdrmaa_job_t*)self)->update( self, status );
 		 }
-		else if( self->state < DRMAA_PS_DONE )
-		 {
+		else
 			self->on_missing( self );
-		 }
 	 }
 	FINALLY
 	 {
+		if( conn_lock )
+			conn_lock = fsd_mutex_unlock( &self->session->drm_connection_mutex );
 		if( status != NULL )
-			session->pbs_connection->statjob_free( session->pbs_connection, status );
+			pbs_statfree( status );
 	 }
 	END_TRY
@@ -161,5 +248,5 @@
 	struct attrl *i = NULL;
 	char pbs_state = 0;
-	int exit_status = -101;
+	int exit_status = -2;
 	const char *cpu_usage = NULL;
 	const char *mem_usage = NULL;
@@ -184,5 +271,5 @@
 				break;
 			case PBSDRMAA_ATTR_EXIT_STATUS:
-				exit_status = fsd_atoi( i->value );
+				exit_status = atoi( i->value );
 				break;
 			case PBSDRMAA_ATTR_RESOURCES_USED:
@@ -204,5 +291,4 @@
 					self->project = fsd_strdup(i->value);
 				break;
-#ifndef PBS_PROFESSIONAL
 			case PBSDRMAA_ATTR_EXECUTION_HOST:
 				if (!self->execution_hosts) {
@@ -211,12 +297,4 @@
 				}
 				break;
-#else
-			case PBSDRMAA_ATTR_EXECUTION_VNODE:
-				if (!self->execution_hosts) {
-					fsd_log_debug(("execution_hosts = %s", i->value));
-					self->execution_hosts = fsd_strdup(i->value);
-				}
-				break;
-#endif
 			case PBSDRMAA_ATTR_START_TIME:
 				{
@@ -236,15 +314,8 @@
 		fsd_log_debug(( "pbs_state: %c", pbs_state ));
 
-	if( exit_status != -101 )
+	if( exit_status != -2 )
 	 {
 		fsd_log_debug(( "exit_status: %d", exit_status ));
 		self->exit_status = exit_status;
-
-		if (self->exit_status < 0)
-		 {
-			self->exit_status = -1;
-			fsd_log_error(("ExitStatus = %d, probably system problem, report job %s to the local administrator", exit_status, self->job_id));
-		 }
-
 	 }
 	if(pbs_state){
@@ -252,10 +323,7 @@
 		 {
 			case 'C': /* Job is completed after having run. */
-#ifdef PBS_PROFESSIONAL
-			case 'F': /* Job is completed after having run. */
-#endif
 				self->flags &= FSD_JOB_TERMINATED_MASK;
 				self->flags |= FSD_JOB_TERMINATED;
-				if (exit_status != -101) { /* has exit code */
+				if (exit_status != -2) { /* has exit code */
 					if( self->exit_status == 0) 
 						self->state = DRMAA_PS_DONE;
@@ -266,12 +334,5 @@
 					self->exit_status = -1;
 				}
-				if (modify_time != 0)
-					self->end_time = modify_time; /* take last modify time as end time */
-				else
-					self->end_time = time(NULL);
-				
-				if (self->start_time == 0)
-					self->start_time = self->end_time;
-
+				self->end_time = modify_time; /* take last modify time as end time */
 				break;
 			case 'E': /* Job is exiting after having run. - MM: ignore exiting state (transient state) - outputs might have not been transfered yet, 
@@ -311,5 +372,6 @@
 		int hours, minutes, seconds;
 		long mem;
-		if( cpu_usage && sscanf( cpu_usage, "%d:%d:%d", &hours, &minutes, &seconds ) == 3 )
+		if( cpu_usage && sscanf( cpu_usage, "%d:%d:%d",
+				&hours, &minutes, &seconds ) == 3 )
 		 {
 			self->cpu_usage = 60*( 60*hours + minutes ) + seconds;
@@ -326,5 +388,6 @@
 			fsd_log_debug(( "vmem_usage: %s=%ldB", vmem_usage, self->vmem_usage ));
 		 }
-		if( walltime && sscanf( walltime, "%d:%d:%d", &hours, &minutes, &seconds ) == 3 )
+		if( walltime && sscanf( walltime, "%d:%d:%d",
+					&hours, &minutes, &seconds ) == 3 )
 		 {
 			self->walltime = 60*( 60*hours + minutes ) + seconds;
@@ -333,98 +396,54 @@
 	 }
 }
+
 
 void
 pbsdrmaa_job_on_missing( fsd_job_t *self )
 {
-	pbsdrmaa_session_t *pbssession = (pbsdrmaa_session_t*)self->session;
-	pbsdrmaa_job_t *pbsself = (pbsdrmaa_job_t *)self;
-	
-	if (!pbsself->missing_time)
-	 {
-		pbsself->missing_time = time(NULL);
-	 }
-
-	fsd_log_info(("pbsdrmaa_job_on_missing: pbs_home=%s, wait_thread_started=%d, submit_time=%d, missing_time=%d", 
-		pbssession->pbs_home, 
-		pbssession->super.wait_thread_started, 
-		(int)self->submit_time, 
-		(int)pbsself->missing_time));
-	
-	#define DRMAA_MAX_MISSING_TIME (30)
-	if( pbssession->pbs_home != NULL && pbssession->super.wait_thread_started && self->submit_time && (time(NULL) - pbsself->missing_time < DRMAA_MAX_MISSING_TIME))
-		fsd_log_info(("Job on missing but WT is running. Skipping...")); /* TODO: try to provide implementation that uses accounting/server log files */
+	fsd_drmaa_session_t *session = self->session;
+	pbsdrmaa_session_t *pbssession = (pbsdrmaa_session_t*)session;
+	if( !pbssession->wait_thread_log){	
+	unsigned missing_mask = 0;
+
+	fsd_log_enter(( "({job_id=%s})", self->job_id ));
+	fsd_log_warning(( "self %s missing from DRM queue", self->job_id ));
+
+	switch( session->missing_jobs )
+	 {
+		case FSD_REVEAL_MISSING_JOBS:         missing_mask = 0;     break;
+		case FSD_IGNORE_MISSING_JOBS:         missing_mask = 0x73;  break;
+		case FSD_IGNORE_QUEUED_MISSING_JOBS:  missing_mask = 0x13;  break;
+	 }
+	fsd_log_debug(( "last job_ps: %s (0x%02x); mask: 0x%02x",
+				drmaa_job_ps_to_str(self->state), self->state, missing_mask ));
+
+	if( self->state < DRMAA_PS_DONE
+			&&  (self->state & ~missing_mask) )
+		fsd_exc_raise_fmt(
+				FSD_ERRNO_INTERNAL_ERROR,
+				"self %s missing from queue", self->job_id
+				);
+
+	if( (self->flags & FSD_JOB_TERMINATED_MASK) == 0 )
+	 {
+		self->flags &= FSD_JOB_TERMINATED_MASK;
+		self->flags |= FSD_JOB_TERMINATED;
+	 }
+
+	if( (self->flags & FSD_JOB_ABORTED) == 0
+			&&  session->missing_jobs == FSD_IGNORE_MISSING_JOBS )
+	 { /* assume everthing was ok */
+		self->state = DRMAA_PS_DONE;
+		self->exit_status = 0;
+	 }
 	else
-		pbsdrmaa_job_on_missing_standard( self );	
-}
-
-void
-pbsdrmaa_job_on_missing_standard( fsd_job_t *self )
-{
-	fsd_drmaa_session_t *session = self->session;
-	pbsdrmaa_session_t *pbssession = (pbsdrmaa_session_t *)session;
-	int exit_status = -1;
-	
-	fsd_log_enter(( "({job_id=%s})", self->job_id ));
-	fsd_log_warning(( "Job %s missing from DRM queue", self->job_id ));
-
-	fsd_log_info(( "job_on_missing: last job_ps: %s (0x%02x)", drmaa_job_ps_to_str(self->state), self->state));
-
-	if( (exit_status = pbsdrmaa_job_read_exit_status(self->job_id, pbssession->job_exit_status_file_prefix)) == 0 )
-	{
-		self->state = DRMAA_PS_DONE;
-		self->exit_status = exit_status;
+	 { /* job aborted */
+		self->state = DRMAA_PS_FAILED;
+		self->exit_status = -1;
+	 }
+
+	fsd_log_return(( "; job_ps=%s, exit_status=%d",
+				drmaa_job_ps_to_str(self->state), self->exit_status ));
 	}
-	else
-	{
-		self->state = DRMAA_PS_FAILED;
-		self->exit_status = exit_status;
-	}
-        fsd_log_info(("job_on_missing evaluation result: state=%d exit_status=%d", self->state, self->exit_status));
-
-	fsd_cond_broadcast( &self->status_cond);
-	fsd_cond_broadcast( &self->session->wait_condition );
-
-	fsd_log_return(( "; job_ps=%s, exit_status=%d", drmaa_job_ps_to_str(self->state), self->exit_status ));
-}
-
-int
-pbsdrmaa_job_read_exit_status( const char *job_id, const char *job_state_dir_prefix)
-{
-	char *status_file = NULL, *start_file = NULL;
-	FILE *fhandle = NULL;
-	int exit_status = -1;
-
-	fsd_log_enter(("({job_id=%s, job_state_dir_prefix=%s})", job_id, job_state_dir_prefix));
-
-	status_file = fsd_asprintf("%s/%s.exitcode", job_state_dir_prefix, job_id);
-	start_file = fsd_asprintf("%s/%s.started", job_state_dir_prefix, job_id);
-
-	if ((fhandle = fopen(status_file, "r")) == NULL)
-	 {
-		struct stat tmpstat;
-
-		fsd_log_error(("Failed to open job status file: %s", status_file));
-		if (stat(start_file, &tmpstat) == 0 && (tmpstat.st_mode & S_IFREG))
-		 {
-			exit_status = 143; /* SIGTERM */
-			fsd_log_info(("But start file exist %s. Assuming that job was killed (exit_status=%d).", start_file, exit_status));
-		 }
-		else
-		 {
-			fsd_log_error(("Start file not found: %s", start_file));
-		 }
-	
-
-	 }
-	else
-	 {
-		(void)fscanf(fhandle, "%d", &exit_status); /*on error exit_status == -1 */
-		fclose(fhandle);
-	 }
-
-	fsd_free(status_file);
-	fsd_free(start_file);
-
-	return exit_status;
-}
-
+}
+
Index: trunk/pbs_drmaa/pbs_attrib.gperf
===================================================================
--- trunk/pbs_drmaa/pbs_attrib.gperf	(revision 71)
+++ trunk/pbs_drmaa/pbs_attrib.gperf	(revision 1)
@@ -1,8 +1,8 @@
 %{
-/* $Id$ */
+/* $Id: pbs_attrib.gperf 2677 2009-09-08 14:32:22Z mmamonski $ */
 /*
  *  FedStage DRMAA for PBS Pro
  *  Copyright (C) 2006-2009  FedStage Systems
- *  Copyright (C) 2011 Poznan Supercomputing and Networking Center
+ *
  *  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
@@ -31,5 +31,5 @@
 		__attribute__ ((unused))
 #	endif
-	= "$Id$";
+	= "$Id: pbs_attrib.gperf 2677 2009-09-08 14:32:22Z mmamonski $";
 #endif
 
@@ -60,5 +60,4 @@
 Resource_List.nice, t(PBSDRMAA_ATTR_NICE)
 Resource_List.vmem, t(PBSDRMAA_ATTR_VMEM_LIMIT)
-Resource_List.mem, t(PBSDRMAA_ATTR_MEM_LIMIT)
 Resource_List.pcput, t(PBSDRMAA_ATTR_SINGLE_CPU_TIME_LIMIT)
 Resource_List.pmem, t(PBSDRMAA_ATTR_SINGLE_RSS_LIMIT)
@@ -68,9 +67,5 @@
 Resource_List.host, t(PBSDRMAA_ATTR_HOST)
 Resource_List.nodes, t(PBSDRMAA_ATTR_NODES)
-Resource_List.procs, t(PBSDRMAA_ATTR_PROCS)
-Resource_List.ncpus, t(PBSDRMAA_ATTR_NCPUS)
 Resource_List.software, t(PBSDRMAA_ATTR_SOFTWARE)
-Resource_List.place, t(PBSDRMAA_ATTR_PLACE)
-Resource_List.select, t(PBSDRMAA_ATTR_SELECT)
 Mail_Points, t(PBSDRMAA_ATTR_MAIL_POINTS)
 Output_Path, t(PBSDRMAA_ATTR_OUTPUT_PATH)
@@ -92,5 +87,4 @@
 # additional job and general attribute names
 exec_host, t(PBSDRMAA_ATTR_EXECUTION_HOST)
-exec_vnode, t(PBSDRMAA_ATTR_EXECUTION_VNODE)
 Job_Owner, t(PBSDRMAA_ATTR_JOB_OWNER)
 resources_used, t(PBSDRMAA_ATTR_RESOURCES_USED)
@@ -104,6 +98,10 @@
 submit_args, t(PBSDRMAA_ATTR_SUBMIT_ARGS)
 mtime, t(PBSDRMAA_ATTR_MTIME)
-Resource_List.node_properties, t(PBSDRMAA_ATTR_NODE_PROPERTIES)
-Resource_List.custom_resources, t(PBSDRMAA_ATTR_CUSTOM_RESOURCES)
+# reservation attributes:
+# reserve_start,       t(PBSDRMAA_ATTR_RESERVATION_START)
+# reserve_end,         t(PBSDRMAA_ATTR_RESERVATION_END)
+# reserve_duration,    t(PBSDRMAA_ATTR_RESERVATION_DURATION)
+# reserve_state,       t(PBSDRMAA_ATTR_RESERVATION_STATE)
+# reserve_substate,    t(PBSDRMAA_ATTR_RESERVATION_SUBSTATE)
 %%
 #undef t
@@ -176,5 +174,4 @@
 	{ "Resource_List.nice", PBSDRMAA_ATTR_NICE, false },
 	{ "Resource_List.vmem", PBSDRMAA_ATTR_VMEM_LIMIT, false },
-	{ "Resource_List.mem", PBSDRMAA_ATTR_MEM_LIMIT, false },
 	{ "Resource_List.pcput", PBSDRMAA_ATTR_SINGLE_CPU_TIME_LIMIT, false },
 	{ "Resource_List.pmem", PBSDRMAA_ATTR_SINGLE_RSS_LIMIT, false },
@@ -184,9 +181,5 @@
 	{ "Resource_List.host", PBSDRMAA_ATTR_HOST, false },
 	{ "Resource_List.nodes", PBSDRMAA_ATTR_NODES, false },
-	{ "Resource_List.procs", PBSDRMAA_ATTR_PROCS, false },
-	{ "Resource_List.ncpus", PBSDRMAA_ATTR_NCPUS, false },
 	{ "Resource_List.software", PBSDRMAA_ATTR_SOFTWARE, false },
-	{ "Resource_List.place", PBSDRMAA_ATTR_PLACE, false },
-	{ "Resource_List.select", PBSDRMAA_ATTR_SELECT, false },
 	{ "Mail_Points", PBSDRMAA_ATTR_MAIL_POINTS, false },
 	{ "Output_Path", PBSDRMAA_ATTR_OUTPUT_PATH, false },
@@ -207,5 +200,4 @@
 	{ "stageout", PBSDRMAA_ATTR_STAGEOUT, false },
 	{ "exec_host", PBSDRMAA_ATTR_EXECUTION_HOST, false },
-	{ "exec_vnode", PBSDRMAA_ATTR_EXECUTION_VNODE, false },
 	{ "Job_Owner", PBSDRMAA_ATTR_JOB_OWNER, false },
 	{ "resources_used", PBSDRMAA_ATTR_RESOURCES_USED, false },
@@ -219,7 +211,4 @@
 	{ "submit_args", PBSDRMAA_ATTR_SUBMIT_ARGS, false },
 	{ "mtime", PBSDRMAA_ATTR_MTIME, false },
-	{ "Resource_List.node_properties", PBSDRMAA_ATTR_NODE_PROPERTIES, false }, /* DRMAA extenstions */
-	{ "Resource_List.custom_resources", PBSDRMAA_ATTR_CUSTOM_RESOURCES, false },
-	
 };
 
Index: trunk/pbs_drmaa/util.c
===================================================================
--- trunk/pbs_drmaa/util.c	(revision 85)
+++ trunk/pbs_drmaa/util.c	(revision 1)
@@ -1,3 +1,3 @@
-/* $Id$ */
+/* $Id: util.c 323 2010-09-21 21:31:29Z mmatloka $ */
 /*
  *  FedStage DRMAA for PBS Pro
@@ -30,7 +30,4 @@
 #include <string.h>
 #include <unistd.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-
 
 #include <drmaa_utils/common.h>
@@ -44,5 +41,5 @@
 		__attribute__ ((unused))
 #	endif
-	= "$Id$";
+	= "$Id: util.c 323 2010-09-21 21:31:29Z mmatloka $";
 #endif
 
@@ -78,73 +75,41 @@
 }
 
-struct attrl *
-pbsdrmaa_add_attr( struct attrl *head, const char *name, const char *value)
-{
-	struct attrl *p = NULL;
-	char *resource = NULL;
-
-	fsd_malloc( p, struct attrl );
-	memset( p, 0, sizeof(struct attrl) );
-
-	resource = strchr( name, '.' );
-
-	if( resource )
-	 {
-		p->name = fsd_strndup( name, resource - name );
-		p->resource = fsd_strdup( resource+1 );
-	 }
-	else
-	 {
-		p->name = fsd_strdup( name );
-	 }
-
-	p->value = fsd_strdup(value);
-	p->op = SET;
-
-	fsd_log_debug(("set attr: %s = %s", name, value));
-
-	if (head)
-		p->next = head;
-	else
-		p->next = NULL;
-
-	return p;
-}
-
 
 void
-pbsdrmaa_exc_raise_pbs( const char *function, int connection )
+pbsdrmaa_exc_raise_pbs( const char *function )
 {
 	int _pbs_errno;
 	int fsd_errno;
 	const char *message = NULL;
-	const char *extended_message = NULL;
 
 	_pbs_errno = pbs_errno;
-
-#ifndef PBS_PROFESSIONAL_NO_LOG
+	/*
+	 * Gathering error messages differ between PBS forks.
+	 * - OpenPBS - ...
+	 * - Torque - pbse_to_txt takes PBS error code (stored in pbs_errno)
+	 *  and returns corresponding error message.
+	 * - PBS Pro - stores errno of last operation inside pbs_errno variable;
+	 *  pbse_to_txt always return NULL.
+	 * All of them define pbs_geterrmsg which returns last error message
+	 * for given connection.
+	 */
+	/* XXX: PBSPro has some link problems with pbse_to_txt function */
+#if 1
 	message = pbse_to_txt( pbs_errno );
 #else
-	message = "PBS error";
-#endif
-
-	if ( connection != -1 )
-	 {
-		extended_message = pbs_geterrmsg(connection);
-	 }
+	message = "pbs error";
+#endif
+
 
 	fsd_errno = pbsdrmaa_map_pbs_errno( _pbs_errno );
-
-	fsd_log_error(( "call to %s returned with error %d:%s(%s) mapped to %d:%s",
-					function,
-					_pbs_errno, message, extended_message,
-					fsd_errno, fsd_strerror(fsd_errno)
-			));
-
-	if (extended_message)
-		fsd_exc_raise_fmt(fsd_errno, "%s: %s ", message, extended_message);
-	else
-		fsd_exc_raise_fmt(fsd_errno, "%s", message);
-}
+	fsd_log_error((
+				"call to %s returned with error %d:%s mapped to %d:%s",
+				function,
+				_pbs_errno, message,
+				fsd_errno, fsd_strerror(fsd_errno)
+				));
+	fsd_exc_raise_fmt( fsd_errno, "%s: %s", function, message );
+}
+
 
 /** Maps PBS error code into DMRAA code. */
@@ -265,8 +230,4 @@
 		if( fd < 0 )
 			fsd_exc_raise_sys(0);
-
-		if( fchmod(fd, 0600 ) != 0)
-			fsd_exc_raise_sys(0);
-
 		while( len > 0 )
 		 {
Index: trunk/pbs_drmaa/job.h
===================================================================
--- trunk/pbs_drmaa/job.h	(revision 62)
+++ trunk/pbs_drmaa/job.h	(revision 1)
@@ -1,3 +1,3 @@
-/* $Id$ */
+/* $Id: job.h 2 2009-10-12 09:51:22Z mamonski $ */
 /*
  *  FedStage DRMAA for PBS Pro
@@ -37,5 +37,4 @@
 struct pbsdrmaa_job_s {
 	fsd_job_t super;
-	time_t missing_time; /* The time when job was seen as missing for the first time */
 
 	void (*
@@ -43,5 +42,4 @@
 };
 
-
 #endif /* __PBS_DRMAA__JOB_H */
 
Index: trunk/pbs_drmaa/util.h
===================================================================
--- trunk/pbs_drmaa/util.h	(revision 85)
+++ trunk/pbs_drmaa/util.h	(revision 1)
@@ -1,3 +1,3 @@
-/* $Id$ */
+/* $Id: util.h 323 2010-09-21 21:31:29Z mmatloka $ */
 /*
  *  FedStage DRMAA for PBS Pro
@@ -25,10 +25,5 @@
 #endif
 
-/*compatibility hack - ugly but help to keep binary compatibility :/ */
-#define PBSOLDE_PROTOCOL 15031
-#define PBSOLDE_EXPIRED 15020
-
-
-void pbsdrmaa_exc_raise_pbs( const char *function, int connection_fd );
+void pbsdrmaa_exc_raise_pbs( const char *function );
 int pbsdrmaa_map_pbs_errno( int _pbs_errno );
 
@@ -36,7 +31,6 @@
 
 void pbsdrmaa_free_attrl( struct attrl *list );
-void pbsdrmaa_dump_attrl( const struct attrl *attribute_list, const char *prefix );
-
-struct attrl *pbsdrmaa_add_attr( struct attrl *head, const char *name, const char *value);
+void pbsdrmaa_dump_attrl(
+		const struct attrl *attribute_list, const char *prefix );
 
 /**
@@ -49,5 +43,4 @@
 pbsdrmaa_write_tmpfile( const char *content, size_t len );
 
-
 #endif /* __PBS_DRMAA__UTIL_H */
 
Index: trunk/pbs_drmaa/session.c
===================================================================
--- trunk/pbs_drmaa/session.c	(revision 93)
+++ trunk/pbs_drmaa/session.c	(revision 1)
@@ -1,3 +1,3 @@
-/* $Id$ */
+/* $Id: session.c 385 2011-01-04 18:24:05Z mamonski $ */
 /*
  *  FedStage DRMAA for PBS Pro
@@ -22,5 +22,4 @@
 #endif
 
-#include <pwd.h>
 #include <stdlib.h>
 #include <string.h>
@@ -30,5 +29,4 @@
 #include <sys/types.h>
 #include <fcntl.h>
-#include <signal.h>
 
 #include <pbs_ifl.h>
@@ -43,5 +41,4 @@
 
 #include <pbs_drmaa/job.h>
-#include <pbs_drmaa/log_reader.h>
 #include <pbs_drmaa/session.h>
 #include <pbs_drmaa/submit.h>
@@ -55,5 +52,5 @@
 		__attribute__ ((unused))
 #	endif
-	= "$Id$";
+	= "$Id: session.c 385 2011-01-04 18:24:05Z mamonski $";
 #endif
 
@@ -66,4 +63,7 @@
 static fsd_job_t *
 pbsdrmaa_session_new_job( fsd_drmaa_session_t *self, const char *job_id );
+
+static bool
+pbsdrmaa_session_do_drm_keeps_completed_jobs( pbsdrmaa_session_t *self );
 
 static void
@@ -95,10 +95,8 @@
 		self = (pbsdrmaa_session_t*)fsd_drmaa_session_new(contact);
 		fsd_realloc( self, 1, pbsdrmaa_session_t );
-
-		fsd_mutex_lock( &self->super.mutex );
-
 		self->super_wait_thread = NULL;
 
 		self->log_file_initial_size = 0;
+		self->pbs_conn = -1;
 		self->pbs_home = NULL;
 
@@ -116,17 +114,20 @@
 		self->super.apply_configuration = pbsdrmaa_session_apply_configuration;
 
+		self->do_drm_keeps_completed_jobs =
+			pbsdrmaa_session_do_drm_keeps_completed_jobs;
+
 		self->status_attrl = pbsdrmaa_create_status_attrl();
-		self->max_retries_count = 3;
-		self->wait_thread_sleep_time = 1;
-		self->job_exit_status_file_prefix = NULL;
+
+		self->pbs_conn = pbs_connect( self->super.contact );
+		fsd_log_debug(( "pbs_connect(%s) =%d", self->super.contact,
+					self->pbs_conn ));
+		if( self->pbs_conn < 0 )
+			pbsdrmaa_exc_raise_pbs( "pbs_connect" );
 
 		self->super.load_configuration( &self->super, "pbs_drmaa" );
 
 		self->super.missing_jobs = FSD_IGNORE_MISSING_JOBS;
-
-		self->pbs_connection = pbsdrmaa_pbs_conn_new( (fsd_drmaa_session_t *)self, contact );
-		self->connection_max_lifetime =  30; /* 30 seconds */
-
-		fsd_mutex_unlock( &self->super.mutex );
+		if( self->do_drm_keeps_completed_jobs( self ) )
+			self->super.missing_jobs = FSD_IGNORE_QUEUED_MISSING_JOBS;
 	 }
 	EXCEPT_DEFAULT
@@ -134,10 +135,7 @@
 		if( self )
 		  {
-			fsd_mutex_unlock( &self->super.mutex );
 			self->super.destroy( &self->super );
 			self = NULL;
 		  }
-
-		fsd_exc_reraise();
 	 }
 	END_TRY
@@ -151,8 +149,7 @@
 	pbsdrmaa_session_t *pbsself = (pbsdrmaa_session_t*)self;
 	self->stop_wait_thread( self );
-	pbsdrmaa_pbs_conn_destroy(pbsself->pbs_connection);
+	if( pbsself->pbs_conn >= 0 )
+		pbs_disconnect( pbsself->pbs_conn );
 	fsd_free( pbsself->status_attrl );
-	fsd_free( pbsself->job_exit_status_file_prefix );
-
 	pbsself->super_destroy( self );	
 }
@@ -213,95 +210,50 @@
 {
 	pbsdrmaa_session_t *pbsself = (pbsdrmaa_session_t*)self;
-	fsd_conf_option_t *pbs_home = NULL;
-	fsd_conf_option_t *wait_thread_sleep_time = NULL;
-	fsd_conf_option_t *max_retries_count = NULL;
-	fsd_conf_option_t *user_state_dir = NULL;
-	fsd_conf_option_t *connection_max_lifetime = NULL;
-
-
+	fsd_conf_option_t *pbs_home;
 	pbs_home = fsd_conf_dict_get(self->configuration, "pbs_home" );
-	wait_thread_sleep_time = fsd_conf_dict_get(self->configuration, "wait_thread_sleep_time" );
-	max_retries_count = fsd_conf_dict_get(self->configuration, "max_retries_count" );
-	user_state_dir = fsd_conf_dict_get(self->configuration, "user_state_dir" );
-	connection_max_lifetime = fsd_conf_dict_get(self->configuration, "connection_max_lifetime");
-
-	if( pbs_home && pbs_home->type == FSD_CONF_STRING )
-	  {
+	if( pbs_home )
+	 {
+		if( pbs_home->type == FSD_CONF_STRING )
+		 {
 			struct stat statbuf;
 			char * volatile log_path;
-			struct tm tm;
-			
+			time_t t;
+
 			pbsself->pbs_home = pbs_home->val.string;
-			fsd_log_info(("pbs_home: %s",pbsself->pbs_home));
+			fsd_log_debug(("pbs_home: %s",pbsself->pbs_home));
 			pbsself->super_wait_thread = pbsself->super.wait_thread;
 			pbsself->super.wait_thread = pbsdrmaa_session_wait_thread;		
 			pbsself->wait_thread_log = true;
 	
-			time(&pbsself->log_file_initial_time);	
-			localtime_r(&pbsself->log_file_initial_time,&tm);
-
-			log_path = fsd_asprintf("%s/server_logs/%04d%02d%02d",
-					pbsself->pbs_home,
-					tm.tm_year + 1900,
-					tm.tm_mon + 1,
-					tm.tm_mday);
-
-			if(stat(log_path,&statbuf) == -1)
-			  {
+			time(&t);	
+			localtime_r(&t,&pbsself->log_file_initial_time);
+
+			if((log_path = fsd_asprintf("%s/server_logs/%04d%02d%02d",
+    		  		pbsself->pbs_home,	 
+  		    		pbsself->log_file_initial_time.tm_year + 1900,
+   		    		pbsself->log_file_initial_time.tm_mon + 1,
+   		   		pbsself->log_file_initial_time.tm_mday)) == NULL) {
+				fsd_exc_raise_fmt(FSD_ERRNO_INTERNAL_ERROR,"WT - Memory allocation wasn't possible");
+			}
+
+			if(stat(log_path,&statbuf) == -1) {
 				char errbuf[256] = "InternalError";
-				(void)strerror_r(errno, errbuf, sizeof(errbuf));
-				fsd_exc_raise_fmt(FSD_ERRNO_INTERNAL_ERROR,"stat error on file %s: %s", log_path, errbuf);
-			  }
+				(void)strerror_r(errno, errbuf, 256);
+				fsd_exc_raise_fmt(FSD_ERRNO_INTERNAL_ERROR,"stat error: %s",errbuf);
+			}
 	
 			fsd_log_debug(("Log file %s size %d",log_path,(int) statbuf.st_size));
 			pbsself->log_file_initial_size = statbuf.st_size;
 			fsd_free(log_path);
-	  }
-
-	if ( max_retries_count && max_retries_count->type == FSD_CONF_INTEGER)
-	  {
-		pbsself->max_retries_count = max_retries_count->val.integer;
-		fsd_log_info(("Max retries count: %d", pbsself->max_retries_count));
-	  }
-
-	if ( connection_max_lifetime && connection_max_lifetime->type == FSD_CONF_INTEGER)
-	  {
-		pbsself->connection_max_lifetime = connection_max_lifetime->val.integer;
-		fsd_log_info(("Max connection lifetime: %d", pbsself->connection_max_lifetime));
-	  }
-
-	if ( wait_thread_sleep_time && wait_thread_sleep_time->type == FSD_CONF_INTEGER)
-	  {
-		pbsself->wait_thread_sleep_time = wait_thread_sleep_time->val.integer;
-		fsd_log_info(("Wait thread sleep time: %d", pbsself->wait_thread_sleep_time));
-	  }
-
-	if( user_state_dir && user_state_dir->type == FSD_CONF_STRING )
-	  {
-		struct passwd *pw = NULL;
-		uid_t uid;
-
-		uid = geteuid();
-		pw = getpwuid(uid); /* drmaa_init is always called in thread safely fashion */
-
-		if (!pw)
-			fsd_exc_raise_fmt(FSD_ERRNO_INTERNAL_ERROR,"Failed to get pw_name of the user %d", uid);
-
-		pbsself->job_exit_status_file_prefix = fsd_asprintf(user_state_dir->val.string, pw->pw_name);
-	  }
-	else
-	  {
-		pbsself->job_exit_status_file_prefix = fsd_asprintf("%s/.drmaa", getenv("HOME"));
-	  }
-
-	fsd_log_debug(("Trying to create state directory: %s", pbsself->job_exit_status_file_prefix));
-
-	if (mkdir(pbsself->job_exit_status_file_prefix, 0700) == -1 && errno != EEXIST) /* TODO it would be much better to do stat before */
-	  {
-		fsd_log_warning(("Failed to create job state directory: %s. Valid job exit status may not be available in some cases.", pbsself->job_exit_status_file_prefix));
-	  }
-
-
-	/* TODO purge old exit statuses files */
+		 }
+		else
+		{
+			pbsself->super.enable_wait_thread = false;
+			pbsself->wait_thread_log = false;
+			fsd_log_debug(("pbs_home not configured. Running standard wait_thread (pooling)."));
+		}
+	 }
+
+
 
 	pbsself->super_apply_configuration(self); /* call method from the superclass */
@@ -312,4 +264,5 @@
 pbsdrmaa_session_update_all_jobs_status( fsd_drmaa_session_t *self )
 {
+	volatile bool conn_lock = false;
 	volatile bool jobs_lock = false;
 	pbsdrmaa_session_t *pbsself = (pbsdrmaa_session_t*)self;
@@ -321,11 +274,32 @@
 	TRY
 	 {
-
-/* TODO: query only for user's jobs pbs_selstat + ATTR_u */
+		conn_lock = fsd_mutex_lock( &self->drm_connection_mutex );
+retry:
+
 #ifdef PBS_PROFESSIONAL
-		status = pbsself->pbs_connection->statjob(pbsself->pbs_connection, NULL, NULL);
+		status = pbs_statjob( pbsself->pbs_conn, NULL, NULL, NULL );
 #else
-		status = pbsself->pbs_connection->statjob(pbsself->pbs_connection, NULL, pbsself->status_attrl);
+		status = pbs_statjob( pbsself->pbs_conn, NULL, pbsself->status_attrl, NULL );
 #endif
+		fsd_log_debug(( "pbs_statjob( fd=%d, job_id=NULL, attribs={...} ) =%p",
+				 pbsself->pbs_conn, (void*)status ));
+		if( status == NULL  &&  pbs_errno != 0 )
+		 {
+			if (pbs_errno == PBSE_PROTOCOL || pbs_errno == PBSE_EXPIRED)
+			 {
+				pbs_disconnect( pbsself->pbs_conn );
+				sleep(1);
+				pbsself->pbs_conn = pbs_connect( pbsself->super.contact );
+				if( pbsself->pbs_conn < 0 )
+					pbsdrmaa_exc_raise_pbs( "pbs_connect" );
+				else
+					goto retry;
+			 }
+			else
+			 {
+				pbsdrmaa_exc_raise_pbs( "pbs_statjob" );
+			 }
+		 }
+		conn_lock = fsd_mutex_unlock( &self->drm_connection_mutex );
 
 		 {
@@ -388,5 +362,7 @@
 	 {
 		if( status != NULL )
-			 pbsself->pbs_connection->statjob_free(pbsself->pbs_connection, status );
+			pbs_statfree( status );
+		if( conn_lock )
+			conn_lock = fsd_mutex_unlock( &self->drm_connection_mutex );
 		if( jobs_lock )
 			jobs_lock = fsd_mutex_unlock( &jobs->mutex );
@@ -450,22 +426,560 @@
 }
 
+
+bool
+pbsdrmaa_session_do_drm_keeps_completed_jobs( pbsdrmaa_session_t *self )
+{
+
+#ifndef PBS_PROFESSIONAL
+	struct attrl default_queue_query;
+	struct attrl keep_completed_query;
+	struct batch_status *default_queue_result = NULL;
+	struct batch_status *keep_completed_result = NULL;
+	const char *default_queue = NULL;
+	const char *keep_completed = NULL;
+	volatile bool result = false;
+	volatile bool conn_lock = false;
+
+	TRY
+	 {
+		default_queue_query.next = NULL;
+		default_queue_query.name = "default_queue";
+		default_queue_query.resource = NULL;
+		default_queue_query.value = NULL;
+		keep_completed_query.next = NULL;
+		keep_completed_query.name = "keep_completed";
+		keep_completed_query.resource = NULL;
+		keep_completed_query.value = NULL;
+
+		conn_lock = fsd_mutex_lock( &self->super.drm_connection_mutex );
+
+		default_queue_result =
+				pbs_statserver( self->pbs_conn, &default_queue_query, NULL );
+		if( default_queue_result == NULL )
+			pbsdrmaa_exc_raise_pbs( "pbs_statserver" );
+		if( default_queue_result->attribs
+				&&  !strcmp( default_queue_result->attribs->name,
+					"default_queue" ) )
+			default_queue = default_queue_result->attribs->value;
+
+		fsd_log_debug(( "default_queue: %s", default_queue ));
+
+		if( default_queue )
+		 {
+			keep_completed_result = pbs_statque( self->pbs_conn,
+					(char*)default_queue, &keep_completed_query, NULL );
+			if( keep_completed_result == NULL )
+				pbsdrmaa_exc_raise_pbs( "pbs_statque" );
+			if( keep_completed_result->attribs
+					&&  !strcmp( keep_completed_result->attribs->name,
+						"keep_completed" ) )
+				keep_completed = keep_completed_result->attribs->value;
+		 }
+
+		fsd_log_debug(( "keep_completed: %s", keep_completed ));
+	 }
+	EXCEPT_DEFAULT
+	 {
+		const fsd_exc_t *e = fsd_exc_get();
+		fsd_log_warning(( "PBS server seems not to keep completed jobs\n"
+				"detail: %s", e->message(e) ));
+		result = false;
+	 }
+	ELSE
+	 {
+		result = false;
+		if( default_queue == NULL )
+			fsd_log_warning(( "no default queue set on PBS server" ));
+		else if( keep_completed == NULL && self->pbs_home == NULL )
+			fsd_log_warning(( "PBS server is not configured to keep completed jobs\n"
+						"in Torque: set keep_completed parameter of default queue\n"
+						"  $ qmgr -c 'set queue batch keep_completed = 60'\n"
+						" or configure DRMAA to utilize log files"
+						));
+		else
+			result = true;
+	 }
+	FINALLY
+	 {
+		if( default_queue_result )
+			pbs_statfree( default_queue_result );
+		if( keep_completed_result )
+			pbs_statfree( keep_completed_result );
+		if( conn_lock )
+			conn_lock = fsd_mutex_unlock( &self->super.drm_connection_mutex );
+
+	 }
+	END_TRY
+#endif
+	return false;
+}
+
+
+enum field
+  {
+  FLD_DATE = 0,
+  FLD_EVENT = 1,
+  FLD_OBJ = 2,
+  FLD_TYPE = 3,
+  FLD_ID = 4,
+  FLD_MSG = 5
+  };
+
+enum field_msg
+  {
+  FLD_MSG_EXIT_STATUS = 0,
+  FLD_MSG_CPUT = 1,
+  FLD_MSG_MEM = 2,
+  FLD_MSG_VMEM = 3,
+  FLD_MSG_WALLTIME = 4
+  };
+
+#define FLD_MSG_STATUS "0010"
+#define FLD_MSG_STATE "0008"
+#define FLD_MSG_LOG "0002"
+
+ssize_t fsd_getline(char * line,ssize_t size, int fd)
+{
+	char buf;
+	char * ptr = NULL;
+	ssize_t n = 0, rc;
+	ptr = line;
+	for(n = 1; n< size; n++)
+	{		
+		if( (rc = read(fd,&buf,1 )) == 1) {
+			*ptr++ = buf;
+			if(buf == '\n')
+			{
+				break;
+			}
+		}
+		else if (rc == 0) {
+			if (n == 1)
+				return 0;
+			else
+				break;
+		}		
+		else
+			return -1; 
+	}
+
+	return n;
+} 
+
 void *
 pbsdrmaa_session_wait_thread( fsd_drmaa_session_t *self )
 {
-	pbsdrmaa_log_reader_t *log_reader = NULL;
+	pbsdrmaa_session_t *pbsself = (pbsdrmaa_session_t*) self;
+	fsd_job_t *volatile job = NULL;
+	pbsdrmaa_job_t *volatile pbsjob = NULL;
+	char job_id[256] = "";
+	char event[256] = "";
+	time_t t;
+	struct tm tm;
+
+	tm = pbsself->log_file_initial_time;
+
+	fsd_log_enter(( "" ));
+	fsd_mutex_lock( &self->mutex );
+	TRY
+	 {	
+		char * volatile log_path = NULL;
+		char buffer[4096] = "";
+		bool volatile date_changed = true;
+		int  volatile fd = -1;
+		bool first_open = true;
+
+		fsd_log_debug(("WT - reading log files"));
+
+		while( self->wait_thread_run_flag )
+		TRY
+		 {			
+			if(date_changed)
+			{
+				int num_tries = 0;
+				
+				time(&t);	
+				localtime_r(&t,&tm);
+			
+				#define DRMAA_WAIT_THREAD_MAX_TRIES (12)
+				/* generate new date, close file and open new */
+				if((log_path = fsd_asprintf("%s/server_logs/%04d%02d%02d",
+       					pbsself->pbs_home,	 
+       					tm.tm_year + 1900,
+       					tm.tm_mon + 1,
+      					tm.tm_mday)) == NULL) {
+					fsd_exc_raise_fmt(FSD_ERRNO_INTERNAL_ERROR,"WT - Memory allocation wasn't possible");
+				}
+
+				if(fd != -1)
+					close(fd);
+
+				fsd_log_debug(("Log file: %s",log_path));
+				
+		retry:
+				if((fd = open(log_path,O_RDONLY) ) == -1 && num_tries > DRMAA_WAIT_THREAD_MAX_TRIES )
+				{
+					fsd_log_error(("Can't open log file. Verify pbs_home. Running standard wait_thread."));
+					fsd_log_error(("Remember that without keep_completed set standard wait_thread won't run correctly"));
+					/*pbsself->super.enable_wait_thread = false;*/ /* run not wait_thread */
+					pbsself->wait_thread_log = false;
+					pbsself->super.wait_thread = pbsself->super_wait_thread;
+					pbsself->super.wait_thread(self);
+				} else if ( fd == -1 ) {
+					fsd_log_warning(("Can't open log file: %s. Retries count: %d", log_path, num_tries));
+					num_tries++;
+					sleep(5);
+					goto retry;
+				}
+
+				fsd_free(log_path);
+
+				fsd_log_debug(("Log file opened"));
+
+				if(first_open) {
+					fsd_log_debug(("Log file lseek"));
+					if(lseek(fd,pbsself->log_file_initial_size,SEEK_SET) == (off_t) -1) {
+						char errbuf[256] = "InternalError";
+						(void)strerror_r(errno, errbuf, 256);
+						fsd_exc_raise_fmt(FSD_ERRNO_INTERNAL_ERROR,"lseek error: %s",errbuf);
+					}
+					first_open = false;
+				}
+
+				date_changed = false;
+			}				
+			
+			while ((fsd_getline(buffer,sizeof(buffer),fd)) > 0) 			
+			{
+				const char *volatile ptr = buffer;
+  				char field[256] = "";
+				int volatile field_n = 0;
+ 				int n;
+
+				bool volatile job_id_match = false;
+				bool volatile event_match = false;
+				bool volatile log_event = false;
+				bool volatile log_match = false;
+  				char *  temp_date = NULL;
+				
+
+				struct batch_status status;
+				status.next = NULL;
+
+				if( strlcpy(job_id,"",sizeof(job_id)) > sizeof(job_id) ) {
+					fsd_log_error(("WT - strlcpy error"));
+				}
+				if( strlcpy(event,"",sizeof(event)) > sizeof(event) ) {
+					fsd_log_error(("WT - strlcpy error"));
+				}
+				while ( sscanf(ptr, "%255[^;]%n", field, &n) == 1 ) /* divide current line into fields */
+				{
+					if(field_n == FLD_DATE)
+					{
+						temp_date = fsd_strdup(field);
+					}
+					else if(field_n == FLD_EVENT && (strcmp(field,FLD_MSG_STATUS) == 0 || 
+						     		    strcmp(field,FLD_MSG_STATE) == 0 ))
+					{
+						/* event described by log line*/
+						if(strlcpy(event, field,sizeof(event)) > sizeof(event)) {
+							fsd_log_error(("WT - strlcpy error"));
+						}
+						event_match = true;									
+					}
+					else if(event_match && field_n == FLD_ID)
+					{	
+						TRY
+						{	
+							job = self->get_job( self, field );
+							pbsjob = (pbsdrmaa_job_t*) job;
+
+							if( job )
+							{
+								if(strlcpy(job_id, field,sizeof(job_id)) > sizeof(job_id)) {
+									fsd_log_error(("WT - strlcpy error"));
+								}
+								fsd_log_debug(("WT - job_id: %s",job_id));
+								status.name = fsd_strdup(job_id);
+								job_id_match = true; /* job_id is in drmaa */
+							}
+							else 
+							{
+								fsd_log_debug(("WT - Unknown job: %s", field));
+							}
+						}
+						END_TRY	
+					}
+					else if(job_id_match && field_n == FLD_MSG)
+					{						
+						/* parse msg - depends on FLD_EVENT*/
+						struct attrl struct_resource_cput,struct_resource_mem,struct_resource_vmem,
+							struct_resource_walltime, struct_status, struct_state, struct_start_time,struct_mtime, struct_queue, struct_account_name;	
+						
+						bool state_running = false;
+
+						struct_status.name = NULL;
+						struct_status.value = NULL;
+						struct_status.next = NULL;
+						struct_status.resource = NULL;
+
+						struct_state.name = NULL;
+						struct_state.value = NULL;
+						struct_state.next = NULL;
+						struct_state.resource = NULL;
+
+						struct_resource_cput.name = NULL;
+						struct_resource_cput.value = NULL;
+						struct_resource_cput.next = NULL;
+						struct_resource_cput.resource = NULL;
+
+						struct_resource_mem.name = NULL;
+						struct_resource_mem.value = NULL;
+						struct_resource_mem.next = NULL;
+						struct_resource_mem.resource = NULL;
+
+						struct_resource_vmem.name = NULL;
+						struct_resource_vmem.value = NULL;
+						struct_resource_vmem.next = NULL;
+						struct_resource_vmem.resource = NULL;
+
+						struct_resource_walltime.name = NULL;
+						struct_resource_walltime.value = NULL;
+						struct_resource_walltime.next = NULL;
+						struct_resource_walltime.resource = NULL;
+
+						struct_start_time.name = NULL;
+						struct_start_time.value = NULL;
+						struct_start_time.next = NULL;
+						struct_start_time.resource = NULL;
+
+						struct_mtime.name = NULL;
+						struct_mtime.value = NULL;
+						struct_mtime.next = NULL;
+						struct_mtime.resource = NULL;
+
+						struct_queue.name = NULL;
+						struct_queue.value = NULL;
+						struct_queue.next = NULL;
+						struct_queue.resource = NULL;
+
+						struct_account_name.name = NULL;
+						struct_account_name.value = NULL;
+						struct_account_name.next = NULL;
+						struct_account_name.resource = NULL;
+
+								
+						if (strcmp(event,FLD_MSG_STATE) == 0) 
+						{
+							/* job run, modified, queued etc */
+							int n = 0;
+							status.attribs = &struct_state;
+							struct_state.next = NULL;
+							struct_state.name = "job_state";
+							if(field[0] == 'J') /* Job Queued, Job Modified, Job Run*/
+							{
+								n = 4;								
+							}		
+							if(field[4] == 'M') {
+								struct tm temp_time_tm;
+								memset(&temp_time_tm, 0, sizeof(temp_time_tm));
+								temp_time_tm.tm_isdst = -1;
+
+								if (strptime(temp_date, "%m/%d/%Y %H:%M:%S", &temp_time_tm) == NULL) 
+								 {
+								 	fsd_log_error(("failed to parse mtime: %s", temp_date));
+								 }
+								else
+								 {
+									time_t temp_time = mktime(&temp_time_tm);
+									status.attribs = &struct_mtime; 
+									struct_mtime.name = "mtime";
+									struct_mtime.next = NULL;
+									struct_mtime.value = fsd_asprintf("%lu",temp_time);
+								 }
+							}		
+							/* != Job deleted and Job to be deleted*/
+							#ifdef PBS_PROFESSIONAL
+							else if	(field[4] != 't' && field[10] != 'd') {
+							#else	 	
+							else if(field[4] != 'd') {
+							#endif 
+
+								if ((struct_state.value = fsd_asprintf("%c",field[n]) ) == NULL ) { /* 4 first letter of state */
+									fsd_exc_raise_fmt(FSD_ERRNO_INTERNAL_ERROR,"WT - Memory allocation wasn't possible");
+								}
+								if(struct_state.value[0] == 'R'){
+									state_running = true;
+								}
+							}
+							else { /* job terminated - pbs drmaa detects failed as completed with exit_status !=0, aborted with status -1*/
+								struct_status.name = "exit_status";
+								struct_status.value = fsd_strdup("-1");
+								struct_status.next = NULL;
+								struct_state.next = &struct_status;
+								struct_state.value = fsd_strdup("C");								
+							}
+						} 						     
+						else /*if (strcmp(event,FLD_MSG_STATUS) == 0 )*/
+						{
+							/* exit status and rusage */
+							const char *ptr2 = field;
+							char  msg[ 256 ] = "";
+							int n2;
+							int msg_field_n = 0;
+							
+							struct_resource_cput.name = "resources_used";
+							struct_resource_mem.name = "resources_used";
+							struct_resource_vmem.name = "resources_used";
+							struct_resource_walltime.name = "resources_used";
+							struct_status.name = "exit_status";
+							struct_state.name = "job_state";
+				
+							status.attribs = &struct_resource_cput;
+							struct_resource_cput.next = &struct_resource_mem;
+							struct_resource_mem.next = &struct_resource_vmem;
+							struct_resource_vmem.next = &struct_resource_walltime;
+							struct_resource_walltime.next =  &struct_status;
+							struct_status.next = &struct_state;
+							struct_state.next = NULL;
+
+							while ( sscanf(ptr2, "%255[^ ]%n", msg, &n2) == 1 )
+							 {						
+								switch(msg_field_n) 
+								{
+									case FLD_MSG_EXIT_STATUS:
+										struct_status.value = fsd_strdup(strchr(msg,'=')+1);
+										break;
+
+									case FLD_MSG_CPUT:
+										struct_resource_cput.resource = "cput";
+										struct_resource_cput.value = fsd_strdup(strchr(msg,'=')+1);
+										break;
+
+									case FLD_MSG_MEM:
+										struct_resource_mem.resource = "mem";
+										struct_resource_mem.value  = fsd_strdup(strchr(msg,'=')+1);
+										break;
+
+									case FLD_MSG_VMEM:
+										struct_resource_vmem.resource = "vmem";
+										struct_resource_vmem.value  = fsd_strdup(strchr(msg,'=')+1);
+										break; 
+
+									case FLD_MSG_WALLTIME:
+										struct_resource_walltime.resource = "walltime";
+										struct_resource_walltime.value  = fsd_strdup(strchr(msg,'=')+1);
+										break; 
+								}
+							      
+								ptr2 += n2; 
+								msg_field_n++;
+								if ( *ptr2 != ' ' )
+							      	 {
+									 break; 
+							  	 }
+							 	++ptr2;						
+							 }
+							struct_state.value = fsd_strdup("C");	/* we got exit_status so we say that it has completed */
+						}						
+
+						if ( state_running )
+						 {
+							fsd_log_debug(("WT - forcing update of job: %s", job->job_id ));
+							job->update_status( job );
+						 }
+						else
+						 {
+							fsd_log_debug(("WT - updating job: %s", job->job_id ));
+							pbsjob->update( job, &status );
+						 }
+
+				
+						fsd_cond_broadcast( &job->status_cond);
+						fsd_cond_broadcast( &self->wait_condition );
+
+						if ( job )
+							job->release( job );
 	
-	fsd_log_enter(( "" ));
-	
-	TRY
-	{	
-		log_reader = pbsdrmaa_log_reader_new( self );
-		log_reader->read_log( log_reader );
-	}
+						fsd_free(struct_resource_cput.value);
+						fsd_free(struct_resource_mem.value);
+						fsd_free(struct_resource_vmem.value);
+						fsd_free(struct_resource_walltime.value);
+						fsd_free(struct_status.value);
+						fsd_free(struct_state.value);
+						fsd_free(struct_start_time.value);
+						fsd_free(struct_mtime.value);
+						fsd_free(struct_queue.value);
+						fsd_free(struct_account_name.value);
+
+						if ( status.name!=NULL ) 
+							fsd_free(status.name);
+					}
+					else if(field_n == FLD_EVENT && strcmp(field,FLD_MSG_LOG) == 0)
+					{
+						log_event = true;					
+					}
+					else if (log_event && field_n == FLD_ID && strcmp(field,"Log") == 0 )
+					{
+						log_match = true;
+						log_event = false;
+					}
+					else if( log_match && field_n == FLD_MSG && 
+						field[0] == 'L' && 
+						field[1] == 'o' && 
+						field[2] == 'g' && 
+						field[3] == ' ' && 
+						field[4] == 'c' && 
+						field[5] == 'l' && 
+						field[6] == 'o' && 
+						field[7] == 's' && 
+						field[8] == 'e' && 
+						field[9] == 'd' )  /* last field in the file - strange bahaviour*/
+					{
+						fsd_log_debug(("WT - Date changed. Closing log file"));
+						date_changed = true;
+						log_match = false;
+					}
+					
+					ptr += n; 
+					if ( *ptr != ';' )
+					{
+						break; /* end of line */
+					}
+					field_n++;
+					++ptr;
+				}		
+
+				if( strlcpy(buffer,"",sizeof(buffer)) > sizeof(buffer) ) {
+					fsd_log_error(("WT - strlcpy error"));
+				}
+
+				fsd_free(temp_date);			
+			}
+
+			fsd_mutex_unlock( &self->mutex );	
+			usleep(1000000);
+			fsd_mutex_lock( &self->mutex );
+		 }
+		EXCEPT_DEFAULT
+		 {
+			const fsd_exc_t *e = fsd_exc_get();
+
+			fsd_log_error(( "wait thread: <%d:%s>", e->code(e), e->message(e) ));
+			fsd_exc_reraise();
+		 }
+		END_TRY
+
+		if(fd != -1)
+			close(fd);
+		fsd_log_debug(("Log file closed"));
+	 }
 	FINALLY
-	{
-		pbsdrmaa_log_reader_destroy( log_reader );
-	}
+	 {
+	 	fsd_log_debug(("WT - Terminated."));	
+	 	fsd_mutex_unlock( &self->mutex );
+	 }
 	END_TRY
-	
+
 	fsd_log_return(( " =NULL" ));
 	return NULL;
Index: trunk/pbs_drmaa/drmaa.c
===================================================================
--- trunk/pbs_drmaa/drmaa.c	(revision 23)
+++ trunk/pbs_drmaa/drmaa.c	(revision 1)
@@ -1,3 +1,3 @@
-/* $Id$ */
+/* $Id: drmaa.c 353 2010-10-18 13:45:14Z mamonski $ */
 /*
  *  FedStage DRMAA for PBS Pro
@@ -124,5 +124,5 @@
 		)
 {
-	*exited = (stat <= 125) && (stat != -1);
+	*exited = (stat <= 125);
 	return DRMAA_ERRNO_SUCCESS;
 }
Index: trunk/pbs_drmaa/pbs_drmaa.conf.example
===================================================================
--- trunk/pbs_drmaa/pbs_drmaa.conf.example	(revision 12)
+++ trunk/pbs_drmaa/pbs_drmaa.conf.example	(revision 1)
@@ -1,3 +1,3 @@
-# $Id$
+# $Id: pbs_drmaa.conf.example 2420 2009-06-24 14:40:21Z lukasz $
 # pbs_drmaa.conf - Sample pbs_drmaa configuration file.
 
Index: trunk/pbs_drmaa/Makefile.am
===================================================================
--- trunk/pbs_drmaa/Makefile.am	(revision 103)
+++ trunk/pbs_drmaa/Makefile.am	(revision 1)
@@ -1,3 +1,3 @@
-# $Id$
+# $Id: Makefile.am 2420 2009-06-24 14:40:21Z lukasz $
 # 
 # FedStage DRMAA for PBS Professional
@@ -27,26 +27,10 @@
  drmaa.c \
  job.c job.h \
- pbs_attrib.h \
+ pbs_attrib.gperf pbs_attrib.h \
  session.c session.h \
  submit.c submit.h \
- util.c util.h \
- log_reader.c log_reader.h \
- pbs_conn.c pbs_conn.h 
-
-
-if PBS_PROFESSIONAL
-GPERF_INPUT= pbs_attrib_pro.gperf
-else
-GPERF_INPUT= pbs_attrib.gperf
-endif
-
-libdrmaa_la_SOURCES += $(GPERF_INPUT)
-
-BUILT_SOURCES       = $(GPERF_INPUT:.gperf=.c)
-EXTRA_DIST          = $(GPERF_INPUT:.gperf=.c)
-
-if TORQUE4
-libdrmaa_la_SOURCES += torque4.cpp torque4.h
-endif
+ util.c util.h
+BUILT_SOURCES       = pbs_attrib.c
+EXTRA_DIST          = pbs_attrib.c
 dist_sysconf_DATA   = pbs_drmaa.conf.example
 libdrmaa_la_LIBADD  = ../drmaa_utils/drmaa_utils/libdrmaa_utils.la @PBS_LIBS@
@@ -58,4 +42,4 @@
 
 if GCC
-$(GPERF_INPUT:.gperf=.lo): CFLAGS += @GCC_W_NO_MISSING_FIELD_INITIALIZERS@
+pbs_attrib.lo: CFLAGS += @GCC_W_NO_MISSING_FIELD_INITIALIZERS@
 endif
Index: trunk/pbs_drmaa/session.h
===================================================================
--- trunk/pbs_drmaa/session.h	(revision 85)
+++ trunk/pbs_drmaa/session.h	(revision 1)
@@ -1,3 +1,3 @@
-/* $Id$ */
+/* $Id: session.h 323 2010-09-21 21:31:29Z mmatloka $ */
 /*
  *  FedStage DRMAA for PBS Pro
@@ -27,26 +27,32 @@
 #include <drmaa_utils/session.h>
 
-#include <pbs_drmaa/pbs_conn.h>
-
 typedef struct pbsdrmaa_session_s pbsdrmaa_session_t;
 
-fsd_drmaa_session_t *pbsdrmaa_session_new( const char *contact );
+fsd_drmaa_session_t *
+pbsdrmaa_session_new( const char *contact );
 
 struct pbsdrmaa_session_s {
 	fsd_drmaa_session_t super;
 
-	void (*super_destroy)( fsd_drmaa_session_t *self );
+	bool (*
+	do_drm_keeps_completed_jobs)( pbsdrmaa_session_t *self );
 
-	void (*super_apply_configuration)(fsd_drmaa_session_t *self);
+	void (*
+	super_destroy)( fsd_drmaa_session_t *self );
+
+	void (*
+	super_apply_configuration)(fsd_drmaa_session_t *self);
 
 	/*
 	 * Pointer to standard wait_thread drmaa_utils function
 	 */
-	void* (*super_wait_thread)( fsd_drmaa_session_t *self );
+        void* (*
+        super_wait_thread)( fsd_drmaa_session_t *self );
 
 	/*
-	 * PBS connection handle
+	 * PBS connection (or -1 if not connected).
+	 * A descriptor of socket conencted to PBS server.
 	 */
-	pbsdrmaa_pbs_conn_t *pbs_connection;
+	int pbs_conn;
 
 	/*
@@ -66,32 +72,12 @@
 
 	/*
-	 * Log file initial size - used by wait_thread which reads log files TODO: check if it can be safely moved to log_reader
+	 * Log file initial size - used by wait_thread which reads log files
  	 */
 	off_t log_file_initial_size;
 
 	/*
-	 * Time we checked log file initial size - used by wait_thread which reads log files TODO: check if it can be safely moved to log_reader
+	 * Time we checked log file initial size - used by wait_thread which reads log files
  	 */
-	time_t log_file_initial_time;
-
-	/*
-	 * Maximal number of retires in pbs_connect. Default 3
-	 */
-	int max_retries_count;
-
-	/*
-	 * Wait thread sleep time (in seconds). Default 1s.
-	 */
-	int wait_thread_sleep_time;
-
-	/*
-	 * The prefix of the directory where the job exit status information is stored (default: %HOME/.pbs-drmaa/
-	 */
-	char *job_exit_status_file_prefix;
-
-	/*
-	 * PBS Max connection time
-	 */
-	int connection_max_lifetime;
+	struct tm log_file_initial_time;
 };
 
Index: trunk/pbs_drmaa/pbs_drmaa.h
===================================================================
--- trunk/pbs_drmaa/pbs_drmaa.h	(revision 1)
+++ trunk/pbs_drmaa/pbs_drmaa.h	(revision 1)
@@ -0,0 +1,120 @@
+/* $Id: pbs_drmaa.h 2 2009-10-12 09:51:22Z mamonski $ */
+/*
+ *  FedStage DRMAA for PBS Pro
+ *  Copyright (C) 2006-2007  FedStage Systems
+ *
+ *  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/>.
+ */
+
+#ifndef __DRMAA__PBS_DRMAA_H
+#define __DRMAA__PBS_DRMAA_H
+
+#ifdef HAVE_CONFIG_H
+#	include <config.h>
+#endif
+
+#include <sys/types.h>
+#include <stdbool.h>
+#include <time.h>
+#include <pbs_ifl.h>
+
+#include <drmaa_utils/common.h>
+#include <pbs_drmaa/pbs_attrib.h>
+
+
+/** PBS DRMAA specific session data. */
+struct drmaa_session_impl_s {
+	int                 pbs_conn;    /**< PBS connection (or -1). */
+	drmaa_mutex_t       conn_mutex;  /**< Mutex for PBS connection. */
+	drmaa_thread_t      wait_thread;
+	bool                wait_thread_started;
+	struct attrl       *status_attrl;
+};
+
+
+enum { PBS_ATTRIBS_BITSET_SIZE = (N_PBS_DRMAA_ATTRIBS+31) / 32 };
+struct drmaa_submit_impl_s {
+	struct attrl *pbs_attribs;
+	uint32_t pbs_attribs_bitset[ PBS_ATTRIBS_BITSET_SIZE ];
+	char *script_filename;
+};
+
+
+void *
+drmaa_wait_thread( void *arg );
+
+drmaa_submit_ctx_t *
+drmaa_create_submission_context(
+		const drmaa_job_template_t *jt, int bulk_no,
+		drmaa_err_ctx_t *err
+		);
+
+void
+drmaa_free_submission_context( drmaa_submit_ctx_t *c, drmaa_err_ctx_t* );
+
+void drmaa_set_job_defaults        ( drmaa_submit_ctx_t*, drmaa_err_ctx_t* );
+void drmaa_create_job_script       ( drmaa_submit_ctx_t*, drmaa_err_ctx_t* );
+void drmaa_set_job_submit_state    ( drmaa_submit_ctx_t*, drmaa_err_ctx_t* );
+void drmaa_set_job_files           ( drmaa_submit_ctx_t*, drmaa_err_ctx_t* );
+void drmaa_set_file_staging        ( drmaa_submit_ctx_t*, drmaa_err_ctx_t* );
+void drmaa_set_job_resources       ( drmaa_submit_ctx_t*, drmaa_err_ctx_t* );
+void drmaa_set_job_environment     ( drmaa_submit_ctx_t*, drmaa_err_ctx_t* );
+void drmaa_set_job_email_notif     ( drmaa_submit_ctx_t*, drmaa_err_ctx_t* );
+void drmaa_apply_native_spec       ( drmaa_submit_ctx_t*, drmaa_err_ctx_t* );
+void drmaa_apply_job_category      ( drmaa_submit_ctx_t*, drmaa_err_ctx_t* );
+char *drmaa_translate_staging( const char *stage, drmaa_err_ctx_t* );
+
+void
+drmaa_parse_qsub_args(
+		drmaa_submit_ctx_t *ctx, const char *string,
+		drmaa_err_ctx_t *err
+		);
+
+void
+drmaa_job_missing( drmaa_job_t *job, drmaa_err_ctx_t *err );
+
+void
+drmaa_add_pbs_attr(
+		drmaa_submit_ctx_t *c,
+		int attr, char *resource, char *value,
+		unsigned set,
+		drmaa_err_ctx_t *err
+		);
+
+char *
+drmaa_write_tmpfile(
+	 const char *content, size_t len,
+	 drmaa_err_ctx_t *err
+	 );
+
+struct attrl *
+drmaa_create_pbs_attrl( drmaa_err_ctx_t *err );
+
+void
+drmaa_log_attrl( const struct attrl *attribute_list, const char *prefix );
+
+void
+drmaa_free_attrl( struct attrl *attr );
+
+void
+drmaa_err_pbs_error( drmaa_err_ctx_t *err );
+
+int
+drmaa_err_map_pbs_error( int pbs_errcode );
+
+#define RAISE_PBS() \
+	drmaa_err_pbs_error( err )
+
+#endif /* __DRMAA__PBS_DRMAA_H */
+
Index: trunk/pbs_drmaa/pbs_attrib.h
===================================================================
--- trunk/pbs_drmaa/pbs_attrib.h	(revision 104)
+++ trunk/pbs_drmaa/pbs_attrib.h	(revision 1)
@@ -1,3 +1,3 @@
-/* $Id$ */
+/* $Id: pbs_attrib.h 256 2010-08-10 16:31:35Z mamonski $ */
 /*
  *  FedStage DRMAA for PBS Pro
@@ -41,5 +41,4 @@
 #define PBSDRMAA_FILE_SIZE_LIMIT        "Resource_List.file"
 #define PBSDRMAA_NICE                   "Resource_List.nice"
-#define PBSDRMAA_MEM_LIMIT              "Resource_List.mem"
 #define PBSDRMAA_VMEM_LIMIT             "Resource_List.vmem"
 #define PBSDRMAA_SINGLE_CPU_TIME_LIMIT  "Resource_List.pcput"
@@ -51,8 +50,4 @@
 #define PBSDRMAA_NODES                  "Resource_List.nodes"
 #define PBSDRMAA_SOFTWARE               "Resource_List.software"
-#define PBSDRMAA_PLACE                  "Resource_List.place"
-#define PBSDRMAA_SELECT                 "Resource_List.select"
-#define PBSDRMAA_PROCS                  "Resource_List.procs"
-#define PBSDRMAA_NCPUS                  "Resource_List.ncpus"
 #define PBSDRMAA_MAIL_POINTS            "Mail_Points"
 #define PBSDRMAA_OUTPUT_PATH            "Output_Path"
@@ -74,5 +69,4 @@
 /* additional job and general attribute names */
 #define PBSDRMAA_EXECUTION_HOST         "exec_host"
-#define PBSDRMAA_EXECUTION_VNODE        "exec_vnode" /* PBS PRO */
 #define PBSDRMAA_JOB_OWNER              "Job_Owner"
 #define PBSDRMAA_RESOURCES_USED         "resources_used"
@@ -81,16 +75,9 @@
 #define PBSDRMAA_SERVER                 "server"
 #define PBSDRMAA_COMMENT                "comment"
+#define PBSDRMAA_EXIT_STATUS            "exit_status"
 #define PBSDRMAA_START_TIME             "start_time"
 #define PBSDRMAA_EXTENSION              "extension"
-#define PBSDRMAA_SUBMIT_ARGS            "submit_args"
-#define PBSDRMAA_MTIME                  "mtime"
-#define PBSDRMAA_NODE_PROPERTIES        "pbsdrmaa.node_properties"
-#define PBSDRMAA_CUSTOM_RESOURCES       "pbsdrmaa.custom_resources"
+#define PBSDRMAA_SUBMIT_ARGS		"submit_args"
 
-#ifdef PBS_PROFESSIONAL
-#	define PBSDRMAA_EXIT_STATUS        	"Exit_status"
-#else
-#	define PBSDRMAA_EXIT_STATUS        	"exit_status"
-#endif
 
 typedef enum {
@@ -107,5 +94,4 @@
 	PBSDRMAA_ATTR_NICE,
 	PBSDRMAA_ATTR_VMEM_LIMIT,
-	PBSDRMAA_ATTR_MEM_LIMIT,
 	PBSDRMAA_ATTR_SINGLE_CPU_TIME_LIMIT,
 	PBSDRMAA_ATTR_SINGLE_RSS_LIMIT,
@@ -115,9 +101,5 @@
 	PBSDRMAA_ATTR_HOST,
 	PBSDRMAA_ATTR_NODES,
-	PBSDRMAA_ATTR_PROCS,
-	PBSDRMAA_ATTR_NCPUS,
 	PBSDRMAA_ATTR_SOFTWARE,
-	PBSDRMAA_ATTR_PLACE,
-	PBSDRMAA_ATTR_SELECT,
 	PBSDRMAA_ATTR_MAIL_POINTS,
 	PBSDRMAA_ATTR_OUTPUT_PATH,
@@ -139,5 +121,4 @@
 	/* additional job and general attribute names */
 	PBSDRMAA_ATTR_EXECUTION_HOST,
-	PBSDRMAA_ATTR_EXECUTION_VNODE, /* PBS PRO */
 	PBSDRMAA_ATTR_JOB_OWNER,
 	PBSDRMAA_ATTR_RESOURCES_USED,
@@ -151,6 +132,61 @@
 	PBSDRMAA_ATTR_SUBMIT_ARGS,
 	PBSDRMAA_ATTR_MTIME,
-	PBSDRMAA_ATTR_NODE_PROPERTIES,
-	PBSDRMAA_ATTR_CUSTOM_RESOURCES,
+
+#if 0
+	/* Additional Torque/OpenPBS attribs (not in DRMAA specification): */
+	/* Used by OpenPBS user commands: */
+	PBSDRMAA_ATTR_CHECKPOINT = DRMAA_N_ATTRIBUTES, /* MAX_DRMAA_ATTR+1, */
+	PBSDRMAA_ATTR_GROUP_LIST,
+	PBSDRMAA_ATTR_HOLD_TYPES,
+	PBSDRMAA_ATTR_KEEP_FILES,
+	PBSDRMAA_ATTR_RESOURCES,
+	PBSDRMAA_ATTR_MAIL_POINTS,
+	PBSDRMAA_ATTR_PRIORITY,
+	PBSDRMAA_ATTR_DESTINATION_QUEUE,
+	PBSDRMAA_ATTR_RERUNABLE,
+	PBSDRMAA_ATTR_USER_LIST,
+	PBSDRMAA_ATTR_ACCOUNT_NAME,
+	PBSDRMAA_ATTR_SHELL,
+	PBSDRMAA_ATTR_DEPENDENCIES,
+	PBSDRMAA_ATTR_INTERACTIVE,
+	PBSDRMAA_ATTR_STAGEIN,
+	PBSDRMAA_ATTR_STAGEOUT,
+
+	/* Additional job and general attribute names: */
+	PBSDRMAA_ATTR_JOB_STATE,
+	PBSDRMAA_ATTR_CTIME,
+	/* PBSDRMAA_ATTR_MTIME, moved to basic attributes - needed to determine job end time*/
+	PBSDRMAA_ATTR_QTIME,
+	PBSDRMAA_ATTR_ETIME,
+	PBSDRMAA_ATTR_RESOURCES_USED,
+	PBSDRMAA_ATTR_EXIT_STATUS,
+	PBSDRMAA_ATTR_JOB_OWNER,
+	PBSDRMAA_ATTR_EUSER,
+	PBSDRMAA_ATTR_EGROUP,
+	PBSDRMAA_ATTR_HOP_COUNT,
+	PBSDRMAA_ATTR_SECURITY,
+	PBSDRMAA_ATTR_SCHEDULER_HINT,
+	PBSDRMAA_ATTR_SERVER,
+	PBSDRMAA_ATTR_QUEUE,
+	PBSDRMAA_ATTR_QUEUE_RANK,
+	PBSDRMAA_ATTR_EXECUTION_HOST,
+	PBSDRMAA_ATTR_TOTAL_JOBS,
+	PBSDRMAA_ATTR_MAX_RUNNING,
+	PBSDRMAA_ATTR_COMMENT,
+	PBSDRMAA_ATTR_JOB_COOKIE,
+	PBSDRMAA_ATTR_HASHNAME,
+	PBSDRMAA_ATTR_SESSION_ID,
+	PBSDRMAA_ATTR_ALT_ID,
+
+	/* Reservation attributes */
+	PBSDRMAA_ATTR_RESERVATION_START,
+	PBSDRMAA_ATTR_RESERVATION_END,
+	PBSDRMAA_ATTR_RESERVATION_DURATION,
+	PBSDRMAA_ATTR_RESERVATION_STATE,
+	PBSDRMAA_ATTR_RESERVATION_SUBSTATE,
+
+	/* Pseudo PBS attributes */
+	PBSDRMAA_ATTR_RESERVATION_ID,
+#endif
 
 	PBSDRMAA_N_PBS_ATTRIBUTES
Index: trunk/pbs_drmaa/torque4.cpp
===================================================================
--- trunk/pbs_drmaa/torque4.cpp	(revision 95)
+++ 	(revision )
@@ -1,17 +1,0 @@
-
-#include "torque4.h"
-
-void hash_add_or_exit_c(memmgr **mm, job_data **head, const char *name, const char *value, int var_type)
-{
-	hash_add_or_exit(mm, head, name, value, var_type);
-}	
-
-int memmgr_init_c(memmgr **mm, int size)
-{
-	return memmgr_init(mm,size);
-}
-
-void memmgr_destroy_c(memmgr **mm)
-{
-	memmgr_destroy(mm);
-}
Index: trunk/pbs_drmaa/log_reader.c
===================================================================
--- trunk/pbs_drmaa/log_reader.c	(revision 104)
+++ 	(revision )
@@ -1,727 +1,0 @@
-/* $Id$ */
-/*
- *  FedStage DRMAA for PBS Pro
- *  Copyright (C) 2006-2007  FedStage Systems
- *
- *  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/>.
- */
-
- #ifdef HAVE_CONFIG_H
-#	include <config.h>
-#endif
-
-#include <stdlib.h>
-#include <ctype.h>
-#include <string.h>
-#include <unistd.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <dirent.h>
-#include <fcntl.h>
-
-#include <pbs_ifl.h>
-#include <pbs_error.h>
-
-#include <drmaa_utils/datetime.h>
-#include <drmaa_utils/drmaa.h>
-#include <drmaa_utils/iter.h>
-#include <drmaa_utils/conf.h>
-#include <drmaa_utils/session.h>
-#include <drmaa_utils/datetime.h>
-
-#include <pbs_drmaa/job.h>
-#include <pbs_drmaa/log_reader.h>
-#include <pbs_drmaa/session.h>
-#include <pbs_drmaa/submit.h>
-#include <pbs_drmaa/util.h>
-#include <pbs_drmaa/pbs_attrib.h>
-
-#include <errno.h>
-
-enum pbsdrmaa_field_id
-{
-	PBSDRMAA_FLD_ID_DATE = 0,
-	PBSDRMAA_FLD_ID_EVENT = 1,
-	PBSDRMAA_FLD_ID_SRC = 2,
-	PBSDRMAA_FLD_ID_OBJ_TYPE = 3,
-	PBSDRMAA_FLD_ID_OBJ_ID = 4,
-	PBSDRMAA_FLD_ID_MSG = 5
-};
-
-
-#define PBSDRMAA_FLD_MSG_0008 "0008"
-#define PBSDRMAA_FLD_MSG_0010 "0010"
-
-enum pbsdrmaa_event_type
-{
-	pbsdrmaa_event_0008 = 8,
-	pbsdrmaa_event_0010 = 10
-};
-
-static void pbsdrmaa_read_log();
-
-static void pbsdrmaa_select_file( pbsdrmaa_log_reader_t * self);
-
-static void pbsdrmaa_close_log( pbsdrmaa_log_reader_t * self);
-
-static void pbsdrmaa_reopen_log( pbsdrmaa_log_reader_t * self);
-
-static time_t pbsdrmaa_parse_log_timestamp(const char *timestamp, char *unixtime_str, size_t size);
-
-static char *pbsdrmaa_get_exec_host_from_accountig(pbsdrmaa_log_reader_t * log_reader, const char *job_id);
-
-/*
- * Snippets from log files
- *
- * PBS Pro
- *
-10/11/2011 14:43:29;0008;Server@nova;Job;2127218.nova;Job Queued at request of mamonski@endor.wcss.wroc.pl, owner = mamonski@endor.wcss.wroc.pl, job name = STDIN, queue = normal
-10/11/2011 14:43:31;0008;Server@nova;Job;2127218.nova;Job Modified at request of Scheduler@nova.wcss.wroc.pl
-10/11/2011 14:43:31;0008;Server@nova;Job;2127218.nova;Job Run at request of Scheduler@nova.wcss.wroc.pl on exec_vnode (wn698:ncpus=3:mem=2048000kb)+(wn700:ncpus=3:mem=2048000kb)
-10/11/2011 14:43:31;0008;Server@nova;Job;2127218.nova;Job Modified at request of Scheduler@nova.wcss.wroc.pl
-10/11/2011 14:43:32;0010;Server@nova;Job;2127218.nova;Exit_status=0 resources_used.cpupercent=0 resources_used.cput=00:00:00 resources_used.mem=1768kb resources_used.ncpus=6 resources_used.vmem=19228kb resources_used.walltime=00:00:01
-
- *
- * Torque
- *
-10/11/2011 14:47:59;0008;PBS_Server;Job;15545337.batch.grid.cyf-kr.edu.pl;Job Queued at request of plgmamonski@ui.cyf-kr.edu.pl, owner = plgmamonski@ui.cyf-kr.edu.pl, job name = STDIN, queue = l_short
-10/11/2011 14:48:23;0008;PBS_Server;Job;15545337.batch.grid.cyf-kr.edu.pl;Job Run at request of root@batch.grid.cyf-kr.edu.pl
-10/11/2011 14:48:24;0010;PBS_Server;Job;15545337.batch.grid.cyf-kr.edu.pl;Exit_status=0 resources_used.cput=00:00:00 resources_used.mem=720kb resources_used.vmem=13308kb resources_used.walltime=00:00:00
-
-deleting job:
-I . PBS Pro
-a) in Q state
-10/16/2011 09:49:25;0008;Server@grass1;Job;2178.grass1.man.poznan.pl;Job Queued at request of mmamonski@grass1.man.poznan.pl, owner = mmamonski@grass1.man.poznan.pl, job name = STDIN, queue = workq
-10/16/2011 09:49:25;0008;Server@grass1;Job;2178.grass1.man.poznan.pl;Job Modified at request of Scheduler@grass1.man.poznan.pl
-10/16/2011 09:49:37;0008;Server@grass1;Job;2178.grass1.man.poznan.pl;Job to be deleted at request of mmamonski@grass1.man.poznan.pl
-10/16/2011 09:49:37;0100;Server@grass1;Job;2178.grass1.man.poznan.pl;dequeuing from workq, state 5
-
-
-b) in R state
-10/16/2011 09:45:12;0080;Server@grass1;Job;2177.grass1.man.poznan.pl;delete job request received
-10/16/2011 09:45:12;0008;Server@grass1;Job;2177.grass1.man.poznan.pl;Job sent signal TermJob on delete
-10/16/2011 09:45:12;0008;Server@grass1;Job;2177.grass1.man.poznan.pl;Job to be deleted at request of mmamonski@grass1.man.poznan.pl
-10/16/2011 09:45:12;0010;Server@grass1;Job;2177.grass1.man.poznan.pl;Exit_status=271 resources_used.cpupercent=0 resources_used.cput=00:00:00 resources_used.mem=2772kb resources_used.ncpus=1 resources_used.vmem=199288kb resources_used.walltime=00:00:26
-10/16/2011 09:45:12;0100;Server@grass1;Job;2177.grass1.man.poznan.pl;dequeuing from workq, state 5
-
-II. Torque
-a) in Q state
-10/15/2011 21:19:25;0008;PBS_Server;Job;113045.grass1.man.poznan.pl;Job deleted at request of mmamonski@grass1.man.poznan.pl
-10/15/2011 21:19:25;0100;PBS_Server;Job;113045.grass1.man.poznan.pl;dequeuing from batch, state EXITING
-
-b) in R state
-10/15/2011 21:19:47;0008;PBS_Server;Job;113046.grass1.man.poznan.pl;Job deleted at request of mmamonski@grass1.man.poznan.pl
-10/15/2011 21:19:47;0008;PBS_Server;Job;113046.grass1.man.poznan.pl;Job sent signal SIGTERM on delete
-10/15/2011 21:19:47;0010;PBS_Server;Job;113046.grass1.man.poznan.pl;Exit_status=271 resources_used.cput=00:00:00 resources_used.mem=0kb resources_used.vmem=0kb resources_used.walltime=00:00:10
-
-Log closed:
-10/16/2011 00:00:17;0002;PBS_Server;Svr;Log;Log closed
-
- */
-pbsdrmaa_log_reader_t * 
-pbsdrmaa_log_reader_new( fsd_drmaa_session_t *session )
-{
-	pbsdrmaa_log_reader_t *volatile self = NULL;
-
-	fsd_log_enter((""));
-
-	TRY
-	{
-		fsd_malloc(self, pbsdrmaa_log_reader_t );
-		
-		self->session = session;
-
-		self->select_file = pbsdrmaa_select_file;
-		self->read_log = pbsdrmaa_read_log;	
-		self->close = pbsdrmaa_close_log;
-		self->reopen = pbsdrmaa_reopen_log;
-		
-		self->run_flag = true;
-		self->fhandle = NULL;
-		self->date_changed = true;
-		self->first_open = true;
-		self->log_path = NULL;
-		self->current_offset = 0;
-		
-	}
-	EXCEPT_DEFAULT
-	{
-		if( self != NULL)
-			fsd_free(self);
-			
-		fsd_exc_reraise();
-	}
-	END_TRY
-
-	fsd_log_return((""));
-
-	return self;
-}
-
-
-void
-pbsdrmaa_log_reader_destroy ( pbsdrmaa_log_reader_t * self )
-{
-	fsd_log_enter((""));
-	TRY
-	{
-		if(self != NULL)
-		{
-			fsd_free(self);	
-		}
-	}
-	EXCEPT_DEFAULT
-	{
-		fsd_exc_reraise();
-	}
-	END_TRY
-	
-	fsd_log_return((""));
-}
-
-
-void
-pbsdrmaa_read_log( pbsdrmaa_log_reader_t * self )
-{
-	fsd_log_enter((""));
-	
-	fsd_mutex_lock( &self->session->mutex );
-
-	TRY
-	 {
-		while( self->run_flag )
-		 {
-			TRY
-			{
-				char *line = NULL;
-				
-				self->select_file(self);
-
-				while ((line = fsd_readline(self->fhandle)) != NULL)
-				 {
-					int field_id = PBSDRMAA_FLD_ID_DATE;
-					char *tok_ctx = NULL;
-					char *field_token = NULL;
-					char *event_timestamp = NULL;
-					int event_type = -1;
-					fsd_job_t *job = NULL;
-
-					/* at first detect if this not the end of log file */
-					if (strstr(line, "Log;Log closed")) /*TODO try to be more effective and safe */
-					 {
-						fsd_log_debug(("WT - Date changed. Closing log file"));
-						self->date_changed = true;
-						goto cleanup;
-					 }
-
-					for (field_token = strtok_r(line, ";", &tok_ctx); field_token; field_token = strtok_r(NULL, ";", &tok_ctx), field_id++)
-					 {
-						if ( field_id == PBSDRMAA_FLD_ID_DATE)
-						 {
-							event_timestamp = field_token;
-#ifdef PBS_PBS_PROFESSIONAL
-							/*additional check */
-							TRY
-							{
-							 (void)pbsdrmaa_parse_log_timestamp(event_timestamp, timestamp_unix, sizeof(timestamp_unix));
-							}
-							EXCEPT_DEFAULT
-							{
-								fsd_log_error(("Failed to parse timestamp: %s. Log corrupted?", event_timestamp));
-							}
-							END_TRY
-#endif
-						 }
-						else if ( field_id == PBSDRMAA_FLD_ID_EVENT)
-						 {
-							if (strncmp(field_token, PBSDRMAA_FLD_MSG_0008, 4) == 0)
-								event_type = pbsdrmaa_event_0008;
-							else if (strncmp(field_token, PBSDRMAA_FLD_MSG_0010, 4) == 0)
-								event_type = pbsdrmaa_event_0010;
-							else
-							 {
-								goto cleanup; /*we are interested only in the above log messages */
-							 }
-						 }
-						else if ( field_id == PBSDRMAA_FLD_ID_SRC)
-						 {
-							/* not used ignore */
-						 }
-						else if (field_id  == PBSDRMAA_FLD_ID_OBJ_TYPE)
-						 {
-							if (strncmp(field_token, "Job", 3) != 0)
-							 {
-								goto cleanup; /* we are interested only in job events */
-							 }
-						 }
-						else if (field_id == PBSDRMAA_FLD_ID_OBJ_ID)
-						 {
-							const char *event_jobid = field_token;
-							
-							if (!isdigit(event_jobid[0]))
-							 {
-								fsd_log_debug(("WT - Invalid job: %s", event_jobid)); 
-								goto cleanup;
-							 }
-
-							job = self->session->get_job( self->session, event_jobid );
-
-							if( job )
-							 {
-								fsd_log_debug(("WT - Found job event: %s", event_jobid));
-							 }
-							else
-							 {
-								fsd_log_debug(("WT - Unknown job: %s", event_jobid)); /* Not a DRMAA job */
-								goto cleanup;
-							 }
-					 	 }
-						else if (field_id == PBSDRMAA_FLD_ID_MSG)
-						 {
-							char *msg = field_token;
-							struct batch_status status;
-							struct attrl *attribs = NULL;
-							bool in_running_state = false;
-
-							if (event_type == pbsdrmaa_event_0008 && strncmp(msg, "Job Queued", 10) == 0)
-							 {
-								/* Queued
-								 * PBS Pro: 10/11/2011 14:43:29;0008;Server@nova;Job;2127218.nova;Job Queued at request of mamonski@endor.wcss.wroc.pl, owner = mamonski@endor.wcss.wroc.pl, job name = STDIN, queue = normal
-								 * Torque:  10/11/2011 14:47:59;0008;PBS_Server;Job;15545337.batch.grid.cyf-kr.edu.pl;Job Queued at request of plgmamonski@ui.cyf-kr.edu.pl, owner = plgmamonski@ui.cyf-kr.edu.pl, job name = STDIN, queue = l_short
-								 */
-								char *p_queue = NULL;
-
-								fsd_log_info(("WT - Detected queuing of job %s", job->job_id));
-
-								if ((p_queue = strstr(msg,"queue =")) == NULL)
-									fsd_exc_raise_fmt(FSD_ERRNO_INTERNAL_ERROR,"No queue attribute found in log line = %s", line);
-
-								attribs = pbsdrmaa_add_attr(attribs, PBSDRMAA_JOB_STATE, "Q");
-								attribs = pbsdrmaa_add_attr(attribs, PBSDRMAA_QUEUE, p_queue + 7);
-							 }
-							else if (event_type == pbsdrmaa_event_0008 && strncmp(msg, "Job Run", 7) == 0)
-							{
-								/*
-								 * Running
-								 * Torque: 10/11/2011 14:48:23;0008;PBS_Server;Job;15545337.batch.grid.cyf-kr.edu.pl;Job Run at request of root@batch.grid.cyf-kr.edu.pl
-								 * PBS Pro: 10/11/2011 14:43:31;0008;Server@nova;Job;2127218.nova;Job Run at request of Scheduler@nova.wcss.wroc.pl on exec_vnode (wn698:ncpus=3:mem=2048000kb)+(wn700:ncpus=3:mem=2048000kb)
-								 */
-								char timestamp_unix[64];
-
-								fsd_log_info(("WT - Detected start of job %s", job->job_id));
-
-								(void)pbsdrmaa_parse_log_timestamp(event_timestamp, timestamp_unix, sizeof(timestamp_unix));
-
-								in_running_state = true;
-
-								attribs = pbsdrmaa_add_attr(attribs, PBSDRMAA_JOB_STATE, "R");
-								attribs = pbsdrmaa_add_attr(attribs, PBSDRMAA_START_TIME, timestamp_unix);
-#ifdef PBS_PROFESSIONAL
-									{
-										char *p_vnode = NULL;
-										if ((p_vnode = strstr(msg, "exec_vnode")))
-										 {
-											attribs = pbsdrmaa_add_attr(attribs, PBSDRMAA_EXECUTION_VNODE, p_vnode + 11);
-										 }
-									}
-#endif
-							 }
-#ifndef PBS_PROFESSIONAL
-							else if (event_type == pbsdrmaa_event_0008 && strncmp(msg, "Job deleted", 11) == 0)
-#else
-							else if (event_type == pbsdrmaa_event_0008 && strncmp(msg, "Job to be deleted", 17) == 0)
-#endif
-							 {
-							/* Deleted
-							 * PBS Pro: 10/16/2011 09:45:12;0008;Server@grass1;Job;2177.grass1.man.poznan.pl;Job to be deleted at request of mmamonski@grass1.man.poznan.pl
-							 * Torque: 10/15/2011 21:19:25;0008;PBS_Server;Job;113045.grass1.man.poznan.pl;Job deleted at request of mmamonski@grass1.man.poznan.pl
-							 */
-								char timestamp_unix[64];
-
-								fsd_log_info(("WT - Detected deletion of job %s", job->job_id));
-
-								(void)pbsdrmaa_parse_log_timestamp(event_timestamp, timestamp_unix, sizeof(timestamp_unix));
-
-								if (job->state < DRMAA_PS_RUNNING)
-								 {
-									fsd_log_info(("WT - Job %s killed before entering running state (%d).", job->job_id, job->state));
-
-#ifdef PBS_PROFESSIONAL
-									attribs = pbsdrmaa_add_attr(attribs, PBSDRMAA_JOB_STATE, "F");
-#else
-									attribs = pbsdrmaa_add_attr(attribs, PBSDRMAA_JOB_STATE, "C");
-#endif
-
-									attribs = pbsdrmaa_add_attr(attribs, PBSDRMAA_MTIME, timestamp_unix);
-									attribs = pbsdrmaa_add_attr(attribs, PBSDRMAA_EXIT_STATUS, "-101");
-								 }
-								else
-								 {
-									fsd_log_info(("WT - Job %s killed after entering running state (%d). Waiting for Completed event...", job->job_id, job->state));
-									goto cleanup; /* job was started, ignore, wait for Exit_status message */
-								 }
-							 }
-							else if (event_type == pbsdrmaa_event_0010 && (strncmp(msg, "Exit_status=", 12) == 0))
-							 {
-							/* Completed:
-							 * PBS Pro: 10/11/2011 14:43:32;0010;Server@nova;Job;2127218.nova;Exit_status=0 resources_used.cpupercent=0 resources_used.cput=00:00:00 resources_used.mem=1768kb resources_used.ncpus=6 resources_used.vmem=19228kb resources_used.walltime=00:00:01
-							 * Torque: 10/11/2011 14:48:24;0010;PBS_Server;Job;15545337.batch.grid.cyf-kr.edu.pl;Exit_status=0 resources_used.cput=00:00:00 resources_used.mem=720kb resources_used.vmem=13308kb resources_used.walltime=00:00:00
-							 */
-								char timestamp_unix[64];
-								time_t timestamp_time_t = pbsdrmaa_parse_log_timestamp(event_timestamp, timestamp_unix, sizeof(timestamp_unix));
-								char *tok_ctx2 = NULL;
-								char *token = NULL;
-
-#ifdef PBS_PBS_PROFESSIONAL
-								attribs = pbsdrmaa_add_attr(attribs, PBSDRMAA_JOB_STATE, "F");
-#else
-								attribs = pbsdrmaa_add_attr(attribs, PBSDRMAA_JOB_STATE, "C");
-#endif
-								attribs = pbsdrmaa_add_attr(attribs, PBSDRMAA_MTIME, timestamp_unix);
-
-								/* tokenize !!! */
-								for (token = strtok_r(msg, " ", &tok_ctx2); token; token = strtok_r(NULL, " ", &tok_ctx2))
-								 {
-									if (strncmp(token, "Exit_status=", 12) == 0)
-									 {
-										token[11] = '\0';
-										attribs = pbsdrmaa_add_attr(attribs, PBSDRMAA_EXIT_STATUS, token + 12);
-										fsd_log_info(("WT - Completion of job %s (Exit_status=%s) detected after %d seconds", job->job_id, token+12, (int)(time(NULL) - timestamp_time_t) ));
-									 }
-									else if (strncmp(token, "resources_used.cput=", 20) == 0)
-									 {
-										token[19] = '\0';
-										attribs = pbsdrmaa_add_attr(attribs, token, token + 20);
-									 }
-									else if (strncmp(token, "resources_used.mem=", 19) == 0)
-									 {
-										token[18] = '\0';
-										attribs = pbsdrmaa_add_attr(attribs, token, token + 19);
-									 }
-									else if (strncmp(token, "resources_used.vmem=", 20) == 0)
-									 {
-										token[19] = '\0';
-										attribs = pbsdrmaa_add_attr(attribs, token, token + 20);
-									 }
-									else if (strncmp(token, "resources_used.walltime=", 24) == 0)
-									 {
-										token[23] = '\0';
-										attribs = pbsdrmaa_add_attr(attribs, token, token + 24);
-									 }
-								 }
-
-								if (!job->execution_hosts)
-								 {
-									char *exec_host = NULL;
-									fsd_log_info(("WT - No execution host information for job %s. Reading accounting logs...", job->job_id));
-									exec_host = pbsdrmaa_get_exec_host_from_accountig(self, job->job_id);
-									if (exec_host)
-									 {
-										attribs = pbsdrmaa_add_attr(attribs, PBSDRMAA_EXECUTION_HOST, exec_host);
-										fsd_free(exec_host);
-									 }
-								 }
-							 }
-							else
-							{
-								fsd_log_debug(("Ignoring msg(type=%d) = %s", event_type,  msg));
-								goto cleanup; /* ignore other job events*/
-							}
-					
-							fsd_log_debug(("WT - updating job: %s", job->job_id ));
-							status.name = job->job_id;
-							status.attribs = attribs;
-
-							((pbsdrmaa_job_t *)job)->update( job, &status );
-
-							if ( in_running_state )
-							 {
-								fsd_log_debug(("WT - forcing update of job: %s", job->job_id ));
-								TRY
-								{
-									job->update_status( job );
-								}
-								EXCEPT_DEFAULT
-								{
-									/*TODO: distinguish between invalid job and internal errors */
-									fsd_log_debug(("Job finished just after entering running state: %s", job->job_id));
-								}
-								END_TRY
-							 }
-
-
-							pbsdrmaa_free_attrl(attribs); /* TODO free on exception */
-
-							fsd_cond_broadcast( &job->status_cond);
-							fsd_cond_broadcast( &self->session->wait_condition );
-
-						 }
-						else
-						 {
-							fsd_assert(0); /*not reached */
-						 }
-					 }
-				cleanup:
-					fsd_free(line); /* TODO what about exceptions */		
-					if ( job )
-						job->release( job );
-
-
-
-				 } /* end of while getline loop */
-
-
-
-				fsd_mutex_unlock( &self->session->mutex );
-
-				/* close */
-				self->close(self);
-
-				sleep(((pbsdrmaa_session_t *)self->session)->wait_thread_sleep_time);
-
-				/* and reopen log file */
-				self->reopen(self);
-
-				fsd_mutex_lock( &self->session->mutex );
-
-				self->run_flag = self->session->wait_thread_run_flag;
-			}
-			EXCEPT_DEFAULT
-			{
-				const fsd_exc_t *e = fsd_exc_get();
-				/* Its better to exit and communicate error rather then let the application to hang */
-				fsd_log_fatal(( "Exception in wait thread: <%d:%s>. Exiting !!!", e->code(e), e->message(e) ));
-				exit(1);
-			}
-			END_TRY
-		 }
-
-		if(self->fhandle)
-			fclose(self->fhandle);
-
-		fsd_log_debug(("WT - Log file closed"));
-	}
-	FINALLY
-	{
-	 	fsd_log_debug(("WT - Terminated."));
-		fsd_mutex_unlock( &self->session->mutex ); /**/
-	}
-	END_TRY
-	
-	fsd_log_return((""));
-}
-
-void
-pbsdrmaa_select_file( pbsdrmaa_log_reader_t * self )
-{
-	pbsdrmaa_session_t *pbssession = (pbsdrmaa_session_t*) self->session;
-	
-	if (self->date_changed)
-	 {
-		int num_tries = 0;
-		struct tm tm; 
-		char *old_log_path = NULL;
-		
-		fsd_log_enter((""));
-		
-		if(!self->first_open)
-			time(&self->t);	
-		else
-			self->t = pbssession->log_file_initial_time;
-			
-		localtime_r(&self->t,&tm);
-				
-		#define DRMAA_WAIT_THREAD_MAX_TRIES (12)
-		/* generate new date, close file and open new */
-		old_log_path = self->log_path;
-
-		self->log_path = fsd_asprintf("%s/server_logs/%04d%02d%02d", pbssession->pbs_home, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
-
-		if(self->fhandle)
-			fclose(self->fhandle);
-
-		fsd_log_info(("Opening log file: %s",self->log_path));
-				
-	retry:
-		if ((self->fhandle = fopen(self->log_path,"r")) == NULL && (num_tries > DRMAA_WAIT_THREAD_MAX_TRIES || self->first_open))
-		 {
-			fsd_log_error(("Can't open log file: %s. Verify pbs_home. Running standard wait_thread.", self->log_path));
-			fsd_log_error(("Remember that without keep_completed set the standard wait_thread won't provide information about job exit status"));
-			/*pbssession->super.enable_wait_thread = false;*/ /* run not wait_thread */
-			pbssession->wait_thread_log = false;
-			pbssession->super.wait_thread = pbssession->super_wait_thread;
-			pbssession->super.wait_thread(self->session);
-		 }
-		else if ( self->fhandle == NULL )
-		 { /* Torque seems not to create a new file immediately after the old one is closed */
-			fsd_log_warning(("Can't open log file: %s. Retries count: %d", self->log_path, num_tries));
-			num_tries++;
-			sleep(2 * num_tries);
-			goto retry;
-		 }
-
-		fsd_log_debug(("Log file opened"));
-
-		if(self->first_open)
-		 {
-			fsd_log_debug(("Log file lseek"));
-
-			if(fseek(self->fhandle, pbssession->log_file_initial_size, SEEK_SET) == (off_t) -1)
-			 {
-				fsd_exc_raise_fmt(FSD_ERRNO_INTERNAL_ERROR,"fseek error");
-			 }
-			self->first_open = false;
-		 }
-		else if (old_log_path && strcmp(old_log_path, self->log_path) == 0)
-		 {
-			fsd_log_info(("PBS restarted. Seeking log file %u", (unsigned int)self->current_offset));
-			if(fseek(self->fhandle, self->current_offset, SEEK_SET) == (off_t) -1)
-			 {
-				fsd_exc_raise_fmt(FSD_ERRNO_INTERNAL_ERROR,"fseek error");
-			 }
-		 }
-
-		self->date_changed = false;
-		
-		fsd_free(old_log_path);
-
-		fsd_log_return((""));
-	}	
-}
-
-time_t
-pbsdrmaa_parse_log_timestamp(const char *timestamp, char *unixtime_str, size_t size)
-{
-	struct tm temp_time_tm;
-	memset(&temp_time_tm, 0, sizeof(temp_time_tm));
-	temp_time_tm.tm_isdst = -1;
-
-	if (strptime(timestamp, "%m/%d/%Y %H:%M:%S", &temp_time_tm) == NULL)
-	 {
-		fsd_exc_raise_fmt(FSD_ERRNO_INTERNAL_ERROR,"WT - failed to parse log timestamp: %s", timestamp);
-	 }
-	else
-	 {
-		time_t temp_time = mktime(&temp_time_tm);
-		snprintf(unixtime_str, size, "%lu", temp_time);
-		return temp_time;
-	 }
-}
-
-char *
-pbsdrmaa_get_exec_host_from_accountig(pbsdrmaa_log_reader_t * log_reader, const char *job_id)
-{
-		pbsdrmaa_session_t *pbssession = (pbsdrmaa_session_t*) log_reader->session;
-		struct tm tm;
-		time_t tm_t;
-		char *line = NULL;
-		char *exec_host = NULL;
-		char *log_path = NULL;
-		FILE *fhandle = NULL;
-
-		fsd_log_enter(("(job_id=%s)", job_id));
-
-		tm_t = time(NULL);
-		localtime_r(&tm_t, &tm);
-
-		log_path = fsd_asprintf("%s/server_priv/accounting/%04d%02d%02d", pbssession->pbs_home, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
-
-		fsd_log_info(("Opening accounting log file: %s", log_path));
-
-		if ((fhandle = fopen(log_path, "r")) == NULL)
-		 {
-			fsd_log_error(("Failed to open accounting log file: %s", log_path));
-			fsd_free(log_path);
-			return NULL;
-		 }
-
-		fsd_free(log_path);
-/*
-10/27/2011 14:09:32;E;114249.grass1.man.poznan.pl;user=drmaa group=drmaa jobname=none queue=shortq ctime=1319717371 qtime=1319717371 etime=1319717371 start=1319717372 owner=drmaa@grass1.man.poznan.pl exec_host=grass4.man.poznan.pl/0 Resource_List.neednodes=1 Resource_List.nodect=1 Resource_List.nodes=1 Resource_List.walltime=02:00:00 session=28561 end=1319717372 Exit_status=0 resources_used.cput=00:00:00 resources_used.mem=0kb resources_used.vmem=0kb resources_used.walltime=00:00:00
- */
-		while ((line = fsd_readline(fhandle)) != NULL)
-		 {
-
-			if (line[20] == 'E'  && strncmp(line + 22, job_id, strlen(job_id)) == 0 )
-			 {
-				char *p = NULL;
-
-				fsd_log_debug(("Matched accounting log record = %s", line));
-
-				if (!(exec_host = strstr(line, "exec_host")))
-				 {
-					fsd_log_error(("Invalid accounting record: %s", exec_host));
-					break;
-				 }
-
-				exec_host += 10;
-
-				p = exec_host;
-				while (*p != ' ' && *p != '\0')
-					p++;
-				*p = '\0';
-
-				break;
-			 }
-
-			fsd_free(line);
-		 }
-
-		if (exec_host)
-		 {
-			fsd_log_info(("Job %s was executing on hosts %s.", job_id, exec_host));
-			exec_host = fsd_strdup(exec_host);
-		 }
-		else
-		 {
-			fsd_log_error(("Could not find executions hosts for %s.", job_id));
-		 }
-
-		if (line)
-			fsd_free(line);
-
-		fclose(fhandle);
-
-		return exec_host;
-}
-
-void
-pbsdrmaa_close_log( pbsdrmaa_log_reader_t * self )
-{
-
-	self->current_offset = ftello(self->fhandle);
-	
-	fsd_log_debug(("Closing log  file (offset=%d)", (int)self->current_offset));
-
-	fclose(self->fhandle);
-
-	self->fhandle = NULL;
-}
-
-void
-pbsdrmaa_reopen_log( pbsdrmaa_log_reader_t * self )
-{
-	fsd_log_debug(("Reopening log file: %s (offset=%d)", self->log_path, (int)self->current_offset));
-
-	if ((self->fhandle = fopen(self->log_path,"r")) == NULL)
-	 {
-		fsd_exc_raise_fmt(FSD_ERRNO_INTERNAL_ERROR,"Failed to reopen log file");
-	 }
-
-	if(fseek(self->fhandle, self->current_offset, SEEK_SET) == (off_t) -1)
-	 {
-		fsd_exc_raise_fmt(FSD_ERRNO_INTERNAL_ERROR,"fseek error");
-	 }
-}
-
Index: trunk/pbs_drmaa/pbs_conn.h
===================================================================
--- trunk/pbs_drmaa/pbs_conn.h	(revision 85)
+++ 	(revision )
@@ -1,75 +1,0 @@
-/* $Id$ */
-/*
- *  PSNC DRMAA for Torque/PBS Pro
- *  Copyright (C) 2012 Poznan Supercomputing and Networking Center
- *
- *  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/>.
- */
- 
-#ifndef __PBS_DRMAA__PBS_CONN_H
-#define __PBS_DRMAA__PBS_CONN_H
-
-#ifdef HAVE_CONFIG_H
-#	include <config.h>
-#endif
-
-#include <stdio.h>
-
-#include <drmaa_utils/job.h>
-#include <drmaa_utils/session.h>
-#include <drmaa_utils/thread.h>
-
-
-#include <pbs_ifl.h>
-
-typedef struct pbsdrmaa_pbs_conn_s pbsdrmaa_pbs_conn_t;
-
-pbsdrmaa_pbs_conn_t *
-pbsdrmaa_pbs_conn_new(
-		fsd_drmaa_session_t * session,
-		const char *server);
-
-void pbsdrmaa_pbs_conn_destroy ( pbsdrmaa_pbs_conn_t * self );
-
-struct pbsdrmaa_pbs_conn_s {
-	fsd_drmaa_session_t *volatile session;
-
-	char* (*submit) ( pbsdrmaa_pbs_conn_t *self, struct attropl *attrib, char *script, char *destination );
-
-	struct batch_status* (*statjob) ( pbsdrmaa_pbs_conn_t *self,  char *job_id, struct attrl *attrib );
-
-	void (*statjob_free) ( pbsdrmaa_pbs_conn_t *self, struct batch_status* job_status );
-
-	void (*sigjob) ( pbsdrmaa_pbs_conn_t *self, char *job_id, char *signal );
-
-	void (*deljob) ( pbsdrmaa_pbs_conn_t *self, char *job_id );
-
-	void (*rlsjob) ( pbsdrmaa_pbs_conn_t *self, char *job_id );
-
-	void (*holdjob) ( pbsdrmaa_pbs_conn_t *self, char *job_id );
-	
-	/* contact string */
-	char *server;
-	/* connection descriptor */
-	int connection_fd;
-	
-	/* timestamp of last connect time */
-	time_t last_connect_time;
-
-	fsd_cond_t autoclose_cond;
-	fsd_mutex_t autoclose_mutex;
-	bool close_connection;
-};
-
-#endif /* __PBS_DRMAA__PBS_CONN_H */
Index: trunk/pbs_drmaa/torque4.h
===================================================================
--- trunk/pbs_drmaa/torque4.h	(revision 95)
+++ 	(revision )
@@ -1,24 +1,0 @@
-#ifdef __cplusplus
-
-#include "u_hash_map_structs.h"
-
-extern "C" {
-#endif
-
-typedef struct job_info
-{
-  memmgr *mm;
-  job_data *job_attr;
-  job_data *res_attr;
-  job_data *user_attr;
-  job_data *client_attr;
-} job_info;
-
-
-void hash_add_or_exit_c(memmgr **mm, job_data **head, const char *name, const char *value, int var_type);
-int memmgr_init_c(memmgr **mm, int size);
-void memmgr_destroy_c(memmgr **mm);
-
-#ifdef __cplusplus
-}
-#endif
Index: trunk/pbs_drmaa/log_reader.h
===================================================================
--- trunk/pbs_drmaa/log_reader.h	(revision 48)
+++ 	(revision )
@@ -1,72 +1,0 @@
-/* $Id$ */
-/*
- *  FedStage DRMAA for PBS Pro
- *  Copyright (C) 2006-2009  FedStage Systems
- *
- *  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/>.
- */
- 
-#ifndef __PBS_DRMAA__LOG_READER_H
-#define __PBS_DRMAA__LOG_READER_H
-
-#ifdef HAVE_CONFIG_H
-#	include <config.h>
-#endif
-
-#include <stdio.h>
-
-#include <drmaa_utils/job.h>
-#include <drmaa_utils/session.h>
-
-typedef struct pbsdrmaa_log_reader_s pbsdrmaa_log_reader_t;
-
-pbsdrmaa_log_reader_t * 
-pbsdrmaa_log_reader_new ( fsd_drmaa_session_t * session);
-
-void
-pbsdrmaa_log_reader_destroy ( pbsdrmaa_log_reader_t * self );
-
-struct pbsdrmaa_log_reader_s {
-	fsd_drmaa_session_t *volatile session ;
-	
-	void (*read_log) ( pbsdrmaa_log_reader_t * self );
-	
-	void (*select_file) ( pbsdrmaa_log_reader_t * self );
-	
-	void (*close) ( pbsdrmaa_log_reader_t * self );
-
-	void (*reopen) ( pbsdrmaa_log_reader_t * self );
-
-
-	/* determines if function should run */
-	bool run_flag;
-	
-	/* date of current file */
-	time_t t;	
-	
-	/* log file handle */
-	FILE *fhandle;
-	
-	/* for wait_thread - day changed */
-	bool volatile date_changed;
-	
-	/* for wait_thread - log file first open */
-	bool volatile first_open;	
-
-	char *volatile log_path;
-
-	off_t volatile current_offset;
-};
-
-#endif /* __PBS_DRMAA__LOG_READER_H */
Index: trunk/pbs_drmaa/pbs_conn.c
===================================================================
--- trunk/pbs_drmaa/pbs_conn.c	(revision 101)
+++ 	(revision )
@@ -1,648 +1,0 @@
-/* $Id$ */
-/*
- *  FedStage DRMAA for PBS Pro
- *  Copyright (C) 2006-2007  FedStage Systems
- *
- *  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/>.
- */
-
-#ifdef HAVE_CONFIG_H
-#	include <config.h>
-#endif
-
-#include <pbs_error.h>
-
-#include <drmaa_utils/datetime.h>
-#include <drmaa_utils/drmaa.h>
-#include <drmaa_utils/iter.h>
-#include <drmaa_utils/conf.h>
-#include <drmaa_utils/datetime.h>
-
-#include <pbs_drmaa/session.h>
-#include <pbs_drmaa/pbs_conn.h>
-#include <pbs_drmaa/util.h>
-
-#include <errno.h>
-#include <signal.h>
-#include <unistd.h>
-
-
-
-static char* pbsdrmaa_pbs_submit( pbsdrmaa_pbs_conn_t *self, struct attropl *attrib, char *script, char *destination );
-
-static struct batch_status* pbsdrmaa_pbs_statjob( pbsdrmaa_pbs_conn_t *self,  char *job_id, struct attrl *attrib );
-
-static void pbsdrmaa_pbs_statjob_free( pbsdrmaa_pbs_conn_t *self, struct batch_status* job_status );
-
-static void pbsdrmaa_pbs_sigjob( pbsdrmaa_pbs_conn_t *self, char *job_id, char *signal );
-
-static void pbsdrmaa_pbs_deljob( pbsdrmaa_pbs_conn_t *self,  char *job_id );
-
-static void pbsdrmaa_pbs_rlsjob( pbsdrmaa_pbs_conn_t *self, char *job_id );
-
-static void pbsdrmaa_pbs_holdjob( pbsdrmaa_pbs_conn_t *self,  char *job_id );
-
-/* static void pbsdrmaa_pbs_connection_autoclose_thread_loop( pbsdrmaa_pbs_conn_t *self, bool reconnect); */
-
-
-static void check_reconnect( pbsdrmaa_pbs_conn_t *self, bool reconnect);
-
-/*
-static void start_autoclose_thread( pbsdrmaa_pbs_conn_t *self );
-
-static void stop_autoclose_thread( pbsdrmaa_pbs_conn_t *self );
-
-static void autoclose_thread_loop( void *data ); */
-
-
-#if defined PBS_PROFESSIONAL && defined PBSE_HISTJOBID
-	#define IS_MISSING_JOB (pbs_errno == PBSE_UNKJOBID || pbs_errno == PBSE_HISTJOBID)
-#else
-	#define IS_MISSING_JOB (pbs_errno == PBSE_UNKJOBID)
-#endif
-#define IS_TRANSIENT_ERROR (pbs_errno == PBSE_PROTOCOL || pbs_errno == PBSE_EXPIRED || pbs_errno == PBSOLDE_PROTOCOL || pbs_errno == PBSOLDE_EXPIRED || pbs_errno == PBSE_BADCRED)
-
-pbsdrmaa_pbs_conn_t * 
-pbsdrmaa_pbs_conn_new( fsd_drmaa_session_t *session, const char *server )
-{
-	pbsdrmaa_pbs_conn_t *volatile self = NULL;
-
-	fsd_log_enter((""));
-
-	TRY
-	  {
-		fsd_malloc(self, pbsdrmaa_pbs_conn_t );
-		
-		self->session = session;
-		
-		self->submit = pbsdrmaa_pbs_submit;
-		self->statjob = pbsdrmaa_pbs_statjob;
-		self->statjob_free = pbsdrmaa_pbs_statjob_free;
-		self->sigjob = pbsdrmaa_pbs_sigjob;
-		self->deljob = pbsdrmaa_pbs_deljob;
-		self->rlsjob = pbsdrmaa_pbs_rlsjob;
-		self->holdjob = pbsdrmaa_pbs_holdjob;
-
-		self->server = fsd_strdup(server);
-
-		self->connection_fd = -1;
-
-		/*ignore SIGPIPE - otherwise pbs_disconnect cause the program to exit */
-		signal(SIGPIPE, SIG_IGN);	
-
-		check_reconnect(self, false);
-	  }
-	EXCEPT_DEFAULT
-	  {
-		if( self != NULL)
-		  {
-			fsd_free(self->server);
-			fsd_free(self);
-
-			if (self->connection_fd != -1)
-			  {
-	                        fsd_log_info(( "pbs_disconnect(%d)", self->connection_fd ));
-				pbs_disconnect(self->connection_fd);
-			  }
-		  }
-			
-		fsd_exc_reraise();
-	  }
-	END_TRY
-
-	fsd_log_return((""));
-
-	return self;
-}
-
-void
-pbsdrmaa_pbs_conn_destroy ( pbsdrmaa_pbs_conn_t * self )
-{
-	fsd_log_enter((""));
-
-	TRY
-	{
-		if(self != NULL)
-		{
-			if (self->connection_fd != -1)
-			  {
-				fsd_log_info(( "pbs_disconnect(%d)", self->connection_fd ));
-				pbs_disconnect(self->connection_fd);
-
-			  }
-			fsd_free(self->server);
-			fsd_free(self);	
-		}
-	}
-	EXCEPT_DEFAULT
-	{
-		fsd_exc_reraise();
-	}
-	END_TRY
-	
-	fsd_log_return((""));
-}
-
-#ifdef HAVE_PBS_SUBMIT_HASH
-
-
-#include <torque4.h>
-
-void set_job_defaults(job_info *ji) {
-  hash_add_or_exit_c(&ji->mm, &ji->job_attr, ATTR_c, CHECKPOINT_UNSPECIFIED, STATIC_DATA);
-
-  hash_add_or_exit_c(&ji->mm, &ji->job_attr, ATTR_h, NO_HOLD, STATIC_DATA);
-
-  hash_add_or_exit_c(&ji->mm, &ji->job_attr, ATTR_j, NO_JOIN, STATIC_DATA);
-
-  hash_add_or_exit_c(&ji->mm, &ji->job_attr, ATTR_k, NO_KEEP, STATIC_DATA);
-
-  hash_add_or_exit_c(&ji->mm, &ji->job_attr, ATTR_m, MAIL_AT_ABORT, STATIC_DATA);
-
-  hash_add_or_exit_c(&ji->mm, &ji->job_attr, ATTR_p, DEFAULT_PRIORITY, STATIC_DATA);
-
-  hash_add_or_exit_c(&ji->mm, &ji->job_attr, ATTR_r, "FALSE", STATIC_DATA);
-  hash_add_or_exit_c(&ji->mm, &ji->job_attr, ATTR_f, "FALSE", STATIC_DATA);
-  
-  hash_add_or_exit_c(&ji->mm, &ji->client_attr, "pbs_dprefix", "#PBS", STATIC_DATA);
-  hash_add_or_exit_c(&ji->mm, &ji->job_attr, ATTR_job_radix, "0", STATIC_DATA);
-  hash_add_or_exit_c(&ji->mm, &ji->job_attr, ATTR_v, "", ENV_DATA);
-}  
-
-
-static char *pbs_submit_4_wrapper(int connection_fd, struct attropl *attrib, char  *script, char *destination)
-{	
-	char *new_jobname = NULL;
-	char *jobname_copy = NULL;
-	char *errmsg = NULL;
-	job_info          ji;
-	int local_errno = 0;
-	struct attropl *p;
-
-	memset(&ji, 0, sizeof(job_info));
-
-	if (memmgr_init_c(&ji.mm, 8192) != PBSE_NONE) /* do not want to use g++ just for this file*/
-	  {
-		pbsdrmaa_exc_raise_pbs( "memmgr_init", connection_fd);
-	  }
-
-	set_job_defaults(&ji);
-
-	for (p = attrib; p; p = p->next) {
-		if (p->resource) {
-			hash_add_or_exit_c(&ji.mm, &ji.res_attr, p->resource, p->value, CMDLINE_DATA);
-		} else {
-			hash_add_or_exit_c(&ji.mm, &ji.job_attr, p->name, p->value, CMDLINE_DATA);
-		}
-	}
-
-
- 	pbs_errno = pbs_submit_hash(
-                  connection_fd,
-                  &ji.mm,
-                  ji.job_attr,
-                  ji.res_attr,
-                  script,
-                  destination,
-                  NULL,
-                  &new_jobname,
-                  &errmsg); 		
-
-	fsd_log_info(("pbs_submit_hash(%s,%s) = %d (jobid=%s)", script, destination, local_errno, new_jobname));
-	
-	jobname_copy = fsd_strdup(new_jobname);
-
-	memmgr_destroy_c(&ji.mm);
-
-	return jobname_copy;
-}
-#endif
-
-char* 
-pbsdrmaa_pbs_submit( pbsdrmaa_pbs_conn_t *self, struct attropl *attrib, char *script, char *destination )
-{
-	char *volatile job_id = NULL;
-	volatile bool first_try = true;
-	volatile bool conn_lock = false;
-
-	fsd_log_enter((""));
-
-	TRY
-	 {
-		conn_lock = fsd_mutex_lock(&self->session->drm_connection_mutex);
-
-		check_reconnect(self, false);
-
-retry:
-
-#ifdef HAVE_PBS_SUBMIT_HASH
-		job_id = pbs_submit_4_wrapper(self->connection_fd, attrib, script, destination);
-#else
-		job_id = pbs_submit(self->connection_fd, attrib, script, destination, NULL);
-#endif
-
-		fsd_log_info(("pbs_submit(%s, %s) = %s", script, destination, job_id));
-
-		if(job_id == NULL)
-		 {
-			fsd_log_error(( "pbs_submit failed, pbs_errno = %d", pbs_errno ));
-			if (IS_TRANSIENT_ERROR && first_try)
-			 {
-				check_reconnect(self, true);
-				first_try = false;
-				goto retry;
-			 }
-			else
-			 {
-				pbsdrmaa_exc_raise_pbs( "pbs_submit", self->connection_fd);
-			 }
-		 }
-	 }
-	EXCEPT_DEFAULT
-	 {
-		fsd_free(job_id);
-		fsd_exc_reraise();
-	 }
-	FINALLY
-	 {
-		if(conn_lock)
-			conn_lock = fsd_mutex_unlock(&self->session->drm_connection_mutex);
-	 }
-	END_TRY
-
-
-	fsd_log_return(("%s", job_id));
-
-	return job_id;
-}
-
-struct batch_status* 
-pbsdrmaa_pbs_statjob( pbsdrmaa_pbs_conn_t *self,  char *job_id, struct attrl *attrib )
-{
-	struct batch_status *volatile status = NULL;
-	volatile bool first_try = true;
-	volatile bool conn_lock = false;
-#if defined PBS_PROFESSIONAL
-    char *stat_job_extend = "x";
-#else
-    char *stat_job_extend = NULL;
-#endif
-
-
-
-	fsd_log_enter((""));
-
-	TRY
-	 {
-		conn_lock = fsd_mutex_lock(&self->session->drm_connection_mutex);
-
-		check_reconnect(self, false);
-
-retry:
-		status = pbs_statjob(self->connection_fd, job_id, attrib, stat_job_extend);
-
-#if defined PBS_PROFESSIONAL
-		fsd_log_info(( "pbs_statjob( fd=%d, job_id=%s, attribs={...}, \"x\" ) = %p", self->connection_fd, job_id, (void*)status));
-#else
-		fsd_log_info(( "pbs_statjob( fd=%d, job_id=%s, attribs={...} ) = %p", self->connection_fd, job_id, (void*)status));
-#endif
-
-		if(status == NULL && pbs_errno)
-		 {
-			if (IS_MISSING_JOB)
-			 {
-				fsd_log_info(( "missing job = %s (code=%d)", job_id, pbs_errno ));
-			 }
-			else if (IS_TRANSIENT_ERROR && first_try)
-			 {
-				fsd_log_info(( "pbs_statjob failed, pbs_errno = %d, retrying", pbs_errno ));
-				check_reconnect(self, true);
-				first_try = false;
-				goto retry;
-			 }
-			else
-			 {
-				pbsdrmaa_exc_raise_pbs( "pbs_statjob", self->connection_fd);
-			 }
-		 }
-	 }
-	EXCEPT_DEFAULT
-	 {
-		if( status != NULL )
-			pbs_statfree( status );
-
-		fsd_exc_reraise();
-	 }
-	FINALLY
-	 {
-		if(conn_lock)
-			conn_lock = fsd_mutex_unlock(&self->session->drm_connection_mutex);
-	 }
-	END_TRY
-
-
-	fsd_log_return((""));
-
-	return status;
-}
-
-void 
-pbsdrmaa_pbs_statjob_free( pbsdrmaa_pbs_conn_t *self, struct batch_status* job_status )
-{
-	fsd_log_enter((""));
-
-	pbs_statfree( job_status );
-}
-
-void 
-pbsdrmaa_pbs_sigjob( pbsdrmaa_pbs_conn_t *self, char *job_id, char *signal_name )
-{
-	int rc = PBSE_NONE;
-	volatile bool first_try = true;
-	volatile bool conn_lock = false;
-
-
-	fsd_log_enter((""));
-
-	TRY
-	 {
-		conn_lock = fsd_mutex_lock(&self->session->drm_connection_mutex);
-
-		check_reconnect(self, false);
-
-retry:
-		rc = pbs_sigjob(self->connection_fd, job_id, signal_name, NULL);
-
-		fsd_log_info(( "pbs_sigjob( fd=%d, job_id=%s, signal_name=%s) = %d", self->connection_fd, job_id, signal_name, rc));
-
-		if(rc != PBSE_NONE)
-		 {
-			fsd_log_error(( "pbs_sigjob failed, pbs_errno = %d", pbs_errno ));
-			if (IS_TRANSIENT_ERROR && first_try)
-			 {
-				check_reconnect(self, true);
-				first_try = false;
-				goto retry;
-			 }
-			else
-			 {
-				pbsdrmaa_exc_raise_pbs( "pbs_sigjob", self->connection_fd);
-			 }
-		 }
-	 }
-	EXCEPT_DEFAULT
-	 {
-		fsd_exc_reraise();
-	 }
-	FINALLY
-	 {
-		if(conn_lock)
-			conn_lock = fsd_mutex_unlock(&self->session->drm_connection_mutex);
-	 }
-	END_TRY
-
-
-	fsd_log_return((""));
-
-}
-
-void 
-pbsdrmaa_pbs_deljob( pbsdrmaa_pbs_conn_t *self, char *job_id )
-{
-	int rc = PBSE_NONE;
-	volatile bool first_try = true;
-	volatile bool conn_lock = false;
-
-
-	fsd_log_enter((""));
-
-	TRY
-	 {
-		conn_lock = fsd_mutex_lock(&self->session->drm_connection_mutex);
-
-		check_reconnect(self, false);
-
-retry:
-		rc = pbs_deljob(self->connection_fd, job_id, NULL);
-
-		fsd_log_info(( "pbs_deljob( fd=%d, job_id=%s) = %d", self->connection_fd, job_id, rc));
-
-		if(rc != PBSE_NONE)
-		 {
-			if (IS_TRANSIENT_ERROR && first_try)
-			 {
-				fsd_log_info(( "pbs_deljob failed, rc = %d, pbs_errno = %d. Retrying...", rc, pbs_errno ));
-				check_reconnect(self, true);
-				first_try = false;
-				goto retry;
-			 }
-			else
-			 {
-				pbsdrmaa_exc_raise_pbs( "pbs_deljob", self->connection_fd);
-			 }
-		 }
-	 }
-	EXCEPT_DEFAULT
-	 {
-		fsd_exc_reraise();
-	 }
-	FINALLY
-	 {
-		if(conn_lock)
-			conn_lock = fsd_mutex_unlock(&self->session->drm_connection_mutex);
-	 }
-	END_TRY
-
-
-	fsd_log_return((""));
-}
-
-void 
-pbsdrmaa_pbs_rlsjob( pbsdrmaa_pbs_conn_t *self, char *job_id )
-{
-	int rc = PBSE_NONE;
-	volatile bool first_try = true;
-	volatile bool conn_lock = false;
-
-
-	fsd_log_enter((""));
-
-	TRY
-	 {
-		conn_lock = fsd_mutex_lock(&self->session->drm_connection_mutex);
-
-		check_reconnect(self, false);
-
-retry:
-		rc = pbs_rlsjob(self->connection_fd, job_id, USER_HOLD, NULL);
-
-		fsd_log_info(( "pbs_rlsjob( fd=%d, job_id=%s) = %d", self->connection_fd, job_id, rc));
-
-		if(rc != PBSE_NONE)
-		 {
-			fsd_log_error(( "pbs_rlsjob failed, rc = %d, pbs_errno = %d", rc,  pbs_errno ));
-			if (IS_TRANSIENT_ERROR && first_try)
-			 {
-				check_reconnect(self, true);
-				first_try = false;
-				goto retry;
-			 }
-			else
-			 {
-				pbsdrmaa_exc_raise_pbs( "pbs_rlsjob", self->connection_fd);
-			 }
-		 }
-	 }
-	EXCEPT_DEFAULT
-	 {
-		fsd_exc_reraise();
-	 }
-	FINALLY
-	 {
-		if(conn_lock)
-			conn_lock = fsd_mutex_unlock(&self->session->drm_connection_mutex);
-	 }
-	END_TRY
-
-
-	fsd_log_return((""));
-}
-
-void 
-pbsdrmaa_pbs_holdjob( pbsdrmaa_pbs_conn_t *self,  char *job_id )
-{
-	int rc = PBSE_NONE;
-	volatile bool first_try = true;
-	volatile bool conn_lock = false;
-
-
-	fsd_log_enter((""));
-
-	TRY
-	 {
-		conn_lock = fsd_mutex_lock(&self->session->drm_connection_mutex);
-
-		check_reconnect(self, false);
-
-retry:
-		rc = pbs_holdjob(self->connection_fd, job_id, USER_HOLD, NULL);
-
-		fsd_log_info(( "pbs_holdjob( fd=%d, job_id=%s) = %d", self->connection_fd, job_id, rc));
-
-		if(rc != PBSE_NONE)
-		 {
-			fsd_log_error(( "pbs_holdjob failed, rc = %d, pbs_errno = %d", rc, pbs_errno ));
-			if (IS_TRANSIENT_ERROR && first_try)
-			 {
-				check_reconnect(self, true);
-				first_try = false;
-				goto retry;
-			 }
-			else
-			 {
-				pbsdrmaa_exc_raise_pbs( "pbs_holdjob", self->connection_fd);
-			 }
-		 }
-	 }
-	EXCEPT_DEFAULT
-	 {
-		fsd_exc_reraise();
-	 }
-	FINALLY
-	 {
-		if(conn_lock)
-			conn_lock = fsd_mutex_unlock(&self->session->drm_connection_mutex);
-	 }
-	END_TRY
-
-
-	fsd_log_return((""));
-}
-
-void 
-check_reconnect( pbsdrmaa_pbs_conn_t *self, bool force_reconnect)
-{
-	int tries_left = ((pbsdrmaa_session_t *)self->session)->max_retries_count;
-	int sleep_time = 1;
-
-	fsd_log_enter(("(%d)", self->connection_fd));
-
-	if ( self->connection_fd != -1 ) 
-	  {
-		if (!force_reconnect)
-		  {
-			fsd_log_return(("(%d)", self->connection_fd));
-			return;
-		  }
-		else
-		 {
-			fsd_log_info(( "pbs_disconnect(%d)", self->connection_fd ));
-			pbs_disconnect(self->connection_fd);
-			self->connection_fd = -1;
-		 }
-	  }
-
-
-
-retry_connect: /* Life... */
-	self->connection_fd = pbs_connect( self->server );
-	fsd_log_info(( "pbs_connect(%s) = %d", self->server, self->connection_fd ));
-	if( self->connection_fd < 0 && tries_left-- )
-	  {
-		sleep(sleep_time);
-		sleep_time *=2;
-		goto retry_connect;
-	  }
-	
-	if( self->connection_fd < 0 )
-		pbsdrmaa_exc_raise_pbs( "pbs_connect", self->connection_fd );
-	
-	fsd_log_return(("(%d)", self->connection_fd));
-}
-
-
-/*
-void start_autoclose_thread( pbsdrmaa_pbs_conn_t *self )
-{
-
-
-}
-
-void stop_autoclose_thread( pbsdrmaa_pbs_conn_t *self )
-{
-
-
-}
-
-void autoclose_thread_loop( void *data )
-{
-	pbsdrmaa_pbs_conn_t *self = (pbsdrmaa_pbs_conn_t *)data;
-	struct timespec wait_time;
-
-	fsd_mutex_lock(&self->session->drm_connection_mutex);
-
-	if (fsd_cond_timedwait(&self->autoclose_cond, &self->session->drm_connection_mutex, wait_time);
-	 {
-		fsd_log_debug("autoclose thread signaled, waiting again");
-	 }
-	else
-	 {
-		fsd_log_info("autoclosing PBS connection: fd=%d, time_diff=%d", self->connection_fd, (int)(time(NULL) - self->last_connect_time));
-		pbs_disconnect(self->connection_fd);
-		self->connection_fd = -1;
-	 }
-
-	fsd_mutex_unlock(&self->session->drm_connection_mutex);
-}
-*/
Index: trunk/.svnignore
===================================================================
--- trunk/.svnignore	(revision 46)
+++ trunk/.svnignore	(revision 1)
@@ -1,5 +1,3 @@
 configure
-.project
-.cproject
 Makefile.in
 config.log
@@ -18,5 +16,6 @@
 pbs_attrib.c
 del_all_jobs
-pbs_drmaa-1.0.11.tar.gz
+pbs_drmaa-1.0.2.tar.gz
+pbs_drmaa-1.0.3.tar.gz
 pbs_drmaa
 .svnignore
@@ -34,4 +33,2 @@
 readme.aux
 readme.log
-drmaa-run
-hpc-bash
Index: trunk/README
===================================================================
--- trunk/README	(revision 12)
+++ trunk/README	(revision 1)
@@ -1,4 +1,1191 @@
-The manual for the DRMAA for Torque/PBS Pro (since version 1.0.7) is available 
-at the project wiki: 
-
-  http://apps.man.poznan.pl/trac/pbs-drmaa/wiki
+=================================
+DRMAA for Torque/PBS Professional
+=================================
+
+:Authors:       Åukasz CieÅnik <lukasz.ciesnik@fedstage.com>, 
+				MichaÅ MatÅoka <michal.matloka@student.put.poznan.pl>, 
+				Mariusz Mamonski <mamonski@man.poznan.pl>
+:Contact:       Mariusz Mamonski <mamonski@man.poznan.pl>
+:Date:          $Date: 2010-07-07 17:05:39 +0200 (Wed, 07 Jul 2010) $
+:Version:       1.0.3
+:Revision:      $Revision: 386 $
+:Copyright:     Copyright (C) 2006-2008 FedStage Systems
+
+:Abstract:  This document describes installation, configuration and usage
+  of `DRMAA for Torque/PBS Pro`_ library (PBS DRMAA for short).
+
+.. meta::
+  :http-equiv=Content-Language: en
+  :http-equiv=Content-Type: application/xhtml+xml; charset=UTF-8
+  :description lang=en: DRMAA implementation for PBS systems.
+  :keywords: DRMAA, PBS, Torque, PBS Professional, PBS Pro, Portable Batch System
+
+.. contents::
+
+.. default-role:: literal
+
+
+Introduction
+============
+
+DRMAA for Torque/PBS Pro is implementation of `Open Grid Forum`_ DRMAA_
+(Distributed Resource Management Application API) specification_ for
+submission and control jobs to PBS_ systems: `PBS Professional`_, Torque_
+and OpenPBS_.  Using DRMAA, grid applications builders, portal developers
+and ISVs can use the same high-level API to link their software with
+different cluster/resource management systems.
+
+This software also enables the integration of `SMOA Computing`_
+with the underlying Torque/PBS Pro system for remote multi-user job submission
+and control over Web Services.
+
+This manual can be found in HTML and PDF formats in ``doc`` directory.
+
+
+Installation
+============
+
+To compile the library just go to main source directory and type::
+
+  $ ./configure [--prefix=/installation/directory] && make
+
+If you had installed PBS in a non standard directory pass it
+in ``--with-pbs`` configure parameter.  There are no unusual requirements
+for basic usage of library: ANSI C compiler and standard make should
+suffice (if linking against PBS Professional you will need also the OpenSSL library).  
+If you have taken sources directly from SVN repository you would 
+need additional `developer tools`_. For further information regarding GNU 
+build system see the INSTALL file.
+
+For Torque_ it is advised to configure queues so jobs are leaved after
+the completion.  To achieve this simply type the following command for
+all queues which are intended to use with PBS DRMAA::
+
+  # qmgr -c "set queue QUEUE_NAME keep_completed = 60"
+
+The value of the ``keep_completed`` parameter denotes a number of
+seconds jobs will have to wait in the queue after the completion (and
+should be greater then ``pool_delay`` value in PBS DRMAA configuration_).
+It enables the DRMAA library to retrieve the information about finished
+jobs.
+
+Alternatively you can configure the DRMAA library to use Torque server daemon logs
+as information source for terminated jobs (consult next section for details) 
+
+Configuration
+=============
+
+During DRMAA session initialization (``drmaa_init``) library tries to read
+its configuration parameters from locations:
+``/etc/pbs_drmaa.conf``, ``~/.pbs_drmaa.conf`` and from file given in
+``PBS_DRMAA_CONF`` environment variable (if set to non-empty string).
+If multiple configuration sources are present then all configurations
+are merged with values from user-defined files taking precedence
+(in following order: ``$PBS_DRMAA_CONF``, ``~/.pbs_drmaa.conf``,
+``/etc/pbs_drmaa.conf``).
+
+Currently recognized configuration parameters are:
+
+  pool_delay
+    Amount of time (in seconds) between successive checks of unfinished job(s).
+
+     Type: integer, Default: 5
+
+  wait_thread
+    Value 1 enables single "wait thread" for updating jobs status. 
+    With ``pbs_home`` set enables wait_thread which reads PBS log files (instead of polling PBS daemons).
+     
+     Type: integer, Default: 0
+
+  pbs_home
+    Path to Torque/PBS Pro spool directory that contains server logs (e.g.: /var/spool/pbs).
+    
+     Type: string, Default: not set
+     
+  job_categories
+    Dictionary of job categories.  It's keys are job categories names
+    mapped to `native specification`_ strings.  Attributes set by
+    job category can be overridden by corresponding DRMAA attributes
+    or native specification.  Special category name ``default``
+    is used when ``drmaa_job_category`` job attribute was not set.
+
+  cache_job_state
+    According to the DRMAA specification every `drmaa_job_ps()` call should
+    query DRM system for job state.  With this option one may optimize
+    communication with DRM.  If set to positive integer `drmaa_job_ps()`
+    returns remembered job state without communicating with DRM for
+    `cache_job_state` seconds since last update.  By default library
+    conforms to specification (no caching will be performed).
+
+    Type: integer, default: 0
+
+
+.. table::
+  Different modes of operation
+
+  =========== ========= =========== ======================= ===================================
+  wait_thread pbs_home     mode     keep_completed needed         comments
+  =========== ========= =========== ======================= ===================================
+       0       not set   polling           yes              default configuration
+       1       not set   polling           yes              more effective than above
+       1         set     triggered         no               read access to server logs needed
+  =========== ========= =========== ======================= ===================================
+  
+
+Configuration file syntax
+-------------------------
+
+Configuration file is in form a dictionary.
+Dictionary is set of zero or more key-value pairs.
+Key is a string while value could be a string, an integer
+or another dictionary.
+::
+
+  configuration: dictionary | dictionary_body
+  dictionary: '{' dictionary_body '}'
+  dictionary_body: (string ':' value ',')*
+  value: integer | string | dictionary
+  string: unquoted-string | single-quoted-string | double-quoted-string
+  unquoted-string: [^ \t\n\r:,0-9][^ \t\n\r:,]*
+  single-quoted-string: '[^']*'
+  double-quoted-string: "[^"]*"
+  integer: [0-9]+
+
+Configuration file example
+--------------------------
+
+::
+  
+  # pbs_drmaa.conf - Sample pbs_drmaa configuration file.
+  
+  wait_thread: 0,
+
+  #pool_delay: 5,
+
+  job_categories: {
+	#default: "-k n", # delete output files from execution hosts
+	longterm: "-p -100 -l nice=5",
+	amd64: "-l arch=amd64",
+	python: "-l software=python",
+	java: "-l software=java,vmem=500mb -v PATH=/opt/sun-jdk-1.6:/usr/bin:/bin",
+	#test: "-u test -q testing",
+  },
+  
+
+Native specification
+====================
+
+DRMAA interface allows to pass DRM dependant job submission options.
+Those options may be specified by settings ``drmaa_native_specification``. ``drmaa_native_specification``
+accepts space delimited ``qsub``. ``qsub``
+options which does not set job attributes (`-b`, `-z`, `-C`) as
+well as meant for submission of interactive jobs (`-I`, `-X`) or
+to specify directories (`-d`, `-D`) are *not* supported.
+Also instead of `-W` option following long options are accepted
+within native specification: `--depend`, `--group-list`, `--stagein`
+and `--stageout`.  For detailed description of each option see PBS
+documentation.
+
+Attributes set in native specification overrides corresponding DRMAA job
+attributes.
+
+.. table::
+  Native specification strings with corresponding DRMAA attributes.
+
+  ===================== =============== ============ ====================
+  DRMAA attribute       PBS attribute   PBS resource native specification
+  ===================== =============== ============ ====================
+                      Attributes which get overridden                   
+  -----------------------------------------------------------------------
+  drmaa_job_name        Job_Name                     `-N` job name       
+  drmaa_output_path     Output_Path                  `-o` output path    
+  drmaa_error_path      Error_Path                   `-e` error path     
+  drmaa_join_files      Join_Path                    `-j` join options   
+  drmaa_block_email     Mail_Points                  `-m` mail options   
+  drmaa_start_time      Execution_Time               `-a` start time     
+  drmaa_js_state        Hold_Types                   `-h`                
+  ..                    Account_Name                 `-A` account string 
+  ..                    Checkpoint                   `-c` interval       
+  ..                    Keep_Files                   `-k` keep           
+  ..                    Priority                     `-p` priority       
+  ..                    destination                  `-q` queue          
+  ..                    Rerunable                    `-r` y/n            
+  ..                    Shell_Path_List              `-S` path list      
+  ..                    User_List                    `-u` user list      
+  ..                    group_list                   `--group_list=`\groups 
+  drmaa_v_env           Variable_List                `-v` variable list  
+  ..                    Variable_List                `-V`                
+  drmaa_v_email         Mail_Users                   `-M` user list      
+  drmaa_duration_hlimit Resource_List   cput         `-l cput=`\limit    
+  drmaa_wct_hlimit      Resource_List   walltime     `-l walltime=`\limit
+  ..                    Resource_List                `-l` resources      
+  ..                    depend                       `--depend=`\dependency
+  ..                    stagein                      `--stagein=`\stagein 
+  ..                    stageout                     `--stageout=`\stageout
+  ===================== =============== ============ ====================
+
+
+Release notes
+=============
+
+Changes in 1.0.4 release
+------------------------
+ * fix "mtime" date parsing ('triggered' mode)
+ * fix "submit_args" attribute bug (PBS Professional only)
+
+Changes in 1.0.3 release
+------------------------
+
+ * new implementation of the "wait thread" which reads PBS log files (increased scalability)
+ * support for native specification attribute
+ * memleak fixes
+ * testsuite passed on PBS Pro 10
+ * exit codes 126-127 cause the drmaa_wifaborted() to return true
+ * other bug fixes
+
+Changes in 1.0.2 release
+------------------------
+
+ * automatic reconnect on PBS connection errors 
+ * static linkage with DRMAA utilities
+ * other bug fixes
+ 
+Changes in 1.0.1 release
+------------------------
+
+ * number of attributes implemented:
+
+   - ``drmaa_start_time``
+   - ``drmaa_duration_hlimit``
+   - ``drmaa_wct_hlimit``
+   - ``drmaa_native_specification``
+   - ``drmaa_job_category``
+
+ * configuration file(s)
+ * separate wait thread
+ * lot of bug fixes
+ * more robust code
+ * separated DRMAA utilities library
+ * Python driven test-suite
+
+
+Known bugs and limitations
+--------------------------
+
+Library covers nearly all DRMAA 1.0 specification_ with exceptions
+listed below.  It passes the `official DRMAA test-suite`_ except of tests
+which require job termination status.  All mandatory and some optional
+job attributes (namely: transfer files, wall clock time hard limit,
+job run duration hard limit) are implemented.
+
+Known limitations imposed by PBS API:
+
+ * With `PBS Pro`_ (and OpenPBS_) retrieving of job termination status is
+   impossible.  For this DRM finished jobs are marked as done with 0
+   return code unless job was terminated through library when they are
+   treated as aborted and killed after receiving SIGTERM.
+
+ * Library accepts job identifiers only of those jobs which
+   were submitted under current session (specification says it should
+   also accept job identifiers from previous sessions and even of
+   jobs submitted in former execution of DRMAA enabled application).
+   This could only be partially fixed as job state needs to be kept by
+   library in order to cope with PBS shortcomings.
+
+ * Job termination (when job is running) is realized by PBS
+   by sending SIGTERM and/or SIGKILL therefore retrieving
+   those signals cannot be distinguished from abort using
+   ``drmaa_control(DRMAA_CONTROL_TERMINATE)``.  Then job termination
+   state is marked as "aborted" and "signaled" whatever is the state.
+
+ * ``drmaa_wcoredump()`` always returns ``false``.
+
+ * Waiting functions (``drmaa_wait()`` and ``drmaa_synchronize()``)
+   must pool DRM to find out whether job finished.
+
+
+Test-suite
+----------
+
+The DRMAA for Torque/PBS Pro library was successfully tested with
+`PBS Pro`_ 10 (10.0.0.82981) and Torque_ 2.5.1 on Linux OS.  Following
+table presents results of tests from
+`Official DRMAA test-suite`_ (originally developed for Sun Grid Engine).
+
+.. table::
+  Mode - Polling
+
+  =============================================== =========== ============ 
+                  Test name                        PBS Pro 10  Torque 2.5.1 
+  =============================================== =========== ============ 
+  test_mt_exit_during_submit                        passed       passed           
+  test_mt_exit_during_submit_or_wait                passed       passed           
+  test_mt_submit_before_init_wait                   passed       passed            
+  test_mt_submit_mt_wait                            passed       passed            
+  test_mt_submit_wait                               passed       passed            
+  test_st_attribute_change                          passed       passed            
+  test_st_bulk_singlesubmit_wait_individual         passed       passed            
+  test_st_bulk_submit_in_hold_session_delete        passed       passed            
+  test_st_bulk_submit_in_hold_session_release       passed       passed            
+  test_st_bulk_submit_in_hold_single_delete         passed       passed            
+  test_st_bulk_submit_in_hold_single_release        passed       passed            
+  test_st_bulk_submit_wait                          passed       passed            
+  test_st_contact                                   passed       passed            
+  test_st_drm_system                                passed       passed            
+  test_st_drmaa_impl                                passed       passed            
+  test_st_empty_session_control                     passed       passed            
+  test_st_empty_session_synchronize_dispose         passed       passed            
+  test_st_empty_session_synchronize_nodispose       passed       passed            
+  test_st_empty_session_wait                        passed       passed            
+  test_st_error_file_failure                      FAILED [1]_    passed       
+  test_st_exit_status                             FAILED [1]_    passed       
+  test_st_input_file_failure                      FAILED [1]_    passed       
+  test_st_mult_exit                                 passed       passed        
+  test_st_mult_init                                 passed       passed         
+  test_st_output_file_failure                     FAILED [1]_    passed      
+  test_st_submit_in_hold_delete                     passed       passed         
+  test_st_submit_in_hold_release                    passed       passed         
+  test_st_submit_kill_sig                         FAILED [1]_    passed       
+  test_st_submit_polling_synchronize_timeout        passed       passed        
+  test_st_submit_polling_synchronize_zerotimeout    passed       passed        
+  test_st_submit_polling_wait_timeout               passed       passed        
+  test_st_submit_polling_wait_zerotimeout           passed       passed       
+  test_st_submit_suspend_resume_wait                passed       passed       
+  test_st_submit_wait                               passed       passed       
+  test_st_submitmixture_sync_all_dispose            passed       passed      
+  test_st_submitmixture_sync_all_nodispose          passed       passed       
+  test_st_submitmixture_sync_allids_dispose         passed       passed      
+  test_st_submitmixture_sync_allids_nodispose       passed       passed     
+  test_st_supported_attr                            passed       passed    
+  test_st_supported_vattr                           passed       passed    
+  test_st_usage_check                               passed       passed    
+  test_st_version                                   passed       passed    
+  =============================================== =========== ============ 
+
+.. [1] Due to unavailability of job termination status.
+
+.. table::
+  Mode - Triggered
+
+  =============================================== =========== ============ 
+                  Test name                        PBS Pro 10  Torque 2.5.1 
+  =============================================== =========== ============ 
+  test_mt_exit_during_submit                        passed       passed           
+  test_mt_exit_during_submit_or_wait                passed       passed           
+  test_mt_submit_before_init_wait                   passed       passed            
+  test_mt_submit_mt_wait                            passed       passed            
+  test_mt_submit_wait                               passed       passed            
+  test_st_attribute_change                          passed       passed            
+  test_st_bulk_singlesubmit_wait_individual         passed       passed            
+  test_st_bulk_submit_in_hold_session_delete        passed       passed            
+  test_st_bulk_submit_in_hold_session_release       passed       passed            
+  test_st_bulk_submit_in_hold_single_delete         passed       passed            
+  test_st_bulk_submit_in_hold_single_release        passed       passed            
+  test_st_bulk_submit_wait                          passed       passed            
+  test_st_contact                                   passed       passed            
+  test_st_drm_system                                passed       passed            
+  test_st_drmaa_impl                                passed       passed            
+  test_st_empty_session_control                     passed       passed            
+  test_st_empty_session_synchronize_dispose         passed       passed            
+  test_st_empty_session_synchronize_nodispose       passed       passed            
+  test_st_empty_session_wait                        passed       passed            
+  test_st_error_file_failure                        passed       passed         
+  test_st_exit_status                               passed       passed        
+  test_st_input_file_failure                        passed       passed        
+  test_st_mult_exit                                 passed       passed        
+  test_st_mult_init                                 passed       passed         
+  test_st_output_file_failure                       passed       passed        
+  test_st_submit_in_hold_delete                     passed       passed         
+  test_st_submit_in_hold_release                    passed       passed         
+  test_st_submit_kill_sig                           passed       passed        
+  test_st_submit_polling_synchronize_timeout        passed       passed        
+  test_st_submit_polling_synchronize_zerotimeout    passed       passed        
+  test_st_submit_polling_wait_timeout               passed       passed        
+  test_st_submit_polling_wait_zerotimeout           passed       passed       
+  test_st_submit_suspend_resume_wait                passed       passed       
+  test_st_submit_wait                               passed       passed       
+  test_st_submitmixture_sync_all_dispose            passed       passed      
+  test_st_submitmixture_sync_all_nodispose          passed       passed       
+  test_st_submitmixture_sync_allids_dispose         passed       passed      
+  test_st_submitmixture_sync_allids_nodispose       passed       passed     
+  test_st_supported_attr                            passed       passed    
+  test_st_supported_vattr                           passed       passed    
+  test_st_usage_check                               passed       passed    
+  test_st_version                                   passed       passed    
+  =============================================== =========== ============ 
+
+Developers
+==========
+
+Core functionality of DRMAA is put into ``drmaa_utils`` library.
+This library was created in order to keep consistent common functionality
+of `DRMAA for Torque/PBS Pro`_ and other DRMAA libraries.  As it is
+independent from any particular DRM you may found this library useful for
+developing other DRMAAs.
+
+Developer tools
+---------------
+Although not needed for library user the following tools may be required
+if you intend to develop DRMAA for Torque/PBS Pro library or run tests:
+
+ * GNU autotools (autoconf, automake, libtool),
+ * Bison_ parser generator,
+ * gperf_ perfect hash function generator,
+ * Python_ (with development files) for Docutils_ and running test-suite
+   (at least 2.5 version but not Python 3.* which will introduce
+   incompatibilities),
+ * Pyrex_ a Language for writing Python extension modules (>=0.9.6),
+ * Docutils_ for processing this ``README``,
+ * LaTeX_ for creating documentation in PDF format,
+ * Doxygen_ for generating code documentation.
+
+.. _Bison:     http://www.gnu.org/software/bison/
+.. _gperf:     http://www.gnu.org/software/gperf/
+.. _Python:    http://www.python.org/
+.. _Pyrex:     http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/
+.. _Docutils:  http://docutils.sourceforge.net/
+.. _LaTeX:     http://www.latex-project.org/
+.. _Doxygen:   http://www.stack.nl/~dimitri/doxygen/
+
+
+
+Contact
+=======
+
+The DRMAA library for Torque and PBSPro is curently maintained by `Poznan Supercomputing and Networking Center`_. Please send 
+your comments, questions and bug reports to: 
+
+   Mariusz Mamonski <mamonski@man.poznan.pl>
+
+
+
+
+.. _DRMAA: http://drmaa.org/
+.. _Open Grid Forum: http://www.gridforum.org/
+.. _specification: http://www.ogf.org/documents/GFD.22.pdf
+.. _Official DRMAA test-suite: http://www.drmaa.org/wiki/index.php?pagename=DrmaaTestsuite
+.. _FedStage DRMAA for PBS Pro:
+  http://www.fedstage.com/wiki/FedStage_DRMAA_for_PBS_Pro
+.. _PBS DRMAA: http://www.fedstage.com/wiki/FedStage_DRMAA_for_PBS_Pro
+.. _FedStage Computing: http://www.fedstage.com/wiki/FedStage_Computing
+.. _PBS: http://en.wikipedia.org/wiki/Portable_Batch_System
+.. _PBS Professional: http://www.pbsgridworks.com/
+.. _PBS Pro: http://www.pbsgridworks.com/
+.. _Torque: http://www.clusterresources.com/pages/products/torque-resource-manager.php
+.. _OpenPBS: http://www.openpbs.org/
+.. _Poznan Supercomputing and Networking Center: http://www.man.poznan.pl/online/en/
+
+
+License
+=======
+
+Copyright (C) 2006-2008 FedStage Systems
+
+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/>.
+
+
+GNU General Public License
+--------------------------
+Version 3, 29 June 2007
+
+| Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+| Everyone is permitted to copy and distribute verbatim copies
+| of this license document, but changing it is not allowed.
+
+Preamble
+........
+
+The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+The precise terms and conditions for copying, distribution and
+modification follow.
+
+TERMS AND CONDITIONS
+....................
+
+0.  Definitions.
+    
+    "This License" refers to version 3 of the GNU General Public License.
+    
+    "Copyright" also means copyright-like laws that apply to other kinds of
+    works, such as semiconductor masks.
+    
+    "The Program" refers to any copyrightable work licensed under this
+    License.  Each licensee is addressed as "you".  "Licensees" and
+    "recipients" may be individuals or organizations.
+    
+    To "modify" a work means to copy from or adapt all or part of the work
+    in a fashion requiring copyright permission, other than the making of an
+    exact copy.  The resulting work is called a "modified version" of the
+    earlier work or a work "based on" the earlier work.
+    
+    A "covered work" means either the unmodified Program or a work based
+    on the Program.
+    
+    To "propagate" a work means to do anything with it that, without
+    permission, would make you directly or secondarily liable for
+    infringement under applicable copyright law, except executing it on a
+    computer or modifying a private copy.  Propagation includes copying,
+    distribution (with or without modification), making available to the
+    public, and in some countries other activities as well.
+    
+    To "convey" a work means any kind of propagation that enables other
+    parties to make or receive copies.  Mere interaction with a user through
+    a computer network, with no transfer of a copy, is not conveying.
+    
+    An interactive user interface displays "Appropriate Legal Notices"
+    to the extent that it includes a convenient and prominently visible
+    feature that (1) displays an appropriate copyright notice, and (2)
+    tells the user that there is no warranty for the work (except to the
+    extent that warranties are provided), that licensees may convey the
+    work under this License, and how to view a copy of this License.  If
+    the interface presents a list of user commands or options, such as a
+    menu, a prominent item in the list meets this criterion.
+    
+1.  Source Code.
+    
+    The "source code" for a work means the preferred form of the work
+    for making modifications to it.  "Object code" means any non-source
+    form of a work.
+    
+    A "Standard Interface" means an interface that either is an official
+    standard defined by a recognized standards body, or, in the case of
+    interfaces specified for a particular programming language, one that
+    is widely used among developers working in that language.
+    
+    The "System Libraries" of an executable work include anything, other
+    than the work as a whole, that (a) is included in the normal form of
+    packaging a Major Component, but which is not part of that Major
+    Component, and (b) serves only to enable use of the work with that
+    Major Component, or to implement a Standard Interface for which an
+    implementation is available to the public in source code form.  A
+    "Major Component", in this context, means a major essential component
+    (kernel, window system, and so on) of the specific operating system
+    (if any) on which the executable work runs, or a compiler used to
+    produce the work, or an object code interpreter used to run it.
+    
+    The "Corresponding Source" for a work in object code form means all
+    the source code needed to generate, install, and (for an executable
+    work) run the object code and to modify the work, including scripts to
+    control those activities.  However, it does not include the work's
+    System Libraries, or general-purpose tools or generally available free
+    programs which are used unmodified in performing those activities but
+    which are not part of the work.  For example, Corresponding Source
+    includes interface definition files associated with source files for
+    the work, and the source code for shared libraries and dynamically
+    linked subprograms that the work is specifically designed to require,
+    such as by intimate data communication or control flow between those
+    subprograms and other parts of the work.
+    
+    The Corresponding Source need not include anything that users
+    can regenerate automatically from other parts of the Corresponding
+    Source.
+    
+    The Corresponding Source for a work in source code form is that
+    same work.
+    
+2.  Basic Permissions.
+    
+    All rights granted under this License are granted for the term of
+    copyright on the Program, and are irrevocable provided the stated
+    conditions are met.  This License explicitly affirms your unlimited
+    permission to run the unmodified Program.  The output from running a
+    covered work is covered by this License only if the output, given its
+    content, constitutes a covered work.  This License acknowledges your
+    rights of fair use or other equivalent, as provided by copyright law.
+    
+    You may make, run and propagate covered works that you do not
+    convey, without conditions so long as your license otherwise remains
+    in force.  You may convey covered works to others for the sole purpose
+    of having them make modifications exclusively for you, or provide you
+    with facilities for running those works, provided that you comply with
+    the terms of this License in conveying all material for which you do
+    not control copyright.  Those thus making or running the covered works
+    for you must do so exclusively on your behalf, under your direction
+    and control, on terms that prohibit them from making any copies of
+    your copyrighted material outside their relationship with you.
+    
+    Conveying under any other circumstances is permitted solely under
+    the conditions stated below.  Sublicensing is not allowed; section 10
+    makes it unnecessary.
+    
+3.  Protecting Users' Legal Rights From Anti-Circumvention Law.
+    
+    No covered work shall be deemed part of an effective technological
+    measure under any applicable law fulfilling obligations under article
+    11 of the WIPO copyright treaty adopted on 20 December 1996, or
+    similar laws prohibiting or restricting circumvention of such
+    measures.
+    
+    When you convey a covered work, you waive any legal power to forbid
+    circumvention of technological measures to the extent such circumvention
+    is effected by exercising rights under this License with respect to
+    the covered work, and you disclaim any intention to limit operation or
+    modification of the work as a means of enforcing, against the work's
+    users, your or third parties' legal rights to forbid circumvention of
+    technological measures.
+    
+4.  Conveying Verbatim Copies.
+    
+    You may convey verbatim copies of the Program's source code as you
+    receive it, in any medium, provided that you conspicuously and
+    appropriately publish on each copy an appropriate copyright notice;
+    keep intact all notices stating that this License and any
+    non-permissive terms added in accord with section 7 apply to the code;
+    keep intact all notices of the absence of any warranty; and give all
+    recipients a copy of this License along with the Program.
+    
+    You may charge any price or no price for each copy that you convey,
+    and you may offer support or warranty protection for a fee.
+    
+5.  Conveying Modified Source Versions.
+    
+    You may convey a work based on the Program, or the modifications to
+    produce it from the Program, in the form of source code under the
+    terms of section 4, provided that you also meet all of these conditions:
+    
+     a) The work must carry prominent notices stating that you modified
+        it, and giving a relevant date.
+    
+     b) The work must carry prominent notices stating that it is
+        released under this License and any conditions added under section
+        7.  This requirement modifies the requirement in section 4 to
+        "keep intact all notices".
+    
+     c) You must license the entire work, as a whole, under this
+        License to anyone who comes into possession of a copy.  This
+        License will therefore apply, along with any applicable section 7
+        additional terms, to the whole of the work, and all its parts,
+        regardless of how they are packaged.  This License gives no
+        permission to license the work in any other way, but it does not
+        invalidate such permission if you have separately received it.
+    
+     d) If the work has interactive user interfaces, each must display
+        Appropriate Legal Notices; however, if the Program has interactive
+        interfaces that do not display Appropriate Legal Notices, your
+        work need not make them do so.
+    
+    A compilation of a covered work with other separate and independent
+    works, which are not by their nature extensions of the covered work,
+    and which are not combined with it such as to form a larger program,
+    in or on a volume of a storage or distribution medium, is called an
+    "aggregate" if the compilation and its resulting copyright are not
+    used to limit the access or legal rights of the compilation's users
+    beyond what the individual works permit.  Inclusion of a covered work
+    in an aggregate does not cause this License to apply to the other
+    parts of the aggregate.
+    
+6.  Conveying Non-Source Forms.
+    
+    You may convey a covered work in object code form under the terms
+    of sections 4 and 5, provided that you also convey the
+    machine-readable Corresponding Source under the terms of this License,
+    in one of these ways:
+    
+     a) Convey the object code in, or embodied in, a physical product
+        (including a physical distribution medium), accompanied by the
+        Corresponding Source fixed on a durable physical medium
+        customarily used for software interchange.
+    
+     b) Convey the object code in, or embodied in, a physical product
+        (including a physical distribution medium), accompanied by a
+        written offer, valid for at least three years and valid for as
+        long as you offer spare parts or customer support for that product
+        model, to give anyone who possesses the object code either (1) a
+        copy of the Corresponding Source for all the software in the
+        product that is covered by this License, on a durable physical
+        medium customarily used for software interchange, for a price no
+        more than your reasonable cost of physically performing this
+        conveying of source, or (2) access to copy the
+        Corresponding Source from a network server at no charge.
+    
+     c) Convey individual copies of the object code with a copy of the
+        written offer to provide the Corresponding Source.  This
+        alternative is allowed only occasionally and noncommercially, and
+        only if you received the object code with such an offer, in accord
+        with subsection 6b.
+    
+     d) Convey the object code by offering access from a designated
+        place (gratis or for a charge), and offer equivalent access to the
+        Corresponding Source in the same way through the same place at no
+        further charge.  You need not require recipients to copy the
+        Corresponding Source along with the object code.  If the place to
+        copy the object code is a network server, the Corresponding Source
+        may be on a different server (operated by you or a third party)
+        that supports equivalent copying facilities, provided you maintain
+        clear directions next to the object code saying where to find the
+        Corresponding Source.  Regardless of what server hosts the
+        Corresponding Source, you remain obligated to ensure that it is
+        available for as long as needed to satisfy these requirements.
+    
+     e) Convey the object code using peer-to-peer transmission, provided
+        you inform other peers where the object code and Corresponding
+        Source of the work are being offered to the general public at no
+        charge under subsection 6d.
+    
+    A separable portion of the object code, whose source code is excluded
+    from the Corresponding Source as a System Library, need not be
+    included in conveying the object code work.
+    
+    A "User Product" is either (1) a "consumer product", which means any
+    tangible personal property which is normally used for personal, family,
+    or household purposes, or (2) anything designed or sold for incorporation
+    into a dwelling.  In determining whether a product is a consumer product,
+    doubtful cases shall be resolved in favor of coverage.  For a particular
+    product received by a particular user, "normally used" refers to a
+    typical or common use of that class of product, regardless of the status
+    of the particular user or of the way in which the particular user
+    actually uses, or expects or is expected to use, the product.  A product
+    is a consumer product regardless of whether the product has substantial
+    commercial, industrial or non-consumer uses, unless such uses represent
+    the only significant mode of use of the product.
+    
+    "Installation Information" for a User Product means any methods,
+    procedures, authorization keys, or other information required to install
+    and execute modified versions of a covered work in that User Product from
+    a modified version of its Corresponding Source.  The information must
+    suffice to ensure that the continued functioning of the modified object
+    code is in no case prevented or interfered with solely because
+    modification has been made.
+    
+    If you convey an object code work under this section in, or with, or
+    specifically for use in, a User Product, and the conveying occurs as
+    part of a transaction in which the right of possession and use of the
+    User Product is transferred to the recipient in perpetuity or for a
+    fixed term (regardless of how the transaction is characterized), the
+    Corresponding Source conveyed under this section must be accompanied
+    by the Installation Information.  But this requirement does not apply
+    if neither you nor any third party retains the ability to install
+    modified object code on the User Product (for example, the work has
+    been installed in ROM).
+    
+    The requirement to provide Installation Information does not include a
+    requirement to continue to provide support service, warranty, or updates
+    for a work that has been modified or installed by the recipient, or for
+    the User Product in which it has been modified or installed.  Access to a
+    network may be denied when the modification itself materially and
+    adversely affects the operation of the network or violates the rules and
+    protocols for communication across the network.
+    
+    Corresponding Source conveyed, and Installation Information provided,
+    in accord with this section must be in a format that is publicly
+    documented (and with an implementation available to the public in
+    source code form), and must require no special password or key for
+    unpacking, reading or copying.
+    
+7.  Additional Terms.
+    
+    "Additional permissions" are terms that supplement the terms of this
+    License by making exceptions from one or more of its conditions.
+    Additional permissions that are applicable to the entire Program shall
+    be treated as though they were included in this License, to the extent
+    that they are valid under applicable law.  If additional permissions
+    apply only to part of the Program, that part may be used separately
+    under those permissions, but the entire Program remains governed by
+    this License without regard to the additional permissions.
+    
+    When you convey a copy of a covered work, you may at your option
+    remove any additional permissions from that copy, or from any part of
+    it.  (Additional permissions may be written to require their own
+    removal in certain cases when you modify the work.)  You may place
+    additional permissions on material, added by you to a covered work,
+    for which you have or can give appropriate copyright permission.
+    
+    Notwithstanding any other provision of this License, for material you
+    add to a covered work, you may (if authorized by the copyright holders of
+    that material) supplement the terms of this License with terms:
+    
+     a) Disclaiming warranty or limiting liability differently from the
+        terms of sections 15 and 16 of this License; or
+    
+     b) Requiring preservation of specified reasonable legal notices or
+        author attributions in that material or in the Appropriate Legal
+        Notices displayed by works containing it; or
+    
+     c) Prohibiting misrepresentation of the origin of that material, or
+        requiring that modified versions of such material be marked in
+        reasonable ways as different from the original version; or
+    
+     d) Limiting the use for publicity purposes of names of licensors or
+        authors of the material; or
+    
+     e) Declining to grant rights under trademark law for use of some
+        trade names, trademarks, or service marks; or
+    
+     f) Requiring indemnification of licensors and authors of that
+        material by anyone who conveys the material (or modified versions of
+        it) with contractual assumptions of liability to the recipient, for
+        any liability that these contractual assumptions directly impose on
+        those licensors and authors.
+    
+    All other non-permissive additional terms are considered "further
+    restrictions" within the meaning of section 10.  If the Program as you
+    received it, or any part of it, contains a notice stating that it is
+    governed by this License along with a term that is a further
+    restriction, you may remove that term.  If a license document contains
+    a further restriction but permits relicensing or conveying under this
+    License, you may add to a covered work material governed by the terms
+    of that license document, provided that the further restriction does
+    not survive such relicensing or conveying.
+    
+    If you add terms to a covered work in accord with this section, you
+    must place, in the relevant source files, a statement of the
+    additional terms that apply to those files, or a notice indicating
+    where to find the applicable terms.
+    
+    Additional terms, permissive or non-permissive, may be stated in the
+    form of a separately written license, or stated as exceptions;
+    the above requirements apply either way.
+    
+8.  Termination.
+    
+    You may not propagate or modify a covered work except as expressly
+    provided under this License.  Any attempt otherwise to propagate or
+    modify it is void, and will automatically terminate your rights under
+    this License (including any patent licenses granted under the third
+    paragraph of section 11).
+    
+    However, if you cease all violation of this License, then your
+    license from a particular copyright holder is reinstated (a)
+    provisionally, unless and until the copyright holder explicitly and
+    finally terminates your license, and (b) permanently, if the copyright
+    holder fails to notify you of the violation by some reasonable means
+    prior to 60 days after the cessation.
+    
+    Moreover, your license from a particular copyright holder is
+    reinstated permanently if the copyright holder notifies you of the
+    violation by some reasonable means, this is the first time you have
+    received notice of violation of this License (for any work) from that
+    copyright holder, and you cure the violation prior to 30 days after
+    your receipt of the notice.
+    
+    Termination of your rights under this section does not terminate the
+    licenses of parties who have received copies or rights from you under
+    this License.  If your rights have been terminated and not permanently
+    reinstated, you do not qualify to receive new licenses for the same
+    material under section 10.
+    
+9.  Acceptance Not Required for Having Copies.
+    
+    You are not required to accept this License in order to receive or
+    run a copy of the Program.  Ancillary propagation of a covered work
+    occurring solely as a consequence of using peer-to-peer transmission
+    to receive a copy likewise does not require acceptance.  However,
+    nothing other than this License grants you permission to propagate or
+    modify any covered work.  These actions infringe copyright if you do
+    not accept this License.  Therefore, by modifying or propagating a
+    covered work, you indicate your acceptance of this License to do so.
+    
+10. Automatic Licensing of Downstream Recipients.
+    
+    Each time you convey a covered work, the recipient automatically
+    receives a license from the original licensors, to run, modify and
+    propagate that work, subject to this License.  You are not responsible
+    for enforcing compliance by third parties with this License.
+    
+    An "entity transaction" is a transaction transferring control of an
+    organization, or substantially all assets of one, or subdividing an
+    organization, or merging organizations.  If propagation of a covered
+    work results from an entity transaction, each party to that
+    transaction who receives a copy of the work also receives whatever
+    licenses to the work the party's predecessor in interest had or could
+    give under the previous paragraph, plus a right to possession of the
+    Corresponding Source of the work from the predecessor in interest, if
+    the predecessor has it or can get it with reasonable efforts.
+    
+    You may not impose any further restrictions on the exercise of the
+    rights granted or affirmed under this License.  For example, you may
+    not impose a license fee, royalty, or other charge for exercise of
+    rights granted under this License, and you may not initiate litigation
+    (including a cross-claim or counterclaim in a lawsuit) alleging that
+    any patent claim is infringed by making, using, selling, offering for
+    sale, or importing the Program or any portion of it.
+    
+11. Patents.
+    
+    A "contributor" is a copyright holder who authorizes use under this
+    License of the Program or a work on which the Program is based.  The
+    work thus licensed is called the contributor's "contributor version".
+    
+    A contributor's "essential patent claims" are all patent claims
+    owned or controlled by the contributor, whether already acquired or
+    hereafter acquired, that would be infringed by some manner, permitted
+    by this License, of making, using, or selling its contributor version,
+    but do not include claims that would be infringed only as a
+    consequence of further modification of the contributor version.  For
+    purposes of this definition, "control" includes the right to grant
+    patent sublicenses in a manner consistent with the requirements of
+    this License.
+    
+    Each contributor grants you a non-exclusive, worldwide, royalty-free
+    patent license under the contributor's essential patent claims, to
+    make, use, sell, offer for sale, import and otherwise run, modify and
+    propagate the contents of its contributor version.
+    
+    In the following three paragraphs, a "patent license" is any express
+    agreement or commitment, however denominated, not to enforce a patent
+    (such as an express permission to practice a patent or covenant not to
+    sue for patent infringement).  To "grant" such a patent license to a
+    party means to make such an agreement or commitment not to enforce a
+    patent against the party.
+    
+    If you convey a covered work, knowingly relying on a patent license,
+    and the Corresponding Source of the work is not available for anyone
+    to copy, free of charge and under the terms of this License, through a
+    publicly available network server or other readily accessible means,
+    then you must either (1) cause the Corresponding Source to be so
+    available, or (2) arrange to deprive yourself of the benefit of the
+    patent license for this particular work, or (3) arrange, in a manner
+    consistent with the requirements of this License, to extend the patent
+    license to downstream recipients.  "Knowingly relying" means you have
+    actual knowledge that, but for the patent license, your conveying the
+    covered work in a country, or your recipient's use of the covered work
+    in a country, would infringe one or more identifiable patents in that
+    country that you have reason to believe are valid.
+    
+    If, pursuant to or in connection with a single transaction or
+    arrangement, you convey, or propagate by procuring conveyance of, a
+    covered work, and grant a patent license to some of the parties
+    receiving the covered work authorizing them to use, propagate, modify
+    or convey a specific copy of the covered work, then the patent license
+    you grant is automatically extended to all recipients of the covered
+    work and works based on it.
+    
+    A patent license is "discriminatory" if it does not include within
+    the scope of its coverage, prohibits the exercise of, or is
+    conditioned on the non-exercise of one or more of the rights that are
+    specifically granted under this License.  You may not convey a covered
+    work if you are a party to an arrangement with a third party that is
+    in the business of distributing software, under which you make payment
+    to the third party based on the extent of your activity of conveying
+    the work, and under which the third party grants, to any of the
+    parties who would receive the covered work from you, a discriminatory
+    patent license (a) in connection with copies of the covered work
+    conveyed by you (or copies made from those copies), or (b) primarily
+    for and in connection with specific products or compilations that
+    contain the covered work, unless you entered into that arrangement,
+    or that patent license was granted, prior to 28 March 2007.
+    
+    Nothing in this License shall be construed as excluding or limiting
+    any implied license or other defenses to infringement that may
+    otherwise be available to you under applicable patent law.
+    
+12. No Surrender of Others' Freedom.
+    
+    If conditions are imposed on you (whether by court order, agreement or
+    otherwise) that contradict the conditions of this License, they do not
+    excuse you from the conditions of this License.  If you cannot convey a
+    covered work so as to satisfy simultaneously your obligations under this
+    License and any other pertinent obligations, then as a consequence you may
+    not convey it at all.  For example, if you agree to terms that obligate you
+    to collect a royalty for further conveying from those to whom you convey
+    the Program, the only way you could satisfy both those terms and this
+    License would be to refrain entirely from conveying the Program.
+    
+13. Use with the GNU Affero General Public License.
+    
+    Notwithstanding any other provision of this License, you have
+    permission to link or combine any covered work with a work licensed
+    under version 3 of the GNU Affero General Public License into a single
+    combined work, and to convey the resulting work.  The terms of this
+    License will continue to apply to the part which is the covered work,
+    but the special requirements of the GNU Affero General Public License,
+    section 13, concerning interaction through a network will apply to the
+    combination as such.
+    
+14. Revised Versions of this License.
+    
+    The Free Software Foundation may publish revised and/or new versions of
+    the GNU General Public License from time to time.  Such new versions will
+    be similar in spirit to the present version, but may differ in detail to
+    address new problems or concerns.
+    
+    Each version is given a distinguishing version number.  If the
+    Program specifies that a certain numbered version of the GNU General
+    Public License "or any later version" applies to it, you have the
+    option of following the terms and conditions either of that numbered
+    version or of any later version published by the Free Software
+    Foundation.  If the Program does not specify a version number of the
+    GNU General Public License, you may choose any version ever published
+    by the Free Software Foundation.
+    
+    If the Program specifies that a proxy can decide which future
+    versions of the GNU General Public License can be used, that proxy's
+    public statement of acceptance of a version permanently authorizes you
+    to choose that version for the Program.
+    
+    Later license versions may give you additional or different
+    permissions.  However, no additional obligations are imposed on any
+    author or copyright holder as a result of your choosing to follow a
+    later version.
+    
+15. Disclaimer of Warranty.
+    
+    THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+    APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+    HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+    OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+    THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+    PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+    IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+    ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+    
+16. Limitation of Liability.
+    
+    IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+    WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+    THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+    GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+    USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+    DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+    PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+    EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+    SUCH DAMAGES.
+    
+17. Interpretation of Sections 15 and 16.
+    
+    If the disclaimer of warranty and limitation of liability provided
+    above cannot be given local legal effect according to their terms,
+    reviewing courts shall apply local law that most closely approximates
+    an absolute waiver of all civil liability in connection with the
+    Program, unless a warranty or assumption of liability accompanies a
+    copy of the Program in return for a fee.
+
+END OF TERMS AND CONDITIONS
+
+How to Apply These Terms to Your New Programs
+.............................................
+
+If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+::
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    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/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode::
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands ``show w`` and ``show c`` should show the
+appropriate parts of the General Public License.  Of course, your
+program's commands might be different; for a GUI interface, you would
+use an "about box".
+
+You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+
+
+
+.. role:: raw-html(raw)
+  :format: html
+.. role:: raw-latex(raw)
+  :format: latex
+.. |--|   unicode:: U+02013 .. en dash
+  :trim:
+.. |---|  unicode:: U+02014 .. em dash
+.. |LaTeX| replace:: :raw-html:`LaTeX` :raw-latex:`\LaTeX{}`
+
+.. vim: ft=rest
+.. vim700: spell spelllang=en
Index: trunk/LICENSE
===================================================================
--- trunk/LICENSE	(revision 12)
+++ 	(revision )
@@ -1,675 +1,0 @@
-                      GNU GENERAL PUBLIC LICENSE
-                       Version 3, 29 June 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc. http://fsf.org
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-                            Preamble
-
-  The GNU General Public License is a free, copyleft license for
-software and other kinds of works.
-
-  The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works.  By contrast,
-the GNU General Public License is intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users.  We, the Free Software Foundation, use the
-GNU General Public License for most of our software; it applies also to
-any other work released this way by its authors.  You can apply it to
-your programs, too.
-
-  When we speak of free software, we are referring to freedom, not
-price.  Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
-
-  To protect your rights, we need to prevent others from denying you
-these rights or asking you to surrender the rights.  Therefore, you have
-certain responsibilities if you distribute copies of the software, or if
-you modify it: responsibilities to respect the freedom of others.
-
-  For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must pass on to the recipients the same
-freedoms that you received.  You must make sure that they, too, receive
-or can get the source code.  And you must show them these terms so they
-know their rights.
-
-  Developers that use the GNU GPL protect your rights with two steps:
-(1) assert copyright on the software, and (2) offer you this License
-giving you legal permission to copy, distribute and/or modify it.
-
-  For the developers' and authors' protection, the GPL clearly explains
-that there is no warranty for this free software.  For both users' and
-authors' sake, the GPL requires that modified versions be marked as
-changed, so that their problems will not be attributed erroneously to
-authors of previous versions.
-
-  Some devices are designed to deny users access to install or run
-modified versions of the software inside them, although the manufacturer
-can do so.  This is fundamentally incompatible with the aim of
-protecting users' freedom to change the software.  The systematic
-pattern of such abuse occurs in the area of products for individuals to
-use, which is precisely where it is most unacceptable.  Therefore, we
-have designed this version of the GPL to prohibit the practice for those
-products.  If such problems arise substantially in other domains, we
-stand ready to extend this provision to those domains in future versions
-of the GPL, as needed to protect the freedom of users.
-
-  Finally, every program is threatened constantly by software patents.
-States should not allow patents to restrict development and use of
-software on general-purpose computers, but in those that do, we wish to
-avoid the special danger that patents applied to a free program could
-make it effectively proprietary.  To prevent this, the GPL assures that
-patents cannot be used to render the program non-free.
-
-  The precise terms and conditions for copying, distribution and
-modification follow.
-
-                       TERMS AND CONDITIONS
-
-  0. Definitions.
-
-  "This License" refers to version 3 of the GNU General Public License.
-
-  "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
-
-  "The Program" refers to any copyrightable work licensed under this
-License.  Each licensee is addressed as "you".  "Licensees" and
-"recipients" may be individuals or organizations.
-
-  To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy.  The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
-  A "covered work" means either the unmodified Program or a work based
-on the Program.
-
-  To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy.  Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
-  To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies.  Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
-  An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License.  If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
-  1. Source Code.
-
-  The "source code" for a work means the preferred form of the work
-for making modifications to it.  "Object code" means any non-source
-form of a work.
-
-  A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
-  The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form.  A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
-  The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities.  However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work.  For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
-  The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
-  The Corresponding Source for a work in source code form is that
-same work.
-
-  2. Basic Permissions.
-
-  All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met.  This License explicitly affirms your unlimited
-permission to run the unmodified Program.  The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work.  This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
-  You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force.  You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright.  Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
-  Conveying under any other circumstances is permitted solely under
-the conditions stated below.  Sublicensing is not allowed; section 10
-makes it unnecessary.
-
-  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
-  No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
-  When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
-  4. Conveying Verbatim Copies.
-
-  You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
-  You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
-  5. Conveying Modified Source Versions.
-
-  You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
-    a) The work must carry prominent notices stating that you modified
-    it, and giving a relevant date.
-
-    b) The work must carry prominent notices stating that it is
-    released under this License and any conditions added under section
-    7.  This requirement modifies the requirement in section 4 to
-    "keep intact all notices".
-
-    c) You must license the entire work, as a whole, under this
-    License to anyone who comes into possession of a copy.  This
-    License will therefore apply, along with any applicable section 7
-    additional terms, to the whole of the work, and all its parts,
-    regardless of how they are packaged.  This License gives no
-    permission to license the work in any other way, but it does not
-    invalidate such permission if you have separately received it.
-
-    
-	d) If the work has interactive user interfaces, each must display
-    Appropriate Legal Notices; however, if the Program has interactive
-    interfaces that do not display Appropriate Legal Notices, your
-    work need not make them do so.
-
-  A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit.  Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
-  6. Conveying Non-Source Forms.
-
-  You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
-    a) Convey the object code in, or embodied in, a physical product
-    (including a physical distribution medium), accompanied by the
-    Corresponding Source fixed on a durable physical medium
-    customarily used for software interchange.
-
-    b) Convey the object code in, or embodied in, a physical product
-    (including a physical distribution medium), accompanied by a
-    written offer, valid for at least three years and valid for as
-    long as you offer spare parts or customer support for that product
-    model, to give anyone who possesses the object code either (1) a
-    copy of the Corresponding Source for all the software in the
-    product that is covered by this License, on a durable physical
-    medium customarily used for software interchange, for a price no
-    more than your reasonable cost of physically performing this
-    conveying of source, or (2) access to copy the
-    Corresponding Source from a network server at no charge.
-
-    c) Convey individual copies of the object code with a copy of the
-    written offer to provide the Corresponding Source.  This
-    alternative is allowed only occasionally and noncommercially, and
-    only if you received the object code with such an offer, in accord
-    with subsection 6b.
-
-    d) Convey the object code by offering access from a designated
-    place (gratis or for a charge), and offer equivalent access to the
-    Corresponding Source in the same way through the same place at no
-    further charge.  You need not require recipients to copy the
-    Corresponding Source along with the object code.  If the place to
-    copy the object code is a network server, the Corresponding Source
-    may be on a different server (operated by you or a third party)
-    that supports equivalent copying facilities, provided you maintain
-    clear directions next to the object code saying where to find the
-    Corresponding Source.  Regardless of what server hosts the
-    Corresponding Source, you remain obligated to ensure that it is
-    available for as long as needed to satisfy these requirements.
-
-    e) Convey the object code using peer-to-peer transmission, provided
-    you inform other peers where the object code and Corresponding
-    Source of the work are being offered to the general public at no
-    charge under subsection 6d.
-
-  A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
-  A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling.  In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage.  For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product.  A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
-  "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source.  The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
-  If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information.  But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
-  The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed.  Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
-  Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
-  7. Additional Terms.
-
-  "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law.  If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
-  When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it.  (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.)  You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
-  Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
-    a) Disclaiming warranty or limiting liability differently from the
-    terms of sections 15 and 16 of this License; or
-
-    b) Requiring preservation of specified reasonable legal notices or
-    author attributions in that material or in the Appropriate Legal
-    Notices displayed by works containing it; or
-
-    c) Prohibiting misrepresentation of the origin of that material, or
-    requiring that modified versions of such material be marked in
-    reasonable ways as different from the original version; or
-
-    d) Limiting the use for publicity purposes of names of licensors or
-    authors of the material; or
-
-    e) Declining to grant rights under trademark law for use of some
-    trade names, trademarks, or service marks; or
-
-    f) Requiring indemnification of licensors and authors of that
-    material by anyone who conveys the material (or modified versions of
-    it) with contractual assumptions of liability to the recipient, for
-    any liability that these contractual assumptions directly impose on
-    those licensors and authors.
-
-  All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10.  If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term.  If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
-  If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
-  Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
-  8. Termination.
-
-  You may not propagate or modify a covered work except as expressly
-provided under this License.  Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
-  However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
-  Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
-  Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License.  If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
-  9. Acceptance Not Required for Having Copies.
-
-  You are not required to accept this License in order to receive or
-run a copy of the Program.  Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance.  However,
-nothing other than this License grants you permission to propagate or
-modify any covered work.  These actions infringe copyright if you do
-not accept this License.  Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
-  10. Automatic Licensing of Downstream Recipients.
-
-  Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License.  You are not responsible
-for enforcing compliance by third parties with this License.
-
-  An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations.  If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
-  You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License.  For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
-  11. Patents.
-
-  A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based.  The
-work thus licensed is called the contributor's "contributor version".
-
-  A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version.  For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
-this License.
-
-  Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
-  In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement).  To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
-  If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients.  "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-
-  If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
-  A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License.  You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
-  Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
-  12. No Surrender of Others' Freedom.
-
-  If conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License.  If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all.  For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
-  13. Use with the GNU Affero General Public License.
-
-  Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU Affero General Public License into a single
-combined work, and to convey the resulting work.  The terms of this
-License will continue to apply to the part which is the covered work,
-but the special requirements of the GNU Affero General Public License,
-section 13, concerning interaction through a network will apply to the
-combination as such.
-
-  14. Revised Versions of this License.
-
-  The Free Software Foundation may publish revised and/or new versions of
-the GNU General Public License from time to time.  Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-  Each version is given a distinguishing version number.  If the
-Program specifies that a certain numbered version of the GNU General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation.  If the Program does not specify a version number of the
-GNU General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
-  If the Program specifies that a proxy can decide which future
-versions of the GNU General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
-  Later license versions may give you additional or different
-permissions.  However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
-  15. Disclaimer of Warranty.
-
-  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
-  16. Limitation of Liability.
-
-  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
-  17. Interpretation of Sections 15 and 16.
-
-  If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
-
-                     END OF TERMS AND CONDITIONS
-
-            How to Apply These Terms to Your New Programs
-
-  If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
-  To do so, attach the following notices to the program.  It is safest
-to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-    <one line to give the program's name and a brief idea of what it does.>
-    Copyright (C) <year>  <name of author>
-
-    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/>.
-
-Also add information on how to contact you by electronic and paper mail.
-
-  If the program does terminal interaction, make it output a short
-notice like this when it starts in an interactive mode:
-
-    <program>  Copyright (C) <year>  <name of author>
-    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
-    This is free software, and you are welcome to redistribute it
-    under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License.  Of course, your program's commands
-might be different; for a GUI interface, you would use an "about box".
-
-  You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU GPL, see
-<http://www.gnu.org/licenses/>.
-
-  The GNU General Public License does not permit incorporating your program
-into proprietary programs.  If your program is a subroutine library, you
-may consider it more useful to permit linking proprietary applications with
-the library.  If this is what you want to do, use the GNU Lesser General
-Public License instead of this License.  But first, please read
-<http://www.gnu.org/philosophy/why-not-lgpl.html>.
