File: plain.pm

package info (click to toggle)
auto-multiple-choice 1.5.0~rc2-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 56,204 kB
  • sloc: perl: 27,850; xml: 23,201; cpp: 1,810; python: 700; makefile: 496; sh: 217; ansic: 195
file content (1503 lines) | stat: -rw-r--r-- 47,624 bytes parent folder | download
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
#
# Copyright (C) 2012-2021 Alexis Bienvenüe <paamc@passoire.fr>
#
# This file is part of Auto-Multiple-Choice
#
# Auto-Multiple-Choice 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.
#
# Auto-Multiple-Choice 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 Auto-Multiple-Choice.  If not, see
# <http://www.gnu.org/licenses/>.

use warnings;
use 5.012;

package AMC::Filter::plain;

use AMC::Filter;
use AMC::Basic;

use File::Spec;
use Data::Dumper;

use utf8;

our @ISA = ("AMC::Filter");

use_gettext;

sub new {
    my $class = shift;
    my $self  = $class->SUPER::new();

    # list of available global options:

    $self->{options_names} = [
        qw/Title Presentation Code Lang Font
          BoxColor PaperSize
          AnswerSheetTitle AnswerSheetPresentation
          AnswerSheetColumns
          CompleteMulti SeparateAnswerSheet AutoMarks
          DefaultScoringM DefaultScoringS
          L-Question L-None L-Name L-Student
          LaTeX LaTeX-Preambule LaTeX-BeginDocument
          LaTeX-BeginCopy LaTeX-EndCopy
          PDF-BeginCopy PDF-EndCopy
          LaTeXEngine xltxtra
          ShuffleQuestions Columns QuestionBlocks
          Arabic ArabicFont
          Disable
          ManualDuplex SingleSided
          L-OpenText L-OpenReserved
          CodeDigitsDirection
          PackageOptions
          NameFieldWidth NameFieldLines NameFieldLinespace
          TitleWidth
          Pages
          RandomSeed
          PreAssociation PreAssociationKey PreAssociationName
          /
    ];

    # from these options, which ones are boolean valued?

    $self->{options_boolean} = [
        qw/LaTeX xltxtra
          ShuffleQuestions QuestionBlocks
          CompleteMulti SeparateAnswerSheet AutoMarks
          Arabic
          ManualDuplex SingleSided
          /
    ];

    # current groups list
    $self->{groups} = [];

    # global LaTeX definitions
    $self->{latex_defs} = [];

    # packages needed
    $self->{packages} = {};

    # maximum of digits that a hrizontal code can handle
    $self->{maxhorizcode} = 6;

    # options values
    $self->{options} = {};

    # default values for options:

    $self->{default_options} = {
        latexengine             => 'xelatex',
        xltxtra                 => 1,
        questionblocks          => 1,
        shufflequestions        => 1,
        completemulti           => 1,
        font                    => 'Linux Libertine O',
        arabic                  => '',
        arabicfont              => 'Rasheeq',
        implicitdefaultscoringm => 'haut=2',
        'l-name'                => '',
        'l-student'             => __(
"Please code your student number opposite, and write your name in the box below."
        ),
        disable               => '',
        manualduplex          => '',
        singlesided           => '',
        columns               => 1,
        codedigitsdirection   => '',
        namefieldwidth        => '',
        namefieldlines        => '',
        namefieldlinespace    => '.5em',
        titlewidth            => ".47\\linewidth",
        randomseed            => "1527384",
        lang                  => '',
        code                  => 0,
        'latex-preambule'     => '',
        'latex-begindocument' => '',
        'latex-begincopy'     => '',
        'latex-endcopy'       => '',
        'pdf-begincopy'       => '',
        'pdf-endcopy'         => '',
        preassociation        => '',
        preassociationkey     => 'id',
        preassociationname    => "\\name{} \\surname{}",
        answersheetcolumns    => 1,
    };

    # List of modules to be used when parsing (see parse_*
    # corresponding methods for implementation). Modules in the
    # Disable global option won't be used.

    $self->{parse_modules} =
      [ 'verbatim', 'local_latex', 'images', 'embf', 'title', 'text' ];

    # current question number among questions for which no ID is given
    # in the source
    $self->{qid} = 0;

    bless( $self, $class );
    return $self;
}

# arabic default localisation texts
my %l_arabic = (
    'l-question' => 'السؤال',
    'l-none'     => 'لا توجد اجابة صحيحة',
);

# arabic alphabet to replace letters ABCDEF... in the boxes
my @alphabet_arabic = (
    'أ', 'ب', 'ج', 'د', 'ه', 'و', 'ز', 'ح', 'ط', 'ي',
    'ك', 'ل', 'م', 'ن', 'س', 'ع', 'ف', 'ص', 'ق', 'ر',
    'ش', 'ت', 'ث', 'خ', 'ذ', 'ض', 'ظ', 'غ',
);

sub is_multicol {
    my ($o) = @_;
    return ( defined( $o->{columns} ) && $o->{columns} > 1 );
}

# add a global LaTeX definition
sub add_global_latex_def {
    my ( $self, $tex ) = @_;
    push @{ $self->{latex_defs} }, $tex;
}

# require a specific LaTeX package, with options in the form
# needs_package("geometry",margins=>'1cm',noheadfoot=>'')
sub needs_package {
    my ( $self, $package, %options ) = @_;
    $self->{packages}->{$package} = {}
      if ( !defined( $self->{packages}->{$package} ) );
    for my $o ( keys %options ) {
        $self->{packages}->{$package}->{$o} = $options{$o};
    }
}

# parse boolean options to get 0 (from empty value, "NO" or " FALSE")
# or 1 (from other values).
sub parse_bool {
    my ($b) = @_;
    return (undef) if ( !defined($b) );
    if ( $b =~ /^\s*(no|false|0)\s*$/i ) {
        return (0);
    } else {
        return ($b);
    }
}

sub first_defined {
    for (@_) { return ($_) if ( defined($_) ); }
}

