~tedks/+junk/spacer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
open Parser
open Lexing
open Ast

let parse_file name =
  let chan = open_in name in
  let lexbuf = Lexing.from_channel chan in
  let p = Parser.file Lexer.file lexbuf in
  close_in chan;
  p

let print_lines c = match c with 
  | Clozestr(s) -> print_endline ("Cloze of "^s)
  | Definstr(f) -> print_endline ("Defin of "^f)
  | Liststr(n) -> print_endline ("List of "^n)

let print_card c = match c with 
  | Cloze(s) -> print_endline ("Cloze of "^s)
  | Defin(f, b) -> print_endline ("Defin of "^f^" :: "^b)
  | List(name, entries) -> 
    print_endline ("List of "^name);
    List.iter (fun (i, s) -> print_endline ((string_of_int i)^". "^s))
      entries

let parse_card c  = match c with
  | Clozestr(s) -> Cloze(s)
  | Definstr(f) -> Parser.defin Lexer.defin (Lexing.from_string f)
  | Liststr(l) -> Parser.list Lexer.list (Lexing.from_string l)

let rec add_card deck c = 
  let spaceadd (f:string) (b:string option) :unit = 
    let front_arg = ("-f \""^f^"\"") in
    let back_arg = match b with 
      | None -> ""
      | Some b -> ("-b \""^b^"\"")
    in 
    ignore (Unix.system ("./spaceadd "^front_arg^" "^back_arg^" -d "^deck))
  in 
  let strengthen s = 
    ("<strong>"^(ExtString.String.strip s)^"</strong>") 
  in
  match c with
    | Cloze(s) -> spaceadd s (None)
    | Defin(f, b) -> 
      let front = strengthen f in
      spaceadd front (Some b);
      spaceadd b (Some front);
    | List(name, l) -> 
      let flattened_list = 
	(List.map (fun (i,s) -> (string_of_int i)^". "^s) l)
      in 
      let clozes = 
	let rec gen_clozes acc c lines = 
	    let header = ((strengthen name)^"\n\n") in
	    let plist = (String.concat "\n" acc)^"\n" in
	    let (i, s) = c in 
	    let flatll = ((string_of_int i)^". "^s) in
	    let lastline = ((string_of_int i) ^". ["^s^"]") in
	    Cloze(header^plist^lastline) :: 
	      if lines = [] then [] else
		(gen_clozes (acc@[flatll]) (List.hd lines) (List.tl lines))
	in 
	gen_clozes [] (List.hd l) (List.tl l)
      in
      let textlist = String.concat "\n" flattened_list in 
      let newcards = (Defin(name, textlist) :: clozes) in
      List.iter (add_card deck) newcards

let main () = 
  let file = parse_file Sys.argv.(1) in
  let deck = Sys.argv.(2) in
  let file = List.map (ExtString.String.strip ~chars:" \t\n") file in
  let linestrings = List.map 
    (fun s -> Parser.line Lexer.line (Lexing.from_string s)) file
  in 
  let cards = List.map parse_card linestrings in
  List.iter (add_card deck) cards
;;

main ()