(*
 * Copyright (c) 2001-2002 Stefan Kral
 *
 * 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 2 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *)

let unitM a state succ_cont fail_cont = succ_cont a state fail_cont
let failM _state _succ_cont fail_cont = fail_cont ()

let catch1M exn handler state succ_cont fail_cont = 
  try 
    succ_cont () state fail_cont 
  with exn -> 
    handler () state succ_cont fail_cont

let fetchStateM state succ_cont fail_cont = succ_cont state state fail_cont
let storeStateM state _ succ_cont fail_cont = succ_cont () state fail_cont

let (>>=) = fun f1 f2 -> fun state succ_cont fail_cont ->
  f1 state (fun a st' fail_cont' -> f2 a st' succ_cont fail_cont') fail_cont

let (|||) = fun f1 f2 -> fun state succ_cont fail_cont ->
  f1 () state succ_cont (fun _ -> f2 () state succ_cont fail_cont)

let posAssertM = function true  -> unitM () | false -> failM
let negAssertM = function false -> unitM () | true  -> failM

let ifThenElseM fCond fThen fElse =
  let cut_else_branch = ref false in
  (   (fun _ ->
	 fCond () >>= fun a ->
	   cut_else_branch := true;
	     fThen a)
  ||| (fun _ ->
	 if !cut_else_branch then
	   failM
	 else
	   fElse ())
  )

let notM fM a state succ_cont fail_cont =
  fM a state (fun _ _ _ -> fail_cont ()) (fun _ -> succ_cont a state fail_cont)

let onceM fM a state succ_cont fail_cont =
  fM a state (fun a state' _ -> succ_cont a state' fail_cont) fail_cont

let findallM fM a = 			(* output is in reversed order *)
  let sols = ref [] in
    (   (fun _ -> fM a >>= fun a' -> sols := a'::!sols; failM)
    ||| (fun _ -> unitM !sols)
    )

let runM fM a initial_state =
  fM a initial_state (fun a state _ -> Some(a,state)) (fun _ -> None)

let runP fM a initial_state = 
  fM a initial_state (fun _ _ _ -> true) (fun _ -> false)