# transforms the list of current options values to make it coherent
sub parse_options {
    my ($self) = @_;

    # boolean options are parsed to get 0 or 1
    for my $n ( @{ $self->{options_boolean} } ) {
        $self->{options}->{ lc($n) } =
          parse_bool( $self->{options}->{ lc($n) } );
    }

    if ( $self->{options}->{lang} ) {

        # if AR language is selected, apply default arabic localisation
        # options and set 'arabic' option to 1
        if ( $self->{options}->{lang} eq 'AR' ) {
            for ( keys %l_arabic ) {
                $self->{options}->{$_} = $l_arabic{$_}
                  if ( !$self->{options}->{$_} );
            }
            $self->{options}->{arabic} = 1;
        }

        # if JA language is selected, switch to 'platex+dvipdf' LaTeX
        # engine, remove default font and don't use xltxtra LaTeX package
        if ( $self->{options}->{lang} eq 'JA' ) {
            $self->{default_options}->{latexengine} = 'platex+dvipdf';
            $self->{default_options}->{font}        = '';
            $self->{default_options}->{xltxtra}     = '';
        }
    }

    # set options values to default if not defined in the source
    for my $k ( keys %{ $self->{default_options} } ) {
        $self->{options}->{$k} = $self->{default_options}->{$k}
          if ( !defined( $self->{options}->{$k} ) );
    }

    # relay LaTeX engine option to the project itself
    $self->set_project_option( 'moteur_latex_b',
        $self->{options}->{latexengine} );

    # PDF-* needs the pdfpages package
    if (   $self->{options}->{'pdf-begincopy'}
        || $self->{options}->{'pdf-endcopy'} )
    {
        $self->needs_package('pdfpages');
    }

    # Pre-association works with package csvsimple
    if ( $self->{options}->{preassociation} ) {
        $self->set_project_option('nombre_copies',0);
        $self->needs_package('csvsimple');
    }

    # split Pages option to pages_question and/or pages_total
    if ( $self->{options}->{pages} ) {
        if (   $self->{options}->{separateanswersheet}
            && $self->{options}->{pages} =~ /^\s*([0-9]*)\s*\+\s*([0-9]*)\s*$/ )
        {
            my $a = $1 || 0;
            my $b = $2 || 0;
            $self->{options}->{pages_question} = $a;
            $self->{options}->{pages_total}    = $a + $b;
        } elsif ( $self->{options}->{pages} =~ /^\s*([0-9]+)\s*$/ ) {
            $self->{options}->{pages_total} = $1;
        } else {

            $self->error(
                sprintf(
# TRANSLATORS: Message when the Pages option used in AMC-TXT can't be
# parsed. %s will be replaced with the option value
                    __ "Pages option value can't be understood: %s",
                    $self->{options}->{pages}
                )
            );
        }
    }
}

# adds an object (hash) to a container (list) and returns the
# corresponding new hashref
sub add_object {
    my ( $container, %object ) = @_;
    push @$container, {%object};
    return ( $container->[$#$container] );
}

# adds a group to current state
sub add_group {
    my ( $self, %g ) = @_;
    add_object( $self->{groups}, %g );
}

# cleanup for text: removes leading and trailing spaces
sub value_cleanup {
    my ( $self, $v ) = @_;
    if ($v) {
        $$v =~ s/^\s+//;
        $$v =~ s/\s+$//;
    }
}

# issue an AMC-TXT (syntax) error to be shown by the GUI
sub parse_error {
    my ( $self, $text ) = @_;
    $self->error(
        "<i>AMC-TXT(" . sprintf( __('Line %d'), $self->{input_line} ) . ")</i> " . $text );
}

# check that a set of answers for a given question is coherent: one
# need more than one answer, and a simple question needs one and only
# one correct answer.
sub check_answers {
    my ( $self, $question ) = @_;
    if ($question) {
        if ( $#{ $question->{answers} } < 1 ) {

            $self->parse_error(
                               __
# TRANSLATORS: Error text for AMC-TXT parsing, when opening a new
# question whereas the previous question has less than two choices
                               "Previous question has less than two choices" );
        } else {
            my $n_correct = 0;
            for my $a ( @{ $question->{answers} } ) {
                $n_correct++ if ( $a->{correct} );
            }
            if ( !( $question->{multiple} || $question->{indicative} ) ) {
                if ( $n_correct != 1 ) {

                    $self->parse_error(
                        sprintf(
                            __(
                    # TRANSLATORS: Error text for AMC-TXT parsing
"Previous question is a simple question but has %d correct choice(s)"
                            ),
                            $n_correct
                        )
                    );
                }
            }
        }
    }
}

sub group_by_id {
    my ( $self, $id, %oo ) = @_;
    my $group = '';

    if ($id) {

      GROUPS: for ( @{ $self->{groups} } ) {
            if ( $_->{id} eq $id ) { $group = $_; last GROUPS; }
        }

    } else {
        $id = 'unnamed' . $self->unused_letter();
    }

    if ( !$group ) {
        $group = $self->add_group( id => $id, questions => [], %oo );

        if ( $id ne '_main_' ) {

            # calls newly created group from the 'main' one

            my $main = $self->group_by_id('_main_');

            add_object(
                $main->{questions},
                textonly => 1,
                text     => {
                    type   => 'latex',
                    string => $self->group_insert_command_name($group)
                },
                %oo,
            );
        }
    }

    return ($group);
}

sub read_options {
    my ( $self, $options_string ) = @_;
    my %oo   = ();
    if ($options_string) {
        my @opts = split( /,+/, $options_string );
        for (@opts) {
            if (/^([^=]+)=(.*)/) {
                $oo{$1} = $2;
            } else {
                $oo{$_} = 1;
            }
        }
    }
    return (%oo);
}

# parse the whole source file to a data tree ($self->{groups})
sub read_source {
    my ( $self, $input_file ) = @_;

    $self->{reader_state} = {
        follow => '',    # variable where to add content comming from
                         # following lines
        group    => $self->group_by_id('_main_'),    # current group
        question => '',                              # current question
    };

    $self->read_file($input_file);
    $self->check_answers( $self->{reader_state}->{question} );
}

sub read_file {
    my ( $self, $input_file ) = @_;

    # regexp that matches an option name:
    my $opt_re = '(' . join( '|', @{ $self->{options_names} } ) . ')';

    debug "Parsing $input_file";

    open( my $infile, "<", $input_file );
    binmode($infile);

    my $line = 0;

  LINE: while (<$infile>) {
        $line ++;
        $self->{input_line} = $line;

        if ( !utf8::decode($_) ) {
            $self->parse_error( __
"Invalid encoding: you must use UTF-8, but your source file was saved using another encoding"
            );
            last LINE;
        }

        chomp;

        debug ":> $_";

        # removes comments
        if (/^\s*\#/) {
            debug "Comment";
            next LINE;
        }

        # Insert other file...
        if (/^\s*IncludeFile:\s*(.*)/i) {
            my $filename = $1;
            $filename =~ s/\s+$//;
            my ( $volume, $directories, $file ) =
              File::Spec->splitpath($input_file);
            my $dir = File::Spec->catpath( $volume, $directories, '' );
            my $f   = File::Spec->rel2abs( $filename, $dir );
            debug "Include $f";
            if ( -f $f ) {
                $self->read_file($f);
            } else {
                $self->parse_error( sprintf( __("File not found: %s"), $f ) );
            }
        }

        # options
        if (/^\s*$opt_re:\s*(.*)/i) {
            debug "Option line ($1)";
            $self->{options}->{ lc($1) } = $2;
            $self->value_cleanup( $self->{reader_state}->{follow} );
            $self->{reader_state}->{follow} = \$self->{options}->{ lc($1) };
            $self->check_answers( $self->{reader_state}->{question} );
            $self->{reader_state}->{question} = '';
            next LINE;
        }

        if (/^([a-z0-9-]+):/i) {
            debug "Unknown option";

            $self->parse_error( sprintf( __(
# TRANSLATORS: Error text for AMC-TXT parsing, when an unknown option
# is given a value
                                            "Unknown option: %s"), $1 ) );
        }

        # groups
        if (/^\s*\*([\(\)])(?:\[([^]]*)\])?\s*(.*)/) {
            my $action  = $1;
            my $options = $2;
            my $text    = $3;
            debug "Group A=" . printable($action) . " O=" . printable($options);
            my %oo = $self->read_options($options);
            if ( $action eq '(' ) {
                $self->needs_package('needspace') if ( $oo{needspace} );
                $self->{reader_state}->{group} = $self->group_by_id(
                    $oo{group},
                    parent => $self->{reader_state}->{group},
                    header => $text,
                    %oo
                );
                $self->{reader_state}->{follow} =
                  \$self->{reader_state}->{group}->{header};
            } else {
                $self->{reader_state}->{group}->{footer} = $text;
                $self->{reader_state}->{follow} =
                  \$self->{reader_state}->{group}->{footer};
                $self->{reader_state}->{group} =
                  $self->{reader_state}->{group}->{parent};
            }
            next LINE;
        }

        # questions
        if (
/^\s*(\*{1,2})(?:<([^>]*)>)?(?:\[([^]]*)\])?(?:\{([^\}]*)\})?\s*(.*)/
          )
        {
            $self->check_answers( $self->{reader_state}->{question} );
            my $star    = $1;
            my $angles  = $2;
            my $options = $3;
            my $scoring = $4;
            my $text    = $5;
            debug "Question S=$star A="
              . printable($angles) . " O="
              . printable($options) . " S="
              . printable($scoring);
            my %oo      = $self->read_options($options);
            my $q_group = $self->{reader_state}->{group};

            if ( $oo{group} ) {
                $q_group = $self->group_by_id( $oo{group} );
            }

            $self->{reader_state}->{question} = add_object(
                $q_group->{questions},
                multiple => length($star) == 2,
                open     => ( defined($angles) ? $angles : '' ),
                scoring  => $scoring,
                text     => $text,
                answers  => [],
                %oo
            );
            $self->value_cleanup( $self->{reader_state}->{follow} );
            $self->{reader_state}->{follow} =
              \$self->{reader_state}->{question}->{text};
            next LINE;
        }

        # answers
        if (/^\s*(\+|-)(?:\[([^]]*)\])?(?:\{([^\}]*)\})?\s*(.*)/) {
            if ( $self->{reader_state}->{question} ) {
                my $sign    = $1;
                my $letter  = $2;
                my $scoring = $3;
                my $text    = $4;
                debug "Choice G=$sign L="
                  . printable($letter) . " S="
                  . printable($scoring);
                my $a = add_object(
                    $self->{reader_state}->{question}->{answers},
                    text    => $text,
                    correct => ( $sign eq '+' ),
                    letter  => $letter,
                    scoring => $scoring
                );
                $self->value_cleanup( $self->{reader_state}->{follow} );
                $self->{reader_state}->{follow} = \$a->{text};
            } else {
                debug "Choice outside question";

                $self->parse_error( __
# TRANSLATORS: Error text for AMC-TXT parsing when a choice is given
# but no question were opened
                                    "Choice outside question" );
            }
            next LINE;
        }

        # text following last line
        if ( $self->{reader_state}->{follow} ) {
            debug "Follow...";
            ${ $self->{reader_state}->{follow} } .= "\n" . $_;
        }
    }
    debug "Cleanup...";
    $self->value_cleanup( $self->{reader_state}->{follow} );
    close($infile);
}

# bold font LaTeX command, not used in arabic language because there
# is often no bold font arabic font.
sub bf_or {
    my ( $self, $replace, $bf ) = @_;
    return ( $self->{options}->{arabic} ? $replace : ( $bf ? $bf : "\\bf" ) );
}

####################################################################
# PARSING METHODS
#
# ARGUMENT: list of components
# RETURN VALUE: list of parsed components
#
# A component is a {type=>TYPE,string=>STRING} hashref, where
# * TYPE is the component type: 'txt' for AMC-TXT text, 'latex' for
#   LaTeX code.
# * STRING is the component string
#
# When all parsing methods has been applied, the result must be a list
# of 'latex' components, that will be concatenated to get the LaTeX
# code corresponding to the source file.

# parse_images extracts an image specification (like '!image.jpg!')
# from 'txt' components, and replaces the component with 3 components:
# the preceding text, the LaTeX code that inserts the image, and the
# following text
sub parse_images {
    my ( $self, @components ) = @_;
    my @o = ();
    for my $c (@components) {
        if ( $c->{type} eq 'txt' ) {
            my $s = $c->{string};
            while ( $s =~ /!(?:\{([^!\s]+)\})?(?:\[([^!\s]+)\])?([^!\s]+)!/p ) {
                my $options    = $1;
                my $ig_options = $2;
                my $path       = $3;
                my $before     = ${^PREMATCH};
                my $after      = ${^POSTMATCH};
                push @o, { type => 'txt', string => $before };
                my $l =
                    "\\includegraphics"
                  . ( $ig_options ? '[' . $ig_options . ']' : '' ) . '{'
                  . $path . '}';
                if ( $options =~ /\bcenter\b/ ) {
                    $l = "\\begin{center}$l\\end{center}";
                }
                push @o, { type => 'latex', string => $l };
                $s = $after;
            }
            push @o, { type => 'txt', string => $s };
        } else {
            push @o, $c;
        }
    }
    return (@o);
}

# parse_local_latex extracts a local LaTeX specification (like
# '[[$f(x)$]]') from 'txt' components
sub parse_local_latex {
    my ( $self, @components ) = @_;
    my @o = ();
    for my $c (@components) {
        if ( $c->{type} eq 'txt' ) {
            my $s = $c->{string};
            while ( $s =~ /\[\[(((?!\]\]).)+)\]\]/p ) {
                my $latex  = $1;
                my $before = ${^PREMATCH};
                my $after  = ${^POSTMATCH};
                push @o, { type => 'txt',   string => $before };
                push @o, { type => 'latex', string => $latex };
                $s = $after;
            }
            push @o, { type => 'txt', string => $s };
        } else {
            push @o, $c;
        }
    }
    return (@o);
}

# generic code to parse '[xxx] ... [/xxx]' constructs
sub parse_tags {
    my ( $self, $name, $parse_content, @components ) = @_;
    my @o = ();
    for my $c (@components) {
        if ( $c->{type} eq 'txt' ) {
            my $s = $c->{string};
            while ( $s =~ /\[\Q$name\E\](.*?)\[\/\Q$name\E\]/sp ) {
                my $content = $1;
                my $before  = ${^PREMATCH};
                my $after   = ${^POSTMATCH};
                push @o, { type => 'txt', string => $before };
                push @o, &$parse_content( $self, $content );
                $s = $after;
            }
            push @o, { type => 'txt', string => $s };
        } else {
            push @o, $c;
        }
    }
    return (@o);
}

# insert LaTeX code to write verbatim texts
sub verbatim_content {
    my ( $self, $verb ) = @_;
    my $letter = $self->unused_letter();

    # adds linebreaks at the beginning and end of $verb, if they none already
    $verb = "\n" . $verb if ( $verb !~ /^\n/ );
    $verb = $verb . "\n" if ( $verb !~ /\n$/ );

    $self->add_global_latex_def(
        "\\begin{SaveVerbatim}{AMCverb$letter}$verb\\end{SaveVerbatim}");
    $self->needs_package('fancyvrb');
    return (
        {
            type   => 'latex',
            string => "\\UseVerbatim{AMCverb$letter}"
        }
    );
}

# parse [verbatim] ... [/verbatim] constructs
sub parse_verbatim {
    my ( $self, @components ) = @_;
    return ( $self->parse_tags( "verbatim", \&verbatim_content, @components ) );
}

# generic code to parse '[xxx ... xxx]' constructs
sub parse_brackets {
    my ( $self, $modifier, $tex_open, $tex_close, @components ) = @_;
    my @o      = ();
    my $levels = 0;
    my $tex;
    for my $c (@components) {
        if ( $c->{type} eq 'txt' ) {
            my $s = $c->{string};
            while ( $s =~ /(\[\Q$modifier\E|\Q$modifier\E\])/p ) {
                my $sep    = $1;
                my $before = ${^PREMATCH};
                my $after  = ${^POSTMATCH};
                if ( $sep =~ /^\[/ ) {
                    $tex = $tex_open;
                    $levels++;
                } else {
                    $tex = $tex_close;
                    $levels--;
                }
                push @o, { type => 'txt',   string => $before };
                push @o, { type => 'latex', string => $tex };
                $s = $after;
            }
            push @o, { type => 'txt', string => $s };
        } else {
            push @o, $c;
        }
    }
    return (@o);
}

# parse_embf inserts LaTeX commands to switch to italic, bold or
# typewriter font or underlined text when '[_ ... _]', '[* ... *]',
# '[| ... |]' or '[/ ... /]' constructs are used in AMC-TXT, respectively.
sub parse_embf {
    my ( $self, @components ) = @_;
    my @c = $self->parse_brackets( '_', "\\textit{", "}", @components );
    @c = $self->parse_brackets( '*', "\\textbf{",    "}", @c );
    @c = $self->parse_brackets( '/', "\\underline{", "}", @c );
    @c = $self->parse_brackets( '|', "\\texttt{",    "}", @c );
    return (@c);
}

# parse_title inserts LaTeX commands to build a title line from '[==
# ... ==]' constructs.
sub parse_title {
    my ( $self, @components ) = @_;
    return (
        $self->parse_brackets( '==', "\\AMCmakeTitle{", "}", @components ) );
}

# parse_text transforms plain text (with no special constructs) to
# LaTeX code, escaping some characters that have special meaning for
# LaTeX.
sub parse_text {
    my ( $self, @components ) = @_;
    my @o = ();
    for my $c (@components) {
        if ( $c->{type} eq 'txt' ) {
            my $s = $c->{string};
            if ( !$self->{options}->{latex} ) {
                $s =~ s/\\/\\(\\backslash\\)/g;
                $s =~ s/~/\\(\\sim\\)/g;
                $s =~ s/\*/\\(\\ast\\)/g;
                $s =~ s/([&{}\#_%])/\\$1/g;
                $s =~ s/-/-{}/g;
                $s =~ s/\$/\\textdollar{}/g;
                $s =~ s/\^/\\textasciicircum{}/g;
            }
            push @o, { type => 'latex', string => $s };
        } else {
            push @o, $c;
        }
    }
    return (@o);
}

# parse_all calls all requested parse_* methods in turn (when they are
# not disabled by the Disable global option).
sub parse_all {
    my ( $self, @components ) = @_;
    for my $m ( @{ $self->{parse_modules} } ) {
        my $mm = 'parse_' . $m;
        @components = $self->$mm(@components)
          if ( $self->{options}->{disable} !~ /\b$m\b/ );
    }
    return (@components);
}

# Checks that the resulting components list has only 'latex' components
sub check_latex {
    my ( $self, @components ) = @_;
    my @s = ();
    for my $c (@components) {
        if ( $c->{type} ne 'latex' ) {
            debug_and_stderr "ERR(FILTER): non-latex resulting component ("
              . $c->{type} . "): "
              . $c->{string};
        }
        push @s, $c->{string};
    }
    return (@s);
}

# converts AMC-TXT string to a LaTeX string: make a single 'txt'
# component, apply parse_all and check_latex, and then concatenates
# the components
sub format_text {
    my ( $self, $t ) = @_;
    my $src;
    if ( ref($t) eq 'HASH' ) {
        $src = $t;
    } else {
        $t =~ s/^\s+//;
        $t =~ s/\s+$//;
        $src = { type => 'txt', string => $t };
    }

    return ( join( '', $self->check_latex( $self->parse_all($src) ) ) );
}

# builds the LaTeX scoring command from the question's scoring
# strategy (or the default scoring strategy)
sub scoring_string {
    my ( $self, $obj, $type ) = @_;

    # manual scoring if some scoring was used, either for the question
    # or for one of the answers
    my $manual_scoring = ( length $obj->{scoring} ? 1 : 0 );
    if ( $obj->{answers} ) {
        for my $a ( @{ $obj->{answers} } ) {
            $manual_scoring = 1 if ( length $a->{scoring} );
        }
    }
    my $s = $obj->{scoring};

    # set to explicit default (defined by DefaultScoringS or
    # DefaultScoringM):
    if ( !length($s) ) {
        $s = $self->{options}->{ 'defaultscoring' . $type };
    }

    # if no manual scoring and no explicit default scoring, use the
    # implicit default scoring:
    if ( !length($s) && !$manual_scoring ) {
        $s = $self->{options}->{ 'implicitdefaultscoring' . $type };
    }
    return ( length($s) ? "\\scoring{$s}" : "" );
}

# builds the LaTeX code for an answer: \correctchoice or \wrongchoice,
# followed by the scoring command
sub format_answer {
    my ( $self, $a ) = @_;
    my $t = '\\' . ( $a->{correct} ? 'correct' : 'wrong' ) . 'choice';
    $t .= '[' . $a->{letter} . ']' if ( defined($a->{letter}) && $a->{letter} ne '' );
    $t .= '{' . $self->format_text( $a->{text} ) . "}";
    $t .= $self->scoring_string( $a, 'a' );
    $t .= "\n";
    return ($t);
}

sub arabic_env {
    my ( $self, $action ) = @_;
    if ( $self->{options}->{arabic} && $self->bidi_year() < 2011 ) {
        return ( "\\" . $action . "{arab}" );
    } else {
        return ("");
    }
}

# builds the LaTeX code for the question (including answers)
sub format_question {
    my ( $self, $q ) = @_;
    my $t = '';

    if ( $q->{textonly} ) {

        $t .= $self->arabic_env('begin');
        $t .= $self->format_text( $q->{text} ) . "\n";
        $t .= $self->arabic_env('end');

    } else {

        my $qid = $q->{id};
        $qid = $q->{name} if ( !$qid );
        $qid = sprintf( "Q%03d", ++$self->{qid} ) if ( !$qid );
        my $mult = ( $q->{multiple} ? 'mult'  : '' );
        my $ct   = ( $q->{horiz}    ? 'horiz' : '' );

        $t .= $self->arabic_env('begin');
        $t .= '\\begin{question' . $mult . '}{' . $qid . "}";
        $t .= $self->scoring_string( $q, ( $q->{multiple} ? 'm' : 's' ) );
        $t .= "\n";
        $t .= $self->format_text( $q->{text} ) . "\n";
        $t .= "\\QuestionIndicative\n" if ( $q->{indicative} );
        if ( $q->{open} ne '' ) {
            $t .= "\\AMCOpen{" . $q->{open} . "}{";
        } else {
            $t .= "\\begin{multicols}{" . $q->{columns} . "}\n"
              if ( is_multicol($q) );
            $t .= "\\begin{choices$ct}" . ( $q->{ordered} ? "[o]" : "" ) . "\n";
        }
        for my $a ( @{ $q->{answers} } ) {
            $t .= $self->format_answer($a);
        }
        if ( $q->{open} ne '' ) {
            $t .= "}\n";
        } else {
            $t .= "\\end{choices$ct}\n";
            $t .= "\\end{multicols}\n"
              if ( is_multicol($q) );
        }
        $t .= "\\end{question" . $mult . "}";
        $t .= $self->arabic_env('end');
        $t .= "\n";
    }

    return ($t);
}

sub int_to_letters {
    my ( $self, $i ) = @_;
    my $l = '';
    while ( $i > 0 ) {
        $l = chr( ord("A") + ( $i % 26 ) ) . $l;
        $i = int( $i / 26 );
    }
    return ($l);
}

sub unused_letter {
    my ($self) = @_;
    $self->{letter_i}++;
    return ( $self->int_to_letters( $self->{letter_i} ) );
}

# returns a new group name 'groupX' (where X is a letter beginnig at
# A)
sub create_group_name {
    my ($self) = @_;
    return ( "gr" . $self->unused_letter() );
}

# returns the group name (creating one if necessary)
sub group_name {
    my ( $self, $group ) = @_;
    if ( !$group->{name} ) {
        if ( $group->{id} =~ /^[a-z]+$/i ) {
            $group->{name} = $group->{id};
        } else {
            $group->{name} = $self->create_group_name();
        }
    }
    return ( $group->{name} );
}

# gets the Year for the version of installed bidi.sty. This will be
# used to adapt the LaTeX code to version before or after 2011
sub bidi_year {
    my ($self) = @_;
    if ( !$self->{bidiyear} ) {
        my $f = find_latex_file("bidi.sty");
        if ( -f $f ) {
            open( BIDI, $f );
          BIDLIG: while (<BIDI>) {
                if (/\\bididate\{([0-9]+)\//) {
                    $self->{bidiyear} = $1;
                    last BIDLIG;
                }
            }
            close(BIDI);
        }
    }
    return ( $self->{bidiyear} );
}

# builds and returns the LaTeX header
sub file_header {
    my ($self) = @_;
    my $t = '';

    my @package_options = ();

    my $o = $self->{options}->{packageoptions};
    if ($o) {
        $o =~ s/^\s+//;
        $o =~ s/\s+$//;
        for my $oo ( split( /,+/, $o ) ) {
            push @package_options, $oo;
        }
    }

    push @package_options, "bloc" if ( $self->{options}->{questionblocks} );
    for my $on (qw/completemulti separateanswersheet automarks/) {
        push @package_options, $on if ( $self->{options}->{$on} );
    }

    push @package_options, "lang=" . uc( $self->{options}->{lang} )
      if ( $self->{options}->{lang} );

    my $po = '';
    $po = '[' . join( ',', @package_options ) . ']' if (@package_options);

    if ( $self->{options}->{arabic} ) {
        $t .= "% bidi YEAR " . $self->bidi_year() . "\n";
    }

    $t .= "\\documentclass{article}\n";
    $t .= "\\usepackage{bidi}\n"
      if ( $self->{options}->{arabic} && $self->bidi_year() < 2011 );
    $t .= "\\usepackage{xltxtra}\n" if ( $self->{options}->{xltxtra} );
    $t .= "\\usepackage{arabxetex}\n"
      if ( $self->{options}->{arabic} && $self->bidi_year() < 2011 );
    $t .= "\\usepackage" . $po . "{automultiplechoice}\n";
    $t .=
      "\\usepackage{"
      . (    $self->{options}->{arabic}
          && $self->bidi_year() < 2011 ? "fmultico" : "multicol" )
      . "}\n";

    # packages
    for my $p ( keys %{ $self->{packages} } ) {
        my @opts = ();
        for my $o ( keys %{ $self->{packages}->{$p} } ) {
            push @opts,
              (
                $o
                  . (
                    $self->{packages}->{$p}->{$o} eq ''
                    ? ''
                    : "=" . $self->{packages}->{$p}->{$o}
                  )
              );
        }
        $t .=
            "\\usepackage"
          . ( @opts ? "[" . join( ",", @opts ) . "]" : "" ) . "{"
          . $p . "}\n";
    }

    $t .= "\\setmainfont{" . $self->{options}->{font} . "}\n"
      if ( $self->{options}->{font} );
    $t .=
      "\\newfontfamily{\\arabicfont}[Script=Arabic,Scale=1]{"
      . $self->{options}->{arabicfont} . "}\n"
      if ( $self->{options}->{arabicfont} && $self->{options}->{arabic} );
    $t .= "\\geometry{paper=" . lc( $self->{options}->{papersize} ) . "paper}\n"
      if ( $self->{options}->{papersize} );
    $t .= $self->{options}->{'latex-preambule'};
    $t .= "\\usepackage{arabxetex}\n"
      if ( $self->{options}->{arabic} && $self->bidi_year() >= 2011 );
    $t .= "\\begin{document}\n";
    $t .=
"\\def\\AMCmakeTitle#1{\\par\\noindent\\hrule\\vspace{1ex}{\\hspace*{\\fill}\\Large\\bf #1\\hspace*{\\fill}}\\vspace{1ex}\\par\\noindent\\hrule\\par\\vspace{1ex}}\n";
    $t .= "\\AMCrandomseed{" . $self->{options}->{randomseed} . "}\n";

    if ( $self->{options}->{boxcolor} ) {
        if ( $self->{options}->{boxcolor} =~ /^\\definecolor\{amcboxcolor\}/ ) {
            $t .= $self->{options}->{boxcolor};
        } elsif ( $self->{options}->{boxcolor} =~
            /^\#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i )
        {
            $t .= "\\definecolor{amcboxcolor}{rgb}{"
              . sprintf( "%0.2f,%0.2f,%0.2f",
                map { hex($_) / 256.0 } ( $1, $2, $3 ) )
              . "}\n";
        } else {
            $t .= "\\definecolor{amcboxcolor}{named}{"
              . $self->{options}->{boxcolor} . "}\n";
        }
        $t .= "\\AMCboxColor{amcboxcolor}\n";
    }
    $t .=
      "\\AMCtext{none}{"
      . $self->format_text( $self->{options}->{'l-none'} ) . "}\n"
      if ( $self->{options}->{'l-none'} );
    $t .=
      "\\def\\AMCotextGoto{\\par "
      . $self->format_text( $self->{options}->{'l-opentext'} ) . "}\n"
      if ( $self->{options}->{'l-opentext'} );
    $t .=
      "\\def\\AMCotextReserved{"
      . $self->format_text( $self->{options}->{'l-openreserved'} ) . "}\n"
      if ( $self->{options}->{'l-openreserved'} );

    $t .=
        "\\def\\AMCbeginQuestion#1#2{\\noindent{"
      . $self->bf_or("\\Large") . " "
      . $self->{options}->{'l-question'}
      . " #1} #2\\hspace{1em}}\n"
      . "\\def\\AMCformQuestion#1{{"
      . $self->bf_or("\\Large") . " "
      . $self->{options}->{'l-question'}
      . " #1 :}}\n"
      if ( $self->{options}->{'l-question'} );
    if ( $self->{options}->{arabic} ) {
        $t .=
"\\def\\AMCchoiceLabel#1{\\csname ArabicAlphabet\\Alph{#1}\\endcsname}\n";
        my $letter = "A";
        for my $c (@alphabet_arabic) {
            $t .= "\\def\\ArabicAlphabet$letter" . "{$c}\n";
            $letter++;
        }
    }
    $t .= $self->{options}->{'latex-begindocument'};

    return ($t);
}

# Builds and returns the question sheet head (or the answer sheet head
# if $answersheet is true)
sub page_header {
    my ( $self, $answersheet ) = @_;
    my $t = "";

    my $titlekey = '';

    if ( $self->{options}->{separateanswersheet} ) {
        if ($answersheet) {
            if ( $self->{options}->{code} > 0 ) {
                $titlekey = 'answersheettitle';
            }
        } else {
            $titlekey = 'title';
        }
    } else {
        if ( $self->{options}->{code} > 0 ) {
            $titlekey = 'title';
        }
    }
    if ( $titlekey && $self->{options}->{$titlekey} ) {
        $t .=
            "\\begin{center}"
          . $self->bf_or( "\\Large", "\\bf\\large" ) . " "
          . $self->format_text( $self->{options}->{$titlekey} )
          . "\\end{center}";
        $t .= "\n\n";
    }
    return ($t);
}

# Builds and returns the name field LaTeX code
sub full_namefield {
    my ( $self, $with_code ) = @_;
    my $n_ligs;
    if ( $self->{options}->{namefieldlines} ) {
        $n_ligs = $self->{options}->{namefieldlines};
    } else {
        $n_ligs = ( $with_code ? 2 : 1 );
    }
    my $t = '';
    $t .= "\\namefield{\\fbox{";
    $t .= "\\begin{minipage}{.9\\linewidth}";
    if ( $self->{options}->{preassociation} ) {
      $t .= "\\vspace*{1mm}\\AMClocalized{namesurname}\\vspace*{2mm}\\newline\\hspace*{.5em}{\\Large\\bf ".$self->{options}->{preassociationname}."}";
    } else {
        $t .= (
              $self->{options}->{'l-name'}
            ? $self->{options}->{'l-name'}
            : '\\AMClocalized{namesurname}'
          )
          . (
            (
                    "\n\n\\vspace*{"
                  . $self->{options}->{namefieldlinespace}
                  . "}\\dotfill"
            ) x $n_ligs
          );
    }
    $t .= "\n\\vspace*{1mm}" . "\n\\end{minipage}";
    $t .= "\n}}";
    return ($t);
}

# Builds and returns the student identification block LaTeX code (with
# name field and AMCcode if requested)
sub student_block {
    my ($self) = @_;
    my $t = '';

    if ( $self->{options}->{code} > 0 ) {

        # Header layout with a code (student number)

        my $vertical = ( $self->{options}->{code} > $self->{maxhorizcode} );
        $vertical = 1 if ( $self->{options}->{codedigitsdirection} =~ /^v/i );
        $vertical = 0 if ( $self->{options}->{codedigitsdirection} =~ /^h/i );

        $t .= "{\\setlength{\\parindent}{0pt}\\hspace*{\\fill}";
        $t .= ( $vertical ? "" : "\\hbox{\\vtop{" );
        $t .= "\\LR{" if ( $self->{options}->{arabic} && $vertical );
        $t .=
            "\\AMCcode"
          . ( $vertical ? "" : "H" )
          . "{student.number}{"
          . $self->{options}->{code} . "}";
        $t .= "}" if ( $self->{options}->{arabic} && $vertical );
        $t .=
            ( $vertical ? "" : "}}" )
          . "\\hspace*{\\fill}"
          . "\\begin{minipage}"
          . ( $vertical ? "[b]" : "[t]" ) . "{"
          . ( $self->{options}->{namefieldwidth}
            ? $self->{options}->{namefieldwidth}
            : '5.8cm' )
          . "}"
          . "\$\\long"
          . ( $self->{options}->{arabic} ? "right" : "left" )
          . "arrow{}\$\\hspace{0pt plus 1cm}"
          . $self->{options}->{'l-student'}
          . "\\vspace{3ex}\n\n\\hfill"
          . $self->full_namefield(1)
          . "\\hfill\\vspace{5ex}\\end{minipage}\\hspace*{\\fill}" . "\n\n}";
        $t .= "\\vspace{4mm}\n";
    } else {

        # header layout without code
        $t .= "\\begin{minipage}{" . $self->{options}->{titlewidth} . "}\n";
        my $titlekey =
          ( $self->{options}->{separateanswersheet}
            ? 'answersheettitle'
            : 'title' );
        if ( $self->{options}->{$titlekey} ) {
            $t .=
                "\\begin{center}"
              . $self->bf_or( "\\Large", "\\bf\\large" ) . " "
              . $self->format_text( $self->{options}->{$titlekey} )
              . "\\end{center}\n\n";
        }
        $t .= "\\end{minipage}\\hfill\n";
        $t .=
          "\\begin{minipage}{"
          . ( $self->{options}->{namefieldwidth}
            ? $self->{options}->{namefieldwidth}
            : ".47\\linewidth" )
          . "}\n";
        $t .= $self->full_namefield(0);
        $t .= "\\end{minipage}\\vspace{4mm}\n\n";
    }
    return ($t);
}

sub group_insert_command_name {
    my ( $self, $group ) = @_;
    return ( "\\insertPlainGroup" . $self->group_name($group) );
}

sub group_insert_command_def {
    my ( $self, $group ) = @_;
    my $t = "\\def" . $self->group_insert_command_name($group) . "{";
    $t .= "\\needspace{" . $group->{needspace} . "}\n"
      if ( $group->{needspace} );
    if ( $group->{header} ) {
        $t .= "\\noindent " . $self->format_text( $group->{header} );
        $t .= "\\vspace{1.5ex}\\par\n"
          if (!$group->{custom}
            && !is_multicol($group) );
    }
    $t .= "\\begin{multicols}{" . $group->{columns} . "}"
      if ( is_multicol($group) );
    for my $q ( grep { $_->{first} } ( @{ $group->{questions} } ) ) {
        $t .= $self->format_question($q) . "\n";
    }
    $t .= "\\insertgroup";
    $t .= "[" . $group->{numquestions} . "]" if ( $group->{numquestions} );
    $t .= "{" . $self->group_name($group) . "}";
    for my $q ( grep { $_->{last} } ( @{ $group->{questions} } ) ) {
        $t .= "\n" . $self->format_question($q);
    }
    $t .= "\\end{multicols}"
      if ( is_multicol($group) );
    if ( $group->{footer} ) {
        $t .= $self->format_text( $group->{footer} );
        $t .= "\\vspace{1.5ex}\\par\n"
          if ( !$group->{custom} && !$group->{cut} );
    }
    $t .= "}\n";
    return ($t);
}

# writes the LaTeX output file
sub write_latex {
    my ( $self, $output_file ) = @_;

    my $tex = '';

    for my $group ( @{ $self->{groups} } ) {

        # create group elements from the questions

        my @questions =
          grep { !( $_->{first} || $_->{last} ) } @{ $group->{questions} };

        my $q;
        while ( $q = shift @questions ) {
            $tex .= "\\element{" . $self->group_name($group) . "}{\n";
            $tex .= $self->format_question($q);
            while ( @questions && $questions[0]->{next} ) {
                $tex .= "\n";
                $tex .= $self->format_question( shift @questions );
            }
            $tex .= "}\n";
        }

        # command to print the group

        $tex .= $self->group_insert_command_def($group);
    }

    # beginning of copy
    if ( $self->{options}->{preassociation} ) {
        $tex .=
            "\\AMCstudentslistfile{"
          . $self->{options}->{preassociation} . "}{"
          . $self->{options}->{preassociationkey} . "}\n";
        $tex .= "\\def\\CopyModel{\n\\onecopy{1}{\n";
    } else {
        $tex .= "\\onecopy{5}{\n";
    }
    if ( $self->{options}->{'pdf-begincopy'} ) {
        $tex .= '\\includepdf[pages=-,pagecommand={\\thispagestyle{empty}}]{'
          . $self->{options}->{'pdf-begincopy'} . "}\n";
    }
    $tex .= $self->{options}->{'latex-begincopy'};

    $tex .= "\\begin{arab}" if ( $self->{options}->{arabic} );
    $tex .= $self->page_header(0);
    $tex .= $self->student_block
      if ( !$self->{options}->{separateanswersheet} );

    if ( $self->{options}->{presentation} ) {
        $tex .= $self->format_text( $self->{options}->{presentation} ) . "\n\n";
    }
    $tex .= "\\vspace{4mm}\\noindent\\hrule\n";
    $tex .= "\\end{arab}" if ( $self->{options}->{arabic} );
    $tex .= "\n\n";

    # shuffle groups...
    for my $g ( @{ $self->{groups} } ) {
        $tex .=
            "\\shufflegroup{"
          . $self->group_name($g)
          . "}\n"
          if (
            parse_bool(
                first_defined(
                    $g->{shuffle}, $self->{options}->{shufflequestions}
                )
            )
          );
    }

    # print groups
    $tex .= "\\begin{arab}"
      if ( $self->{options}->{arabic} && $self->bidi_year() >= 2011 );
    if ( is_multicol( $self->{options} ) ) {
        $tex .= "\\begin{multicols}{" . $self->{options}->{columns} . "}\n";
    }
    else {
        $tex .= "\\vspace{2ex}\n\n";
    }

    $tex .=
      $self->group_insert_command_name( $self->group_by_id('_main_') ) . "\n";

    if ( is_multicol( $self->{options} ) ) {
        $tex .= "\\end{multicols}\n";
    }
    $tex .= "\\end{arab}"
      if ( $self->{options}->{arabic} && $self->bidi_year() >= 2011 );

    # separate answer sheet
    if ( $self->{options}->{separateanswersheet} ) {
        $tex .= "\n\\AMCaddpagesto{" . $self->{options}->{pages_question} . "}"
          if ( $self->{options}->{pages_question} );
        if ( $self->{options}->{singlesided} ) {
            $tex .= "\n\\clearpage\n\n";
        } else {
            $tex .= "\n\\AMCcleardoublepage\n\n";
        }
        $tex .= "\\AMCformBegin\n";

        $tex .= "\\begin{arab}" if ( $self->{options}->{arabic} );
        $tex .= $self->page_header(1);
        $tex .= $self->student_block;
        if ( $self->{options}->{answersheetpresentation} ) {
            $tex .=
              $self->format_text( $self->{options}->{answersheetpresentation} )
              . "\n\n";
        }
        $tex .= "\\vspace{4mm}\\noindent\\hrule\n";
        $tex .= "\\end{arab}" if ( $self->{options}->{arabic} );
        $tex .= "\n\n";

        $tex .= "\\begin{arab}" if ( $self->{options}->{arabic} );
        $tex .=
          "\\begin{multicols}{"
          . $self->{options}->{answersheetcolumns} . "}\n"
          if ( $self->{options}->{answersheetcolumns} > 1 );
        $tex .= "\\AMCform\n";
        $tex .= "\\end{multicols}\n"
          if ( $self->{options}->{answersheetcolumns} > 1 );
        $tex .= "\\end{arab}" if ( $self->{options}->{arabic} );
    }

    $tex .= "\n\n";
    $tex .= $self->{options}->{'latex-endcopy'};
    if ( $self->{options}->{'pdf-endcopy'} ) {
        $tex .= '\includepdf[pages=-,pagecommand={\thispagestyle{empty}}]{'
          . $self->{options}->{'pdf-endcopy'} . "}\n";
    }
    $tex .= "\\AMCaddpagesto{" . $self->{options}->{pages_total} . "}\n"
      if ( $self->{options}->{pages_total} );
    $tex .= "\\AMCcleardoublepage\n" if ( $self->{options}->{manualduplex} );

    # end of copy
    if ( $self->{options}->{preassociation} ) {
        $tex .=
          "\\AMCassociation{\\" . $self->{options}->{preassociationkey} . "}\n";
        $tex .= "}\n}\n";
        $tex .=
            "\\csvreader[head to column names]{"
          . $self->{options}->{preassociation}
          . "}{}{\\CopyModel}\n";
    } else {
        $tex .= "}\n";
    }

    $tex .= "\\end{document}\n";

    open( OUT, ">:utf8", $output_file );

    print OUT $self->file_header();
    print OUT join( "\n", @{ $self->{latex_defs} } ) . "\n";
    print OUT $tex;

    close(OUT);
}

# Checks that the requested prerequisites (in fact, fonts) are
# installed on the system
sub check {
    my ($self) = @_;
    my @cf     = ('font');
    my @mf     = ();
    push @cf, 'arabicfont' if ( $self->{options}->{arabic} );
    for my $k (@cf) {
        if ( $self->{options}->{font} ) {
            if (
                !check_fonts(
                    {
                        type   => 'fontconfig',
                        family => [ $self->{options}->{$k} ]
                    }
                )
              )
            {
                push @mf, $self->{options}->{$k};
            }
        }
    }
    $self->error(
        sprintf(
            __(
"The following fonts does not seem to be installed on the system: <b>%s</b>."
            ),
            join( ', ', @mf )
        )
    ) if (@mf);
}

# Whole filter processing
sub filter {
    my ( $self, $input_file, $output_file ) = @_;
    $self->read_source($input_file);
    $self->parse_options();
    $self->check();
    $self->write_latex($output_file);
}

1;