OSDN Git Service

Fortran frontend changelog:
[pf3gnuchains/gcc-fork.git] / libgfortran / io / transfer.c
1 /* Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007
2    Free Software Foundation, Inc.
3    Contributed by Andy Vaught
4    Namelist transfer functions contributed by Paul Thomas
5
6 This file is part of the GNU Fortran 95 runtime library (libgfortran).
7
8 Libgfortran is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
11 any later version.
12
13 In addition to the permissions in the GNU General Public License, the
14 Free Software Foundation gives you unlimited permission to link the
15 compiled version of this file into combinations with other programs,
16 and to distribute those combinations without any restriction coming
17 from the use of this file.  (The General Public License restrictions
18 do apply in other respects; for example, they cover modification of
19 the file, and distribution when not linked into a combine
20 executable.)
21
22 Libgfortran is distributed in the hope that it will be useful,
23 but WITHOUT ANY WARRANTY; without even the implied warranty of
24 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 GNU General Public License for more details.
26
27 You should have received a copy of the GNU General Public License
28 along with Libgfortran; see the file COPYING.  If not, write to
29 the Free Software Foundation, 51 Franklin Street, Fifth Floor,
30 Boston, MA 02110-1301, USA.  */
31
32
33 /* transfer.c -- Top level handling of data transfer statements.  */
34
35 #include "config.h"
36 #include <string.h>
37 #include <assert.h>
38 #include "libgfortran.h"
39 #include "io.h"
40
41
42 /* Calling conventions:  Data transfer statements are unlike other
43    library calls in that they extend over several calls.
44
45    The first call is always a call to st_read() or st_write().  These
46    subroutines return no status unless a namelist read or write is
47    being done, in which case there is the usual status.  No further
48    calls are necessary in this case.
49
50    For other sorts of data transfer, there are zero or more data
51    transfer statement that depend on the format of the data transfer
52    statement.
53
54       transfer_integer
55       transfer_logical
56       transfer_character
57       transfer_real
58       transfer_complex
59
60     These subroutines do not return status.
61
62     The last call is a call to st_[read|write]_done().  While
63     something can easily go wrong with the initial st_read() or
64     st_write(), an error inhibits any data from actually being
65     transferred.  */
66
67 extern void transfer_integer (st_parameter_dt *, void *, int);
68 export_proto(transfer_integer);
69
70 extern void transfer_real (st_parameter_dt *, void *, int);
71 export_proto(transfer_real);
72
73 extern void transfer_logical (st_parameter_dt *, void *, int);
74 export_proto(transfer_logical);
75
76 extern void transfer_character (st_parameter_dt *, void *, int);
77 export_proto(transfer_character);
78
79 extern void transfer_complex (st_parameter_dt *, void *, int);
80 export_proto(transfer_complex);
81
82 extern void transfer_array (st_parameter_dt *, gfc_array_char *, int,
83                             gfc_charlen_type);
84 export_proto(transfer_array);
85
86 static void us_read (st_parameter_dt *, int);
87 static void us_write (st_parameter_dt *, int);
88 static void next_record_r_unf (st_parameter_dt *, int);
89 static void next_record_w_unf (st_parameter_dt *, int);
90
91 static const st_option advance_opt[] = {
92   {"yes", ADVANCE_YES},
93   {"no", ADVANCE_NO},
94   {NULL, 0}
95 };
96
97
98 typedef enum
99 { FORMATTED_SEQUENTIAL, UNFORMATTED_SEQUENTIAL,
100   FORMATTED_DIRECT, UNFORMATTED_DIRECT, FORMATTED_STREAM, UNFORMATTED_STREAM
101 }
102 file_mode;
103
104
105 static file_mode
106 current_mode (st_parameter_dt *dtp)
107 {
108   file_mode m;
109
110   m = FORM_UNSPECIFIED;
111
112   if (dtp->u.p.current_unit->flags.access == ACCESS_DIRECT)
113     {
114       m = dtp->u.p.current_unit->flags.form == FORM_FORMATTED ?
115         FORMATTED_DIRECT : UNFORMATTED_DIRECT;
116     }
117   else if (dtp->u.p.current_unit->flags.access == ACCESS_SEQUENTIAL)
118     {
119       m = dtp->u.p.current_unit->flags.form == FORM_FORMATTED ?
120         FORMATTED_SEQUENTIAL : UNFORMATTED_SEQUENTIAL;
121     }
122   else if (dtp->u.p.current_unit->flags.access == ACCESS_STREAM)
123     {
124       m = dtp->u.p.current_unit->flags.form == FORM_FORMATTED ?
125         FORMATTED_STREAM : UNFORMATTED_STREAM;
126     }
127
128   return m;
129 }
130
131
132 /* Mid level data transfer statements.  These subroutines do reading
133    and writing in the style of salloc_r()/salloc_w() within the
134    current record.  */
135
136 /* When reading sequential formatted records we have a problem.  We
137    don't know how long the line is until we read the trailing newline,
138    and we don't want to read too much.  If we read too much, we might
139    have to do a physical seek backwards depending on how much data is
140    present, and devices like terminals aren't seekable and would cause
141    an I/O error.
142
143    Given this, the solution is to read a byte at a time, stopping if
144    we hit the newline.  For small allocations, we use a static buffer.
145    For larger allocations, we are forced to allocate memory on the
146    heap.  Hopefully this won't happen very often.  */
147
148 char *
149 read_sf (st_parameter_dt *dtp, int *length, int no_error)
150 {
151   char *base, *p, *q;
152   int n, readlen, crlf;
153   gfc_offset pos;
154
155   if (*length > SCRATCH_SIZE)
156     dtp->u.p.line_buffer = get_mem (*length);
157   p = base = dtp->u.p.line_buffer;
158
159   /* If we have seen an eor previously, return a length of 0.  The
160      caller is responsible for correctly padding the input field.  */
161   if (dtp->u.p.sf_seen_eor)
162     {
163       *length = 0;
164       return base;
165     }
166
167   if (is_internal_unit (dtp))
168     {
169       readlen = *length;
170       q = salloc_r (dtp->u.p.current_unit->s, &readlen);
171       memcpy (p, q, readlen);
172       goto done;
173     }
174
175   readlen = 1;
176   n = 0;
177
178   do
179     {
180       q = salloc_r (dtp->u.p.current_unit->s, &readlen);
181       if (q == NULL)
182         break;
183
184       /* If we have a line without a terminating \n, drop through to
185          EOR below.  */
186       if (readlen < 1 && n == 0)
187         {
188           if (no_error)
189             break;
190           generate_error (&dtp->common, ERROR_END, NULL);
191           return NULL;
192         }
193
194       if (readlen < 1 || *q == '\n' || *q == '\r')
195         {
196           /* Unexpected end of line.  */
197
198           /* If we see an EOR during non-advancing I/O, we need to skip
199              the rest of the I/O statement.  Set the corresponding flag.  */
200           if (dtp->u.p.advance_status == ADVANCE_NO || dtp->u.p.seen_dollar)
201             dtp->u.p.eor_condition = 1;
202
203           crlf = 0;
204           /* If we encounter a CR, it might be a CRLF.  */
205           if (*q == '\r') /* Probably a CRLF */
206             {
207               readlen = 1;
208               pos = stream_offset (dtp->u.p.current_unit->s);
209               q = salloc_r (dtp->u.p.current_unit->s, &readlen);
210               if (*q != '\n' && readlen == 1) /* Not a CRLF after all.  */
211                 sseek (dtp->u.p.current_unit->s, pos);
212               else
213                 crlf = 1;
214             }
215
216           /* Without padding, terminate the I/O statement without assigning
217              the value.  With padding, the value still needs to be assigned,
218              so we can just continue with a short read.  */
219           if (dtp->u.p.current_unit->flags.pad == PAD_NO)
220             {
221               if (no_error)
222                 break;
223               generate_error (&dtp->common, ERROR_EOR, NULL);
224               return NULL;
225             }
226
227           *length = n;
228           dtp->u.p.sf_seen_eor = (crlf ? 2 : 1);
229           break;
230         }
231       /*  Short circuit the read if a comma is found during numeric input.
232           The flag is set to zero during character reads so that commas in
233           strings are not ignored  */
234       if (*q == ',')
235         if (dtp->u.p.sf_read_comma == 1)
236           {
237             notify_std (&dtp->common, GFC_STD_GNU,
238                         "Comma in formatted numeric read.");
239             *length = n;
240             break;
241           }
242
243       n++;
244       *p++ = *q;
245       dtp->u.p.sf_seen_eor = 0;
246     }
247   while (n < *length);
248
249  done:
250   dtp->u.p.current_unit->bytes_left -= *length;
251
252   if ((dtp->common.flags & IOPARM_DT_HAS_SIZE) != 0)
253     dtp->u.p.size_used += (gfc_offset) *length;
254
255   return base;
256 }
257
258
259 /* Function for reading the next couple of bytes from the current
260    file, advancing the current position.  We return a pointer to a
261    buffer containing the bytes.  We return NULL on end of record or
262    end of file.
263
264    If the read is short, then it is because the current record does not
265    have enough data to satisfy the read request and the file was
266    opened with PAD=YES.  The caller must assume tailing spaces for
267    short reads.  */
268
269 void *
270 read_block (st_parameter_dt *dtp, int *length)
271 {
272   char *source;
273   int nread;
274
275   if (is_stream_io (dtp))
276     {
277       if (sseek (dtp->u.p.current_unit->s,
278                  dtp->u.p.current_unit->strm_pos - 1) == FAILURE)
279         {
280           generate_error (&dtp->common, ERROR_END, NULL);
281           return NULL;
282         }
283     }
284   else
285     {
286       if (dtp->u.p.current_unit->bytes_left < (gfc_offset) *length)
287         {
288           /* For preconnected units with default record length, set bytes left
289            to unit record length and proceed, otherwise error.  */
290           if (dtp->u.p.current_unit->unit_number == options.stdin_unit
291               && dtp->u.p.current_unit->recl == DEFAULT_RECL)
292           dtp->u.p.current_unit->bytes_left = dtp->u.p.current_unit->recl;
293           else
294             {
295               if (dtp->u.p.current_unit->flags.pad == PAD_NO)
296                 {
297                   /* Not enough data left.  */
298                   generate_error (&dtp->common, ERROR_EOR, NULL);
299                   return NULL;
300                 }
301             }
302
303           if (dtp->u.p.current_unit->bytes_left == 0)
304             {
305               dtp->u.p.current_unit->endfile = AT_ENDFILE;
306               generate_error (&dtp->common, ERROR_END, NULL);
307               return NULL;
308             }
309
310           *length = dtp->u.p.current_unit->bytes_left;
311         }
312     }
313
314   if (dtp->u.p.current_unit->flags.form == FORM_FORMATTED &&
315       (dtp->u.p.current_unit->flags.access == ACCESS_SEQUENTIAL ||
316        dtp->u.p.current_unit->flags.access == ACCESS_STREAM))
317     {
318       source = read_sf (dtp, length, 0);
319       dtp->u.p.current_unit->strm_pos +=
320         (gfc_offset) (*length + dtp->u.p.sf_seen_eor);
321       return source;
322     }
323   dtp->u.p.current_unit->bytes_left -= (gfc_offset) *length;
324
325   nread = *length;
326   source = salloc_r (dtp->u.p.current_unit->s, &nread);
327
328   if ((dtp->common.flags & IOPARM_DT_HAS_SIZE) != 0)
329     dtp->u.p.size_used += (gfc_offset) nread;
330
331   if (nread != *length)
332     {                           /* Short read, this shouldn't happen.  */
333       if (dtp->u.p.current_unit->flags.pad == PAD_YES)
334         *length = nread;
335       else
336         {
337           generate_error (&dtp->common, ERROR_EOR, NULL);
338           source = NULL;
339         }
340     }
341
342   dtp->u.p.current_unit->strm_pos += (gfc_offset) nread;
343
344   return source;
345 }
346
347
348 /* Reads a block directly into application data space.  This is for
349    unformatted files.  */
350
351 static void
352 read_block_direct (st_parameter_dt *dtp, void *buf, size_t *nbytes)
353 {
354   size_t to_read_record;
355   size_t have_read_record;
356   size_t to_read_subrecord;
357   size_t have_read_subrecord;
358   int short_record;
359
360   if (is_stream_io (dtp))
361     {
362       if (sseek (dtp->u.p.current_unit->s,
363                  dtp->u.p.current_unit->strm_pos - 1) == FAILURE)
364         {
365           generate_error (&dtp->common, ERROR_END, NULL);
366           return;
367         }
368
369       to_read_record = *nbytes;
370       have_read_record = to_read_record;
371       if (sread (dtp->u.p.current_unit->s, buf, &have_read_record) != 0)
372         {
373           generate_error (&dtp->common, ERROR_OS, NULL);
374           return;
375         }
376
377       dtp->u.p.current_unit->strm_pos += (gfc_offset) have_read_record; 
378
379       if (to_read_record != have_read_record)
380         {
381           /* Short read,  e.g. if we hit EOF.  For stream files,
382            we have to set the end-of-file condition.  */
383           generate_error (&dtp->common, ERROR_END, NULL);
384           return;
385         }
386       return;
387     }
388
389   if (dtp->u.p.current_unit->flags.access == ACCESS_DIRECT)
390     {
391       if (dtp->u.p.current_unit->bytes_left < (gfc_offset) *nbytes)
392         {
393           short_record = 1;
394           to_read_record = (size_t) dtp->u.p.current_unit->bytes_left;
395           *nbytes = to_read_record;
396         }
397
398       else
399         {
400           short_record = 0;
401           to_read_record = *nbytes;
402         }
403
404       dtp->u.p.current_unit->bytes_left -= to_read_record;
405
406       if (sread (dtp->u.p.current_unit->s, buf, &to_read_record) != 0)
407         {
408           generate_error (&dtp->common, ERROR_OS, NULL);
409           return;
410         }
411
412       if (to_read_record != *nbytes)  
413         {
414           /* Short read, e.g. if we hit EOF.  Apparently, we read
415            more than was written to the last record.  */
416           *nbytes = to_read_record;
417           return;
418         }
419
420       if (short_record)
421         {
422           generate_error (&dtp->common, ERROR_SHORT_RECORD, NULL);
423           return;
424         }
425       return;
426     }
427
428   /* Unformatted sequential.  We loop over the subrecords, reading
429      until the request has been fulfilled or the record has run out
430      of continuation subrecords.  */
431
432   if (dtp->u.p.current_unit->endfile == AT_ENDFILE)
433     {
434       generate_error (&dtp->common, ERROR_END, NULL);
435       return;
436     }
437
438   /* Check whether we exceed the total record length.  */
439
440   if (dtp->u.p.current_unit->flags.has_recl
441       && (*nbytes > (size_t) dtp->u.p.current_unit->bytes_left))
442     {
443       to_read_record = (size_t) dtp->u.p.current_unit->bytes_left;
444       short_record = 1;
445     }
446   else
447     {
448       to_read_record = *nbytes;
449       short_record = 0;
450     }
451   have_read_record = 0;
452
453   while(1)
454     {
455       if (dtp->u.p.current_unit->bytes_left_subrecord
456           < (gfc_offset) to_read_record)
457         {
458           to_read_subrecord = (size_t) dtp->u.p.current_unit->bytes_left_subrecord;
459           to_read_record -= to_read_subrecord;
460         }
461       else
462         {
463           to_read_subrecord = to_read_record;
464           to_read_record = 0;
465         }
466
467       dtp->u.p.current_unit->bytes_left_subrecord -= to_read_subrecord;
468
469       have_read_subrecord = to_read_subrecord;
470       if (sread (dtp->u.p.current_unit->s, buf + have_read_record,
471                  &have_read_subrecord) != 0)
472         {
473           generate_error (&dtp->common, ERROR_OS, NULL);
474           return;
475         }
476
477       have_read_record += have_read_subrecord;
478
479       if (to_read_subrecord != have_read_subrecord)  
480                         
481         {
482           /* Short read, e.g. if we hit EOF.  This means the record
483              structure has been corrupted, or the trailing record
484              marker would still be present.  */
485
486           *nbytes = have_read_record;
487           generate_error (&dtp->common, ERROR_CORRUPT_FILE, NULL);
488           return;
489         }
490
491       if (to_read_record > 0)
492         {
493           if (dtp->u.p.current_unit->continued)
494             {
495               next_record_r_unf (dtp, 0);
496               us_read (dtp, 1);
497             }
498           else
499             {
500               /* Let's make sure the file position is correctly pre-positioned
501                  for the next read statement.  */
502
503               dtp->u.p.current_unit->current_record = 0;
504               next_record_r_unf (dtp, 0);
505               generate_error (&dtp->common, ERROR_SHORT_RECORD, NULL);
506               return;
507             }
508         }
509       else
510         {
511           /* Normal exit, the read request has been fulfilled.  */
512           break;
513         }
514     }
515
516   dtp->u.p.current_unit->bytes_left -= have_read_record;
517   if (short_record)
518     {
519       generate_error (&dtp->common, ERROR_SHORT_RECORD, NULL);
520       return;
521     }
522   return;
523 }
524
525
526 /* Function for writing a block of bytes to the current file at the
527    current position, advancing the file pointer. We are given a length
528    and return a pointer to a buffer that the caller must (completely)
529    fill in.  Returns NULL on error.  */
530
531 void *
532 write_block (st_parameter_dt *dtp, int length)
533 {
534   char *dest;
535
536   if (is_stream_io (dtp))
537     {
538       if (sseek (dtp->u.p.current_unit->s,
539                  dtp->u.p.current_unit->strm_pos - 1) == FAILURE)
540         {
541           generate_error (&dtp->common, ERROR_OS, NULL);
542           return NULL;
543         }
544     }
545   else
546     {
547       if (dtp->u.p.current_unit->bytes_left < (gfc_offset) length)
548         {
549           /* For preconnected units with default record length, set bytes left
550              to unit record length and proceed, otherwise error.  */
551           if ((dtp->u.p.current_unit->unit_number == options.stdout_unit
552                 || dtp->u.p.current_unit->unit_number == options.stderr_unit)
553                 && dtp->u.p.current_unit->recl == DEFAULT_RECL)
554             dtp->u.p.current_unit->bytes_left = dtp->u.p.current_unit->recl;
555           else
556             {
557               generate_error (&dtp->common, ERROR_EOR, NULL);
558               return NULL;
559             }
560         }
561
562       dtp->u.p.current_unit->bytes_left -= (gfc_offset) length;
563     }
564
565   dest = salloc_w (dtp->u.p.current_unit->s, &length);
566
567   if (dest == NULL)
568     {
569       generate_error (&dtp->common, ERROR_END, NULL);
570       return NULL;
571     }
572
573   if (is_internal_unit (dtp) && dtp->u.p.current_unit->endfile == AT_ENDFILE)
574     generate_error (&dtp->common, ERROR_END, NULL);
575
576   if ((dtp->common.flags & IOPARM_DT_HAS_SIZE) != 0)
577     dtp->u.p.size_used += (gfc_offset) length;
578
579   dtp->u.p.current_unit->strm_pos += (gfc_offset) length;
580
581   return dest;
582 }
583
584
585 /* High level interface to swrite(), taking care of errors.  This is only
586    called for unformatted files.  There are three cases to consider:
587    Stream I/O, unformatted direct, unformatted sequential.  */
588
589 static try
590 write_buf (st_parameter_dt *dtp, void *buf, size_t nbytes)
591 {
592
593   size_t have_written, to_write_subrecord;
594   int short_record;
595
596
597   /* Stream I/O.  */
598
599   if (is_stream_io (dtp))
600     {
601       if (sseek (dtp->u.p.current_unit->s,
602                  dtp->u.p.current_unit->strm_pos - 1) == FAILURE)
603         {
604           generate_error (&dtp->common, ERROR_OS, NULL);
605           return FAILURE;
606         }
607
608       if (swrite (dtp->u.p.current_unit->s, buf, &nbytes) != 0)
609         {
610           generate_error (&dtp->common, ERROR_OS, NULL);
611           return FAILURE;
612         }
613
614       dtp->u.p.current_unit->strm_pos += (gfc_offset) nbytes; 
615
616       return SUCCESS;
617     }
618
619   /* Unformatted direct access.  */
620
621   if (dtp->u.p.current_unit->flags.access == ACCESS_DIRECT)
622     {
623       if (dtp->u.p.current_unit->bytes_left < (gfc_offset) nbytes)
624         {
625           generate_error (&dtp->common, ERROR_DIRECT_EOR, NULL);
626           return FAILURE;
627         }
628
629       if (swrite (dtp->u.p.current_unit->s, buf, &nbytes) != 0)
630         {
631           generate_error (&dtp->common, ERROR_OS, NULL);
632           return FAILURE;
633         }
634
635       dtp->u.p.current_unit->strm_pos += (gfc_offset) nbytes;
636       dtp->u.p.current_unit->bytes_left -= (gfc_offset) nbytes;
637
638       return SUCCESS;
639
640     }
641
642   /* Unformatted sequential.  */
643
644   have_written = 0;
645
646   if (dtp->u.p.current_unit->flags.has_recl
647       && (gfc_offset) nbytes > dtp->u.p.current_unit->bytes_left)
648     {
649       nbytes = dtp->u.p.current_unit->bytes_left;
650       short_record = 1;
651     }
652   else
653     {
654       short_record = 0;
655     }
656
657   while (1)
658     {
659
660       to_write_subrecord =
661         (size_t) dtp->u.p.current_unit->bytes_left_subrecord < nbytes ?
662         (size_t) dtp->u.p.current_unit->bytes_left_subrecord : nbytes;
663
664       dtp->u.p.current_unit->bytes_left_subrecord -=
665         (gfc_offset) to_write_subrecord;
666
667       if (swrite (dtp->u.p.current_unit->s, buf + have_written,
668                   &to_write_subrecord) != 0)
669         {
670           generate_error (&dtp->common, ERROR_OS, NULL);
671           return FAILURE;
672         }
673
674       dtp->u.p.current_unit->strm_pos += (gfc_offset) to_write_subrecord; 
675       nbytes -= to_write_subrecord;
676       have_written += to_write_subrecord;
677
678       if (nbytes == 0)
679         break;
680
681       next_record_w_unf (dtp, 1);
682       us_write (dtp, 1);
683     }
684   dtp->u.p.current_unit->bytes_left -= have_written;
685   if (short_record)
686     {
687       generate_error (&dtp->common, ERROR_SHORT_RECORD, NULL);
688       return FAILURE;
689     }
690   return SUCCESS;
691 }
692
693
694 /* Master function for unformatted reads.  */
695
696 static void
697 unformatted_read (st_parameter_dt *dtp, bt type,
698                   void *dest, int kind __attribute__((unused)),
699                   size_t size, size_t nelems)
700 {
701   size_t i, sz;
702
703   /* Currently, character implies size=1.  */
704   if (dtp->u.p.current_unit->flags.convert == CONVERT_NATIVE
705       || size == 1 || type == BT_CHARACTER)
706     {
707       sz = size * nelems;
708       read_block_direct (dtp, dest, &sz);
709     }
710   else
711     {
712       char buffer[16];
713       char *p;
714       
715       /* Break up complex into its constituent reals.  */
716       if (type == BT_COMPLEX)
717         {
718           nelems *= 2;
719           size /= 2;
720         }
721       p = dest;
722       
723       /* By now, all complex variables have been split into their
724          constituent reals.  */
725       
726       for (i=0; i<nelems; i++)
727         {
728           read_block_direct (dtp, buffer, &size);
729           reverse_memcpy (p, buffer, size);
730           p += size;
731         }
732     }
733 }
734
735
736 /* Master function for unformatted writes.  NOTE: For kind=10 the size is 16
737    bytes on 64 bit machines.  The unused bytes are not initialized and never
738    used, which can show an error with memory checking analyzers like
739    valgrind.  */
740
741 static void
742 unformatted_write (st_parameter_dt *dtp, bt type,
743                    void *source, int kind __attribute__((unused)),
744                    size_t size, size_t nelems)
745 {
746   if (dtp->u.p.current_unit->flags.convert == CONVERT_NATIVE ||
747       size == 1 || type == BT_CHARACTER)
748     {
749       size *= nelems;
750       write_buf (dtp, source, size);
751     }
752   else
753     {
754       char buffer[16];
755       char *p;
756       size_t i;
757   
758       /* Break up complex into its constituent reals.  */
759       if (type == BT_COMPLEX)
760         {
761           nelems *= 2;
762           size /= 2;
763         }      
764
765       p = source;
766
767       /* By now, all complex variables have been split into their
768          constituent reals.  */
769
770
771       for (i=0; i<nelems; i++)
772         {
773           reverse_memcpy(buffer, p, size);
774           p+= size;
775           write_buf (dtp, buffer, size);
776         }
777     }
778 }
779
780
781 /* Return a pointer to the name of a type.  */
782
783 const char *
784 type_name (bt type)
785 {
786   const char *p;
787
788   switch (type)
789     {
790     case BT_INTEGER:
791       p = "INTEGER";
792       break;
793     case BT_LOGICAL:
794       p = "LOGICAL";
795       break;
796     case BT_CHARACTER:
797       p = "CHARACTER";
798       break;
799     case BT_REAL:
800       p = "REAL";
801       break;
802     case BT_COMPLEX:
803       p = "COMPLEX";
804       break;
805     default:
806       internal_error (NULL, "type_name(): Bad type");
807     }
808
809   return p;
810 }
811
812
813 /* Write a constant string to the output.
814    This is complicated because the string can have doubled delimiters
815    in it.  The length in the format node is the true length.  */
816
817 static void
818 write_constant_string (st_parameter_dt *dtp, const fnode *f)
819 {
820   char c, delimiter, *p, *q;
821   int length;
822
823   length = f->u.string.length;
824   if (length == 0)
825     return;
826
827   p = write_block (dtp, length);
828   if (p == NULL)
829     return;
830
831   q = f->u.string.p;
832   delimiter = q[-1];
833
834   for (; length > 0; length--)
835     {
836       c = *p++ = *q++;
837       if (c == delimiter && c != 'H' && c != 'h')
838         q++;                    /* Skip the doubled delimiter.  */
839     }
840 }
841
842
843 /* Given actual and expected types in a formatted data transfer, make
844    sure they agree.  If not, an error message is generated.  Returns
845    nonzero if something went wrong.  */
846
847 static int
848 require_type (st_parameter_dt *dtp, bt expected, bt actual, const fnode *f)
849 {
850   char buffer[100];
851
852   if (actual == expected)
853     return 0;
854
855   st_sprintf (buffer, "Expected %s for item %d in formatted transfer, got %s",
856               type_name (expected), dtp->u.p.item_count, type_name (actual));
857
858   format_error (dtp, f, buffer);
859   return 1;
860 }
861
862
863 /* This subroutine is the main loop for a formatted data transfer
864    statement.  It would be natural to implement this as a coroutine
865    with the user program, but C makes that awkward.  We loop,
866    processing format elements.  When we actually have to transfer
867    data instead of just setting flags, we return control to the user
868    program which calls a subroutine that supplies the address and type
869    of the next element, then comes back here to process it.  */
870
871 static void
872 formatted_transfer_scalar (st_parameter_dt *dtp, bt type, void *p, int len,
873                            size_t size)
874 {
875   char scratch[SCRATCH_SIZE];
876   int pos, bytes_used;
877   const fnode *f;
878   format_token t;
879   int n;
880   int consume_data_flag;
881
882   /* Change a complex data item into a pair of reals.  */
883
884   n = (p == NULL) ? 0 : ((type != BT_COMPLEX) ? 1 : 2);
885   if (type == BT_COMPLEX)
886     {
887       type = BT_REAL;
888       size /= 2;
889     }
890
891   /* If there's an EOR condition, we simulate finalizing the transfer
892      by doing nothing.  */
893   if (dtp->u.p.eor_condition)
894     return;
895
896   /* Set this flag so that commas in reads cause the read to complete before
897      the entire field has been read.  The next read field will start right after
898      the comma in the stream.  (Set to 0 for character reads).  */
899   dtp->u.p.sf_read_comma = 1;
900
901   dtp->u.p.line_buffer = scratch;
902   for (;;)
903     {
904       /* If reversion has occurred and there is another real data item,
905          then we have to move to the next record.  */
906       if (dtp->u.p.reversion_flag && n > 0)
907         {
908           dtp->u.p.reversion_flag = 0;
909           next_record (dtp, 0);
910         }
911
912       consume_data_flag = 1 ;
913       if ((dtp->common.flags & IOPARM_LIBRETURN_MASK) != IOPARM_LIBRETURN_OK)
914         break;
915
916       f = next_format (dtp);
917       if (f == NULL)
918         {
919           /* No data descriptors left.  */
920           if (n > 0)
921             generate_error (&dtp->common, ERROR_FORMAT,
922                 "Insufficient data descriptors in format after reversion");
923           return;
924         }
925
926       /* Now discharge T, TR and X movements to the right.  This is delayed
927          until a data producing format to suppress trailing spaces.  */
928          
929       t = f->format;
930       if (dtp->u.p.mode == WRITING && dtp->u.p.skips != 0
931         && ((n>0 && (  t == FMT_I  || t == FMT_B  || t == FMT_O
932                     || t == FMT_Z  || t == FMT_F  || t == FMT_E
933                     || t == FMT_EN || t == FMT_ES || t == FMT_G
934                     || t == FMT_L  || t == FMT_A  || t == FMT_D))
935             || t == FMT_STRING))
936         {
937           if (dtp->u.p.skips > 0)
938             {
939               write_x (dtp, dtp->u.p.skips, dtp->u.p.pending_spaces);
940               dtp->u.p.max_pos = (int)(dtp->u.p.current_unit->recl
941                                        - dtp->u.p.current_unit->bytes_left);
942             }
943           if (dtp->u.p.skips < 0)
944             {
945               move_pos_offset (dtp->u.p.current_unit->s, dtp->u.p.skips);
946               dtp->u.p.current_unit->bytes_left -= (gfc_offset) dtp->u.p.skips;
947             }
948           dtp->u.p.skips = dtp->u.p.pending_spaces = 0;
949         }
950
951       bytes_used = (int)(dtp->u.p.current_unit->recl
952                    - dtp->u.p.current_unit->bytes_left);
953
954       if (is_stream_io(dtp))
955         bytes_used = 0;
956
957       switch (t)
958         {
959         case FMT_I:
960           if (n == 0)
961             goto need_data;
962           if (require_type (dtp, BT_INTEGER, type, f))
963             return;
964
965           if (dtp->u.p.mode == READING)
966             read_decimal (dtp, f, p, len);
967           else
968             write_i (dtp, f, p, len);
969
970           break;
971
972         case FMT_B:
973           if (n == 0)
974             goto need_data;
975
976           if (compile_options.allow_std < GFC_STD_GNU
977               && require_type (dtp, BT_INTEGER, type, f))
978             return;
979
980           if (dtp->u.p.mode == READING)
981             read_radix (dtp, f, p, len, 2);
982           else
983             write_b (dtp, f, p, len);
984
985           break;
986
987         case FMT_O:
988           if (n == 0)
989             goto need_data; 
990
991           if (compile_options.allow_std < GFC_STD_GNU
992               && require_type (dtp, BT_INTEGER, type, f))
993             return;
994
995           if (dtp->u.p.mode == READING)
996             read_radix (dtp, f, p, len, 8);
997           else
998             write_o (dtp, f, p, len);
999
1000           break;
1001
1002         case FMT_Z:
1003           if (n == 0)
1004             goto need_data;
1005
1006           if (compile_options.allow_std < GFC_STD_GNU
1007               && require_type (dtp, BT_INTEGER, type, f))
1008             return;
1009
1010           if (dtp->u.p.mode == READING)
1011             read_radix (dtp, f, p, len, 16);
1012           else
1013             write_z (dtp, f, p, len);
1014
1015           break;
1016
1017         case FMT_A:
1018           if (n == 0)
1019             goto need_data;
1020
1021           if (dtp->u.p.mode == READING)
1022             read_a (dtp, f, p, len);
1023           else
1024             write_a (dtp, f, p, len);
1025
1026           break;
1027
1028         case FMT_L:
1029           if (n == 0)
1030             goto need_data;
1031
1032           if (dtp->u.p.mode == READING)
1033             read_l (dtp, f, p, len);
1034           else
1035             write_l (dtp, f, p, len);
1036
1037           break;
1038
1039         case FMT_D:
1040           if (n == 0)
1041             goto need_data;
1042           if (require_type (dtp, BT_REAL, type, f))
1043             return;
1044
1045           if (dtp->u.p.mode == READING)
1046             read_f (dtp, f, p, len);
1047           else
1048             write_d (dtp, f, p, len);
1049
1050           break;
1051
1052         case FMT_E:
1053           if (n == 0)
1054             goto need_data;
1055           if (require_type (dtp, BT_REAL, type, f))
1056             return;
1057
1058           if (dtp->u.p.mode == READING)
1059             read_f (dtp, f, p, len);
1060           else
1061             write_e (dtp, f, p, len);
1062           break;
1063
1064         case FMT_EN:
1065           if (n == 0)
1066             goto need_data;
1067           if (require_type (dtp, BT_REAL, type, f))
1068             return;
1069
1070           if (dtp->u.p.mode == READING)
1071             read_f (dtp, f, p, len);
1072           else
1073             write_en (dtp, f, p, len);
1074
1075           break;
1076
1077         case FMT_ES:
1078           if (n == 0)
1079             goto need_data;
1080           if (require_type (dtp, BT_REAL, type, f))
1081             return;
1082
1083           if (dtp->u.p.mode == READING)
1084             read_f (dtp, f, p, len);
1085           else
1086             write_es (dtp, f, p, len);
1087
1088           break;
1089
1090         case FMT_F:
1091           if (n == 0)
1092             goto need_data;
1093           if (require_type (dtp, BT_REAL, type, f))
1094             return;
1095
1096           if (dtp->u.p.mode == READING)
1097             read_f (dtp, f, p, len);
1098           else
1099             write_f (dtp, f, p, len);
1100
1101           break;
1102
1103         case FMT_G:
1104           if (n == 0)
1105             goto need_data;
1106           if (dtp->u.p.mode == READING)
1107             switch (type)
1108               {
1109               case BT_INTEGER:
1110                 read_decimal (dtp, f, p, len);
1111                 break;
1112               case BT_LOGICAL:
1113                 read_l (dtp, f, p, len);
1114                 break;
1115               case BT_CHARACTER:
1116                 read_a (dtp, f, p, len);
1117                 break;
1118               case BT_REAL:
1119                 read_f (dtp, f, p, len);
1120                 break;
1121               default:
1122                 goto bad_type;
1123               }
1124           else
1125             switch (type)
1126               {
1127               case BT_INTEGER:
1128                 write_i (dtp, f, p, len);
1129                 break;
1130               case BT_LOGICAL:
1131                 write_l (dtp, f, p, len);
1132                 break;
1133               case BT_CHARACTER:
1134                 write_a (dtp, f, p, len);
1135                 break;
1136               case BT_REAL:
1137                 write_d (dtp, f, p, len);
1138                 break;
1139               default:
1140               bad_type:
1141                 internal_error (&dtp->common,
1142                                 "formatted_transfer(): Bad type");
1143               }
1144
1145           break;
1146
1147         case FMT_STRING:
1148           consume_data_flag = 0 ;
1149           if (dtp->u.p.mode == READING)
1150             {
1151               format_error (dtp, f, "Constant string in input format");
1152               return;
1153             }
1154           write_constant_string (dtp, f);
1155           break;
1156
1157         /* Format codes that don't transfer data.  */
1158         case FMT_X:
1159         case FMT_TR:
1160           consume_data_flag = 0;
1161
1162           dtp->u.p.skips += f->u.n;
1163           pos = bytes_used + dtp->u.p.skips - 1;
1164           dtp->u.p.pending_spaces = pos - dtp->u.p.max_pos + 1;
1165
1166           /* Writes occur just before the switch on f->format, above, so
1167              that trailing blanks are suppressed, unless we are doing a
1168              non-advancing write in which case we want to output the blanks
1169              now.  */
1170           if (dtp->u.p.mode == WRITING
1171               && dtp->u.p.advance_status == ADVANCE_NO)
1172             {
1173               write_x (dtp, dtp->u.p.skips, dtp->u.p.pending_spaces);
1174               dtp->u.p.skips = dtp->u.p.pending_spaces = 0;
1175             }
1176
1177           if (dtp->u.p.mode == READING)
1178             read_x (dtp, f->u.n);
1179
1180           break;
1181
1182         case FMT_TL:
1183         case FMT_T:
1184           consume_data_flag = 0;
1185
1186           if (f->format == FMT_TL)
1187             {
1188
1189               /* Handle the special case when no bytes have been used yet.
1190                  Cannot go below zero. */
1191               if (bytes_used == 0)
1192                 {
1193                   dtp->u.p.pending_spaces -= f->u.n;
1194                   dtp->u.p.skips -= f->u.n;
1195                   dtp->u.p.skips = dtp->u.p.skips < 0 ? 0 : dtp->u.p.skips;
1196                 }
1197
1198               pos = bytes_used - f->u.n;
1199             }
1200           else /* FMT_T */
1201             {
1202               if (dtp->u.p.mode == READING)
1203                 pos = f->u.n - 1;
1204               else
1205                 pos = f->u.n - dtp->u.p.pending_spaces - 1;
1206             }
1207
1208           /* Standard 10.6.1.1: excessive left tabbing is reset to the
1209              left tab limit.  We do not check if the position has gone
1210              beyond the end of record because a subsequent tab could
1211              bring us back again.  */
1212           pos = pos < 0 ? 0 : pos;
1213
1214           dtp->u.p.skips = dtp->u.p.skips + pos - bytes_used;
1215           dtp->u.p.pending_spaces = dtp->u.p.pending_spaces
1216                                     + pos - dtp->u.p.max_pos;
1217           dtp->u.p.pending_spaces = dtp->u.p.pending_spaces < 0
1218                                     ? 0 : dtp->u.p.pending_spaces;
1219
1220           if (dtp->u.p.skips == 0)
1221             break;
1222
1223           /* Writes occur just before the switch on f->format, above, so that
1224              trailing blanks are suppressed.  */
1225           if (dtp->u.p.mode == READING)
1226             {
1227               /* Adjust everything for end-of-record condition */
1228               if (dtp->u.p.sf_seen_eor && !is_internal_unit (dtp))
1229                 {
1230                   if (dtp->u.p.sf_seen_eor == 2)
1231                     {
1232                       /* The EOR was a CRLF (two bytes wide).  */
1233                       dtp->u.p.current_unit->bytes_left -= 2;
1234                       dtp->u.p.skips -= 2;
1235                     }
1236                   else
1237                     {
1238                       /* The EOR marker was only one byte wide.  */
1239                       dtp->u.p.current_unit->bytes_left--;
1240                       dtp->u.p.skips--;
1241                     }
1242                   bytes_used = pos;
1243                   dtp->u.p.sf_seen_eor = 0;
1244                 }
1245               if (dtp->u.p.skips < 0)
1246                 {
1247                   move_pos_offset (dtp->u.p.current_unit->s, dtp->u.p.skips);
1248                   dtp->u.p.current_unit->bytes_left
1249                     -= (gfc_offset) dtp->u.p.skips;
1250                   dtp->u.p.skips = dtp->u.p.pending_spaces = 0;
1251                 }
1252               else
1253                 read_x (dtp, dtp->u.p.skips);
1254             }
1255
1256           break;
1257
1258         case FMT_S:
1259           consume_data_flag = 0 ;
1260           dtp->u.p.sign_status = SIGN_S;
1261           break;
1262
1263         case FMT_SS:
1264           consume_data_flag = 0 ;
1265           dtp->u.p.sign_status = SIGN_SS;
1266           break;
1267
1268         case FMT_SP:
1269           consume_data_flag = 0 ;
1270           dtp->u.p.sign_status = SIGN_SP;
1271           break;
1272
1273         case FMT_BN:
1274           consume_data_flag = 0 ;
1275           dtp->u.p.blank_status = BLANK_NULL;
1276           break;
1277
1278         case FMT_BZ:
1279           consume_data_flag = 0 ;
1280           dtp->u.p.blank_status = BLANK_ZERO;
1281           break;
1282
1283         case FMT_P:
1284           consume_data_flag = 0 ;
1285           dtp->u.p.scale_factor = f->u.k;
1286           break;
1287
1288         case FMT_DOLLAR:
1289           consume_data_flag = 0 ;
1290           dtp->u.p.seen_dollar = 1;
1291           break;
1292
1293         case FMT_SLASH:
1294           consume_data_flag = 0 ;
1295           dtp->u.p.skips = dtp->u.p.pending_spaces = 0;
1296           next_record (dtp, 0);
1297           break;
1298
1299         case FMT_COLON:
1300           /* A colon descriptor causes us to exit this loop (in
1301              particular preventing another / descriptor from being
1302              processed) unless there is another data item to be
1303              transferred.  */
1304           consume_data_flag = 0 ;
1305           if (n == 0)
1306             return;
1307           break;
1308
1309         default:
1310           internal_error (&dtp->common, "Bad format node");
1311         }
1312
1313       /* Free a buffer that we had to allocate during a sequential
1314          formatted read of a block that was larger than the static
1315          buffer.  */
1316
1317       if (dtp->u.p.line_buffer != scratch)
1318         {
1319           free_mem (dtp->u.p.line_buffer);
1320           dtp->u.p.line_buffer = scratch;
1321         }
1322
1323       /* Adjust the item count and data pointer.  */
1324
1325       if ((consume_data_flag > 0) && (n > 0))
1326       {
1327         n--;
1328         p = ((char *) p) + size;
1329       }
1330
1331       if (dtp->u.p.mode == READING)
1332         dtp->u.p.skips = 0;
1333
1334       pos = (int)(dtp->u.p.current_unit->recl - dtp->u.p.current_unit->bytes_left);
1335       dtp->u.p.max_pos = (dtp->u.p.max_pos > pos) ? dtp->u.p.max_pos : pos;
1336
1337     }
1338
1339   return;
1340
1341   /* Come here when we need a data descriptor but don't have one.  We
1342      push the current format node back onto the input, then return and
1343      let the user program call us back with the data.  */
1344  need_data:
1345   unget_format (dtp, f);
1346 }
1347
1348 static void
1349 formatted_transfer (st_parameter_dt *dtp, bt type, void *p, int kind,
1350                     size_t size, size_t nelems)
1351 {
1352   size_t elem;
1353   char *tmp;
1354
1355   tmp = (char *) p;
1356
1357   /* Big loop over all the elements.  */
1358   for (elem = 0; elem < nelems; elem++)
1359     {
1360       dtp->u.p.item_count++;
1361       formatted_transfer_scalar (dtp, type, tmp + size*elem, kind, size);
1362     }
1363 }
1364
1365
1366
1367 /* Data transfer entry points.  The type of the data entity is
1368    implicit in the subroutine call.  This prevents us from having to
1369    share a common enum with the compiler.  */
1370
1371 void
1372 transfer_integer (st_parameter_dt *dtp, void *p, int kind)
1373 {
1374   if ((dtp->common.flags & IOPARM_LIBRETURN_MASK) != IOPARM_LIBRETURN_OK)
1375     return;
1376   dtp->u.p.transfer (dtp, BT_INTEGER, p, kind, kind, 1);
1377 }
1378
1379
1380 void
1381 transfer_real (st_parameter_dt *dtp, void *p, int kind)
1382 {
1383   size_t size;
1384   if ((dtp->common.flags & IOPARM_LIBRETURN_MASK) != IOPARM_LIBRETURN_OK)
1385     return;
1386   size = size_from_real_kind (kind);
1387   dtp->u.p.transfer (dtp, BT_REAL, p, kind, size, 1);
1388 }
1389
1390
1391 void
1392 transfer_logical (st_parameter_dt *dtp, void *p, int kind)
1393 {
1394   if ((dtp->common.flags & IOPARM_LIBRETURN_MASK) != IOPARM_LIBRETURN_OK)
1395     return;
1396   dtp->u.p.transfer (dtp, BT_LOGICAL, p, kind, kind, 1);
1397 }
1398
1399
1400 void
1401 transfer_character (st_parameter_dt *dtp, void *p, int len)
1402 {
1403   static char *empty_string[0];
1404
1405   if ((dtp->common.flags & IOPARM_LIBRETURN_MASK) != IOPARM_LIBRETURN_OK)
1406     return;
1407
1408   /* Strings of zero length can have p == NULL, which confuses the
1409      transfer routines into thinking we need more data elements.  To avoid
1410      this, we give them a nice pointer.  */
1411   if (len == 0 && p == NULL)
1412     p = empty_string;
1413
1414   /* Currently we support only 1 byte chars, and the library is a bit
1415      confused of character kind vs. length, so we kludge it by setting
1416      kind = length.  */
1417   dtp->u.p.transfer (dtp, BT_CHARACTER, p, len, len, 1);
1418 }
1419
1420
1421 void
1422 transfer_complex (st_parameter_dt *dtp, void *p, int kind)
1423 {
1424   size_t size;
1425   if ((dtp->common.flags & IOPARM_LIBRETURN_MASK) != IOPARM_LIBRETURN_OK)
1426     return;
1427   size = size_from_complex_kind (kind);
1428   dtp->u.p.transfer (dtp, BT_COMPLEX, p, kind, size, 1);
1429 }
1430
1431
1432 void
1433 transfer_array (st_parameter_dt *dtp, gfc_array_char *desc, int kind,
1434                 gfc_charlen_type charlen)
1435 {
1436   index_type count[GFC_MAX_DIMENSIONS];
1437   index_type extent[GFC_MAX_DIMENSIONS];
1438   index_type stride[GFC_MAX_DIMENSIONS];
1439   index_type stride0, rank, size, type, n;
1440   size_t tsize;
1441   char *data;
1442   bt iotype;
1443
1444   if ((dtp->common.flags & IOPARM_LIBRETURN_MASK) != IOPARM_LIBRETURN_OK)
1445     return;
1446
1447   type = GFC_DESCRIPTOR_TYPE (desc);
1448   size = GFC_DESCRIPTOR_SIZE (desc);
1449
1450   /* FIXME: What a kludge: Array descriptors and the IO library use
1451      different enums for types.  */
1452   switch (type)
1453     {
1454     case GFC_DTYPE_UNKNOWN:
1455       iotype = BT_NULL;  /* Is this correct?  */
1456       break;
1457     case GFC_DTYPE_INTEGER:
1458       iotype = BT_INTEGER;
1459       break;
1460     case GFC_DTYPE_LOGICAL:
1461       iotype = BT_LOGICAL;
1462       break;
1463     case GFC_DTYPE_REAL:
1464       iotype = BT_REAL;
1465       break;
1466     case GFC_DTYPE_COMPLEX:
1467       iotype = BT_COMPLEX;
1468       break;
1469     case GFC_DTYPE_CHARACTER:
1470       iotype = BT_CHARACTER;
1471       /* FIXME: Currently dtype contains the charlen, which is
1472          clobbered if charlen > 2**24. That's why we use a separate
1473          argument for the charlen. However, if we want to support
1474          non-8-bit charsets we need to fix dtype to contain
1475          sizeof(chartype) and fix the code below.  */
1476       size = charlen;
1477       kind = charlen;
1478       break;
1479     case GFC_DTYPE_DERIVED:
1480       internal_error (&dtp->common,
1481                 "Derived type I/O should have been handled via the frontend.");
1482       break;
1483     default:
1484       internal_error (&dtp->common, "transfer_array(): Bad type");
1485     }
1486
1487   rank = GFC_DESCRIPTOR_RANK (desc);
1488   for (n = 0; n < rank; n++)
1489     {
1490       count[n] = 0;
1491       stride[n] = desc->dim[n].stride;
1492       extent[n] = desc->dim[n].ubound + 1 - desc->dim[n].lbound;
1493
1494       /* If the extent of even one dimension is zero, then the entire
1495          array section contains zero elements, so we return.  */
1496       if (extent[n] <= 0)
1497         return;
1498     }
1499
1500   stride0 = stride[0];
1501
1502   /* If the innermost dimension has stride 1, we can do the transfer
1503      in contiguous chunks.  */
1504   if (stride0 == 1)
1505     tsize = extent[0];
1506   else
1507     tsize = 1;
1508
1509   data = GFC_DESCRIPTOR_DATA (desc);
1510
1511   while (data)
1512     {
1513       dtp->u.p.transfer (dtp, iotype, data, kind, size, tsize);
1514       data += stride0 * size * tsize;
1515       count[0] += tsize;
1516       n = 0;
1517       while (count[n] == extent[n])
1518         {
1519           count[n] = 0;
1520           data -= stride[n] * extent[n] * size;
1521           n++;
1522           if (n == rank)
1523             {
1524               data = NULL;
1525               break;
1526             }
1527           else
1528             {
1529               count[n]++;
1530               data += stride[n] * size;
1531             }
1532         }
1533     }
1534 }
1535
1536
1537 /* Preposition a sequential unformatted file while reading.  */
1538
1539 static void
1540 us_read (st_parameter_dt *dtp, int continued)
1541 {
1542   char *p;
1543   int n;
1544   int nr;
1545   GFC_INTEGER_4 i4;
1546   GFC_INTEGER_8 i8;
1547   gfc_offset i;
1548
1549   if (dtp->u.p.current_unit->endfile == AT_ENDFILE)
1550     return;
1551
1552   if (compile_options.record_marker == 0)
1553     n = sizeof (GFC_INTEGER_4);
1554   else
1555     n = compile_options.record_marker;
1556
1557   nr = n;
1558
1559   p = salloc_r (dtp->u.p.current_unit->s, &n);
1560
1561   if (n == 0)
1562     {
1563       dtp->u.p.current_unit->endfile = AT_ENDFILE;
1564       return;  /* end of file */
1565     }
1566
1567   if (p == NULL || n != nr)
1568     {
1569       generate_error (&dtp->common, ERROR_BAD_US, NULL);
1570       return;
1571     }
1572
1573   /* Only CONVERT_NATIVE and CONVERT_SWAP are valid here.  */
1574   if (dtp->u.p.current_unit->flags.convert == CONVERT_NATIVE)
1575     {
1576       switch (nr)
1577         {
1578         case sizeof(GFC_INTEGER_4):
1579           memcpy (&i4, p, sizeof (i4));
1580           i = i4;
1581           break;
1582
1583         case sizeof(GFC_INTEGER_8):
1584           memcpy (&i8, p, sizeof (i8));
1585           i = i8;
1586           break;
1587
1588         default:
1589           runtime_error ("Illegal value for record marker");
1590           break;
1591         }
1592     }
1593   else
1594       switch (nr)
1595         {
1596         case sizeof(GFC_INTEGER_4):
1597           reverse_memcpy (&i4, p, sizeof (i4));
1598           i = i4;
1599           break;
1600
1601         case sizeof(GFC_INTEGER_8):
1602           reverse_memcpy (&i8, p, sizeof (i8));
1603           i = i8;
1604           break;
1605
1606         default:
1607           runtime_error ("Illegal value for record marker");
1608           break;
1609         }
1610
1611   if (i >= 0)
1612     {
1613       dtp->u.p.current_unit->bytes_left_subrecord = i;
1614       dtp->u.p.current_unit->continued = 0;
1615     }
1616   else
1617     {
1618       dtp->u.p.current_unit->bytes_left_subrecord = -i;
1619       dtp->u.p.current_unit->continued = 1;
1620     }
1621
1622   if (! continued)
1623     dtp->u.p.current_unit->bytes_left = dtp->u.p.current_unit->recl;
1624 }
1625
1626
1627 /* Preposition a sequential unformatted file while writing.  This
1628    amount to writing a bogus length that will be filled in later.  */
1629
1630 static void
1631 us_write (st_parameter_dt *dtp, int continued)
1632 {
1633   size_t nbytes;
1634   gfc_offset dummy;
1635
1636   dummy = 0;
1637
1638   if (compile_options.record_marker == 0)
1639     nbytes = sizeof (GFC_INTEGER_4);
1640   else
1641     nbytes = compile_options.record_marker ;
1642
1643   if (swrite (dtp->u.p.current_unit->s, &dummy, &nbytes) != 0)
1644     generate_error (&dtp->common, ERROR_OS, NULL);
1645
1646   /* For sequential unformatted, if RECL= was not specified in the OPEN
1647      we write until we have more bytes than can fit in the subrecord
1648      markers, then we write a new subrecord.  */
1649
1650   dtp->u.p.current_unit->bytes_left_subrecord =
1651     dtp->u.p.current_unit->recl_subrecord;
1652   dtp->u.p.current_unit->continued = continued;
1653 }
1654
1655
1656 /* Position to the next record prior to transfer.  We are assumed to
1657    be before the next record.  We also calculate the bytes in the next
1658    record.  */
1659
1660 static void
1661 pre_position (st_parameter_dt *dtp)
1662 {
1663   if (dtp->u.p.current_unit->current_record)
1664     return;                     /* Already positioned.  */
1665
1666   switch (current_mode (dtp))
1667     {
1668     case FORMATTED_STREAM:
1669     case UNFORMATTED_STREAM:
1670       /* There are no records with stream I/O.  Set the default position
1671          to the beginning of the file if no position was specified.  */
1672       if ((dtp->common.flags & IOPARM_DT_HAS_REC) == 0)
1673         dtp->u.p.current_unit->strm_pos = 1;
1674       break;
1675     
1676     case UNFORMATTED_SEQUENTIAL:
1677       if (dtp->u.p.mode == READING)
1678         us_read (dtp, 0);
1679       else
1680         us_write (dtp, 0);
1681
1682       break;
1683
1684     case FORMATTED_SEQUENTIAL:
1685     case FORMATTED_DIRECT:
1686     case UNFORMATTED_DIRECT:
1687       dtp->u.p.current_unit->bytes_left = dtp->u.p.current_unit->recl;
1688       break;
1689     }
1690
1691   dtp->u.p.current_unit->current_record = 1;
1692 }
1693
1694
1695 /* Initialize things for a data transfer.  This code is common for
1696    both reading and writing.  */
1697
1698 static void
1699 data_transfer_init (st_parameter_dt *dtp, int read_flag)
1700 {
1701   unit_flags u_flags;  /* Used for creating a unit if needed.  */
1702   GFC_INTEGER_4 cf = dtp->common.flags;
1703   namelist_info *ionml;
1704
1705   ionml = ((cf & IOPARM_DT_IONML_SET) != 0) ? dtp->u.p.ionml : NULL;
1706   memset (&dtp->u.p, 0, sizeof (dtp->u.p));
1707   dtp->u.p.ionml = ionml;
1708   dtp->u.p.mode = read_flag ? READING : WRITING;
1709
1710   if ((dtp->common.flags & IOPARM_LIBRETURN_MASK) != IOPARM_LIBRETURN_OK)
1711     return;
1712
1713   if ((cf & IOPARM_DT_HAS_SIZE) != 0)
1714     dtp->u.p.size_used = 0;  /* Initialize the count.  */
1715
1716   dtp->u.p.current_unit = get_unit (dtp, 1);
1717   if (dtp->u.p.current_unit->s == NULL)
1718   {  /* Open the unit with some default flags.  */
1719      st_parameter_open opp;
1720      unit_convert conv;
1721
1722      if (dtp->common.unit < 0)
1723      {
1724        close_unit (dtp->u.p.current_unit);
1725        dtp->u.p.current_unit = NULL;
1726        generate_error (&dtp->common, ERROR_BAD_OPTION,
1727                        "Bad unit number in OPEN statement");
1728        return;
1729      }
1730      memset (&u_flags, '\0', sizeof (u_flags));
1731      u_flags.access = ACCESS_SEQUENTIAL;
1732      u_flags.action = ACTION_READWRITE;
1733
1734      /* Is it unformatted?  */
1735      if (!(cf & (IOPARM_DT_HAS_FORMAT | IOPARM_DT_LIST_FORMAT
1736                  | IOPARM_DT_IONML_SET)))
1737        u_flags.form = FORM_UNFORMATTED;
1738      else
1739        u_flags.form = FORM_UNSPECIFIED;
1740
1741      u_flags.delim = DELIM_UNSPECIFIED;
1742      u_flags.blank = BLANK_UNSPECIFIED;
1743      u_flags.pad = PAD_UNSPECIFIED;
1744      u_flags.status = STATUS_UNKNOWN;
1745
1746      conv = get_unformatted_convert (dtp->common.unit);
1747
1748      if (conv == CONVERT_NONE)
1749        conv = compile_options.convert;
1750
1751      /* We use l8_to_l4_offset, which is 0 on little-endian machines
1752         and 1 on big-endian machines.  */
1753      switch (conv)
1754        {
1755        case CONVERT_NATIVE:
1756        case CONVERT_SWAP:
1757          break;
1758          
1759        case CONVERT_BIG:
1760          conv = l8_to_l4_offset ? CONVERT_NATIVE : CONVERT_SWAP;
1761          break;
1762       
1763        case CONVERT_LITTLE:
1764          conv = l8_to_l4_offset ? CONVERT_SWAP : CONVERT_NATIVE;
1765          break;
1766          
1767        default:
1768          internal_error (&opp.common, "Illegal value for CONVERT");
1769          break;
1770        }
1771
1772      u_flags.convert = conv;
1773
1774      opp.common = dtp->common;
1775      opp.common.flags &= IOPARM_COMMON_MASK;
1776      dtp->u.p.current_unit = new_unit (&opp, dtp->u.p.current_unit, &u_flags);
1777      dtp->common.flags &= ~IOPARM_COMMON_MASK;
1778      dtp->common.flags |= (opp.common.flags & IOPARM_COMMON_MASK);
1779      if (dtp->u.p.current_unit == NULL)
1780        return;
1781   }
1782
1783   /* Check the action.  */
1784
1785   if (read_flag && dtp->u.p.current_unit->flags.action == ACTION_WRITE)
1786     {
1787       generate_error (&dtp->common, ERROR_BAD_ACTION,
1788                       "Cannot read from file opened for WRITE");
1789       return;
1790     }
1791
1792   if (!read_flag && dtp->u.p.current_unit->flags.action == ACTION_READ)
1793     {
1794       generate_error (&dtp->common, ERROR_BAD_ACTION,
1795                       "Cannot write to file opened for READ");
1796       return;
1797     }
1798
1799   dtp->u.p.first_item = 1;
1800
1801   /* Check the format.  */
1802
1803   if ((cf & IOPARM_DT_HAS_FORMAT) != 0)
1804     parse_format (dtp);
1805
1806   if (dtp->u.p.current_unit->flags.form == FORM_UNFORMATTED
1807       && (cf & (IOPARM_DT_HAS_FORMAT | IOPARM_DT_LIST_FORMAT))
1808          != 0)
1809     {
1810       generate_error (&dtp->common, ERROR_OPTION_CONFLICT,
1811                       "Format present for UNFORMATTED data transfer");
1812       return;
1813     }
1814
1815   if ((cf & IOPARM_DT_HAS_NAMELIST_NAME) != 0 && dtp->u.p.ionml != NULL)
1816      {
1817         if ((cf & IOPARM_DT_HAS_FORMAT) != 0)
1818            generate_error (&dtp->common, ERROR_OPTION_CONFLICT,
1819                     "A format cannot be specified with a namelist");
1820      }
1821   else if (dtp->u.p.current_unit->flags.form == FORM_FORMATTED &&
1822            !(cf & (IOPARM_DT_HAS_FORMAT | IOPARM_DT_LIST_FORMAT)))
1823     {
1824       generate_error (&dtp->common, ERROR_OPTION_CONFLICT,
1825                       "Missing format for FORMATTED data transfer");
1826     }
1827
1828   if (is_internal_unit (dtp)
1829       && dtp->u.p.current_unit->flags.form == FORM_UNFORMATTED)
1830     {
1831       generate_error (&dtp->common, ERROR_OPTION_CONFLICT,
1832                       "Internal file cannot be accessed by UNFORMATTED "
1833                       "data transfer");
1834       return;
1835     }
1836
1837   /* Check the record or position number.  */
1838
1839   if (dtp->u.p.current_unit->flags.access == ACCESS_DIRECT
1840       && (cf & IOPARM_DT_HAS_REC) == 0)
1841     {
1842       generate_error (&dtp->common, ERROR_MISSING_OPTION,
1843                       "Direct access data transfer requires record number");
1844       return;
1845     }
1846
1847   if (dtp->u.p.current_unit->flags.access == ACCESS_SEQUENTIAL
1848       && (cf & IOPARM_DT_HAS_REC) != 0)
1849     {
1850       generate_error (&dtp->common, ERROR_OPTION_CONFLICT,
1851                       "Record number not allowed for sequential access data transfer");
1852       return;
1853     }
1854
1855   /* Process the ADVANCE option.  */
1856
1857   dtp->u.p.advance_status
1858     = !(cf & IOPARM_DT_HAS_ADVANCE) ? ADVANCE_UNSPECIFIED :
1859       find_option (&dtp->common, dtp->advance, dtp->advance_len, advance_opt,
1860                    "Bad ADVANCE parameter in data transfer statement");
1861
1862   if (dtp->u.p.advance_status != ADVANCE_UNSPECIFIED)
1863     {
1864       if (dtp->u.p.current_unit->flags.access == ACCESS_DIRECT)
1865         {
1866           generate_error (&dtp->common, ERROR_OPTION_CONFLICT,
1867                           "ADVANCE specification conflicts with sequential access");
1868           return;
1869         }
1870
1871       if (is_internal_unit (dtp))
1872         {
1873           generate_error (&dtp->common, ERROR_OPTION_CONFLICT,
1874                           "ADVANCE specification conflicts with internal file");
1875           return;
1876         }
1877
1878       if ((cf & (IOPARM_DT_HAS_FORMAT | IOPARM_DT_LIST_FORMAT))
1879           != IOPARM_DT_HAS_FORMAT)
1880         {
1881           generate_error (&dtp->common, ERROR_OPTION_CONFLICT,
1882                           "ADVANCE specification requires an explicit format");
1883           return;
1884         }
1885     }
1886
1887   if (read_flag)
1888     {
1889       if ((cf & IOPARM_EOR) != 0 && dtp->u.p.advance_status != ADVANCE_NO)
1890         {
1891           generate_error (&dtp->common, ERROR_MISSING_OPTION,
1892                           "EOR specification requires an ADVANCE specification "
1893                           "of NO");
1894           return;
1895         }
1896
1897       if ((cf & IOPARM_DT_HAS_SIZE) != 0 && dtp->u.p.advance_status != ADVANCE_NO)
1898         {
1899           generate_error (&dtp->common, ERROR_MISSING_OPTION,
1900                           "SIZE specification requires an ADVANCE specification of NO");
1901           return;
1902         }
1903     }
1904   else
1905     {                           /* Write constraints.  */
1906       if ((cf & IOPARM_END) != 0)
1907         {
1908           generate_error (&dtp->common, ERROR_OPTION_CONFLICT,
1909                           "END specification cannot appear in a write statement");
1910           return;
1911         }
1912
1913       if ((cf & IOPARM_EOR) != 0)
1914         {
1915           generate_error (&dtp->common, ERROR_OPTION_CONFLICT,
1916                           "EOR specification cannot appear in a write statement");
1917           return;
1918         }
1919
1920       if ((cf & IOPARM_DT_HAS_SIZE) != 0)
1921         {
1922           generate_error (&dtp->common, ERROR_OPTION_CONFLICT,
1923                           "SIZE specification cannot appear in a write statement");
1924           return;
1925         }
1926     }
1927
1928   if (dtp->u.p.advance_status == ADVANCE_UNSPECIFIED)
1929     dtp->u.p.advance_status = ADVANCE_YES;
1930
1931   /* Sanity checks on the record number.  */
1932   if ((cf & IOPARM_DT_HAS_REC) != 0)
1933     {
1934       if (dtp->rec <= 0)
1935         {
1936           generate_error (&dtp->common, ERROR_BAD_OPTION,
1937                           "Record number must be positive");
1938           return;
1939         }
1940
1941       if (dtp->rec >= dtp->u.p.current_unit->maxrec)
1942         {
1943           generate_error (&dtp->common, ERROR_BAD_OPTION,
1944                           "Record number too large");
1945           return;
1946         }
1947
1948       /* Check to see if we might be reading what we wrote before  */
1949
1950       if (dtp->u.p.mode == READING
1951           && dtp->u.p.current_unit->mode == WRITING
1952           && !is_internal_unit (dtp))
1953          flush(dtp->u.p.current_unit->s);
1954
1955       /* Check whether the record exists to be read.  Only
1956          a partial record needs to exist.  */
1957
1958       if (dtp->u.p.mode == READING && (dtp->rec -1)
1959           * dtp->u.p.current_unit->recl >= file_length (dtp->u.p.current_unit->s))
1960         {
1961           generate_error (&dtp->common, ERROR_BAD_OPTION,
1962                           "Non-existing record number");
1963           return;
1964         }
1965
1966       /* Position the file.  */
1967       if (!is_stream_io (dtp))
1968         {
1969           if (sseek (dtp->u.p.current_unit->s, (gfc_offset) (dtp->rec - 1)
1970                      * dtp->u.p.current_unit->recl) == FAILURE)
1971             {
1972               generate_error (&dtp->common, ERROR_OS, NULL);
1973               return;
1974             }
1975         }
1976       else
1977         dtp->u.p.current_unit->strm_pos = dtp->rec;
1978
1979     }
1980
1981   /* Overwriting an existing sequential file ?
1982      it is always safe to truncate the file on the first write */
1983   if (dtp->u.p.mode == WRITING
1984       && dtp->u.p.current_unit->flags.access == ACCESS_SEQUENTIAL
1985       && dtp->u.p.current_unit->last_record == 0 
1986       && !is_preconnected(dtp->u.p.current_unit->s))
1987         struncate(dtp->u.p.current_unit->s);
1988
1989   /* Bugware for badly written mixed C-Fortran I/O.  */
1990   flush_if_preconnected(dtp->u.p.current_unit->s);
1991
1992   dtp->u.p.current_unit->mode = dtp->u.p.mode;
1993
1994   /* Set the initial value of flags.  */
1995
1996   dtp->u.p.blank_status = dtp->u.p.current_unit->flags.blank;
1997   dtp->u.p.sign_status = SIGN_S;
1998   
1999   /* Set the maximum position reached from the previous I/O operation.  This
2000      could be greater than zero from a previous non-advancing write.  */
2001   dtp->u.p.max_pos = dtp->u.p.current_unit->saved_pos;
2002
2003   pre_position (dtp);
2004
2005   /* Set up the subroutine that will handle the transfers.  */
2006
2007   if (read_flag)
2008     {
2009       if (dtp->u.p.current_unit->flags.form == FORM_UNFORMATTED)
2010         dtp->u.p.transfer = unformatted_read;
2011       else
2012         {
2013           if ((cf & IOPARM_DT_LIST_FORMAT) != 0)
2014             dtp->u.p.transfer = list_formatted_read;
2015           else
2016             dtp->u.p.transfer = formatted_transfer;
2017         }
2018     }
2019   else
2020     {
2021       if (dtp->u.p.current_unit->flags.form == FORM_UNFORMATTED)
2022         dtp->u.p.transfer = unformatted_write;
2023       else
2024         {
2025           if ((cf & IOPARM_DT_LIST_FORMAT) != 0)
2026             dtp->u.p.transfer = list_formatted_write;
2027           else
2028             dtp->u.p.transfer = formatted_transfer;
2029         }
2030     }
2031
2032   /* Make sure that we don't do a read after a nonadvancing write.  */
2033
2034   if (read_flag)
2035     {
2036       if (dtp->u.p.current_unit->read_bad && !is_stream_io (dtp))
2037         {
2038           generate_error (&dtp->common, ERROR_BAD_OPTION,
2039                           "Cannot READ after a nonadvancing WRITE");
2040           return;
2041         }
2042     }
2043   else
2044     {
2045       if (dtp->u.p.advance_status == ADVANCE_YES && !dtp->u.p.seen_dollar)
2046         dtp->u.p.current_unit->read_bad = 1;
2047     }
2048
2049   /* Start the data transfer if we are doing a formatted transfer.  */
2050   if (dtp->u.p.current_unit->flags.form == FORM_FORMATTED
2051       && ((cf & (IOPARM_DT_LIST_FORMAT | IOPARM_DT_HAS_NAMELIST_NAME)) == 0)
2052       && dtp->u.p.ionml == NULL)
2053     formatted_transfer (dtp, 0, NULL, 0, 0, 1);
2054 }
2055
2056 /* Initialize an array_loop_spec given the array descriptor.  The function
2057    returns the index of the last element of the array.  */
2058    
2059 gfc_offset
2060 init_loop_spec (gfc_array_char *desc, array_loop_spec *ls)
2061 {
2062   int rank = GFC_DESCRIPTOR_RANK(desc);
2063   int i;
2064   gfc_offset index; 
2065
2066   index = 1;
2067   for (i=0; i<rank; i++)
2068     {
2069       ls[i].idx = desc->dim[i].lbound;
2070       ls[i].start = desc->dim[i].lbound;
2071       ls[i].end = desc->dim[i].ubound;
2072       ls[i].step = desc->dim[i].stride;
2073       
2074       index += (desc->dim[i].ubound - desc->dim[i].lbound)
2075                       * desc->dim[i].stride;
2076     }
2077   return index;
2078 }
2079
2080 /* Determine the index to the next record in an internal unit array by
2081    by incrementing through the array_loop_spec.  TODO:  Implement handling
2082    negative strides. */
2083    
2084 gfc_offset
2085 next_array_record (st_parameter_dt *dtp, array_loop_spec *ls)
2086 {
2087   int i, carry;
2088   gfc_offset index;
2089   
2090   carry = 1;
2091   index = 0;
2092   
2093   for (i = 0; i < dtp->u.p.current_unit->rank; i++)
2094     {
2095       if (carry)
2096         {
2097           ls[i].idx++;
2098           if (ls[i].idx > ls[i].end)
2099             {
2100               ls[i].idx = ls[i].start;
2101               carry = 1;
2102             }
2103           else
2104             carry = 0;
2105         }
2106       index = index + (ls[i].idx - ls[i].start) * ls[i].step;
2107     }
2108
2109   return index;
2110 }
2111
2112
2113
2114 /* Skip to the end of the current record, taking care of an optional
2115    record marker of size bytes.  If the file is not seekable, we
2116    read chunks of size MAX_READ until we get to the right
2117    position.  */
2118
2119 #define MAX_READ 4096
2120
2121 static void
2122 skip_record (st_parameter_dt *dtp, size_t bytes)
2123 {
2124   gfc_offset new;
2125   int rlength, length;
2126   char *p;
2127
2128   dtp->u.p.current_unit->bytes_left_subrecord += bytes;
2129   if (dtp->u.p.current_unit->bytes_left_subrecord == 0)
2130     return;
2131
2132   if (is_seekable (dtp->u.p.current_unit->s))
2133     {
2134       new = file_position (dtp->u.p.current_unit->s)
2135         + dtp->u.p.current_unit->bytes_left_subrecord;
2136
2137       /* Direct access files do not generate END conditions,
2138          only I/O errors.  */
2139       if (sseek (dtp->u.p.current_unit->s, new) == FAILURE)
2140         generate_error (&dtp->common, ERROR_OS, NULL);
2141     }
2142   else
2143     {                   /* Seek by reading data.  */
2144       while (dtp->u.p.current_unit->bytes_left_subrecord > 0)
2145         {
2146           rlength = length =
2147             (MAX_READ > dtp->u.p.current_unit->bytes_left_subrecord) ?
2148             MAX_READ : dtp->u.p.current_unit->bytes_left_subrecord;
2149
2150           p = salloc_r (dtp->u.p.current_unit->s, &rlength);
2151           if (p == NULL)
2152             {
2153               generate_error (&dtp->common, ERROR_OS, NULL);
2154               return;
2155             }
2156
2157           dtp->u.p.current_unit->bytes_left_subrecord -= length;
2158         }
2159     }
2160
2161 }
2162
2163 #undef MAX_READ
2164
2165 /* Advance to the next record reading unformatted files, taking
2166    care of subrecords.  If complete_record is nonzero, we loop
2167    until all subrecords are cleared.  */
2168
2169 static void
2170 next_record_r_unf (st_parameter_dt *dtp, int complete_record)
2171 {
2172   size_t bytes;
2173
2174   bytes =  compile_options.record_marker == 0 ?
2175     sizeof (GFC_INTEGER_4) : compile_options.record_marker;
2176
2177   while(1)
2178     {
2179
2180       /* Skip over tail */
2181
2182       skip_record (dtp, bytes);
2183
2184       if ( ! (complete_record && dtp->u.p.current_unit->continued))
2185         return;
2186
2187       us_read (dtp, 1);
2188     }
2189 }
2190
2191 /* Space to the next record for read mode.  */
2192
2193 static void
2194 next_record_r (st_parameter_dt *dtp)
2195 {
2196   gfc_offset record;
2197   int length, bytes_left;
2198   char *p;
2199
2200   switch (current_mode (dtp))
2201     {
2202     /* No records in unformatted STREAM I/O.  */
2203     case UNFORMATTED_STREAM:
2204       return;
2205     
2206     case UNFORMATTED_SEQUENTIAL:
2207       next_record_r_unf (dtp, 1);
2208       dtp->u.p.current_unit->bytes_left = dtp->u.p.current_unit->recl;
2209       break;
2210
2211     case FORMATTED_DIRECT:
2212     case UNFORMATTED_DIRECT:
2213       skip_record (dtp, 0);
2214       break;
2215
2216     case FORMATTED_STREAM:
2217     case FORMATTED_SEQUENTIAL:
2218       length = 1;
2219       /* sf_read has already terminated input because of an '\n'  */
2220       if (dtp->u.p.sf_seen_eor)
2221         {
2222           dtp->u.p.sf_seen_eor = 0;
2223           break;
2224         }
2225
2226       if (is_internal_unit (dtp))
2227         {
2228           if (is_array_io (dtp))
2229             {
2230               record = next_array_record (dtp, dtp->u.p.current_unit->ls);
2231
2232               /* Now seek to this record.  */
2233               record = record * dtp->u.p.current_unit->recl;
2234               if (sseek (dtp->u.p.current_unit->s, record) == FAILURE)
2235                 {
2236                   generate_error (&dtp->common, ERROR_INTERNAL_UNIT, NULL);
2237                   break;
2238                 }
2239               dtp->u.p.current_unit->bytes_left = dtp->u.p.current_unit->recl;
2240             }
2241           else  
2242             {
2243               bytes_left = (int) dtp->u.p.current_unit->bytes_left;
2244               p = salloc_r (dtp->u.p.current_unit->s, &bytes_left);
2245               if (p != NULL)
2246                 dtp->u.p.current_unit->bytes_left
2247                   = dtp->u.p.current_unit->recl;
2248             } 
2249           break;
2250         }
2251       else do
2252         {
2253           p = salloc_r (dtp->u.p.current_unit->s, &length);
2254
2255           if (p == NULL)
2256             {
2257               generate_error (&dtp->common, ERROR_OS, NULL);
2258               break;
2259             }
2260
2261           if (length == 0)
2262             {
2263               dtp->u.p.current_unit->endfile = AT_ENDFILE;
2264               break;
2265             }
2266
2267           if (is_stream_io (dtp))
2268             dtp->u.p.current_unit->strm_pos++;
2269         }
2270       while (*p != '\n');
2271
2272       break;
2273     }
2274
2275   if (dtp->u.p.current_unit->flags.access == ACCESS_SEQUENTIAL
2276       && !dtp->u.p.namelist_mode
2277       && dtp->u.p.current_unit->endfile == NO_ENDFILE
2278       && (file_length (dtp->u.p.current_unit->s) ==
2279          file_position (dtp->u.p.current_unit->s)))
2280     dtp->u.p.current_unit->endfile = AT_ENDFILE;
2281
2282 }
2283
2284
2285 /* Small utility function to write a record marker, taking care of
2286    byte swapping and of choosing the correct size.  */
2287
2288 inline static int
2289 write_us_marker (st_parameter_dt *dtp, const gfc_offset buf)
2290 {
2291   size_t len;
2292   GFC_INTEGER_4 buf4;
2293   GFC_INTEGER_8 buf8;
2294   char p[sizeof (GFC_INTEGER_8)];
2295
2296   if (compile_options.record_marker == 0)
2297     len = sizeof (GFC_INTEGER_4);
2298   else
2299     len = compile_options.record_marker;
2300
2301   /* Only CONVERT_NATIVE and CONVERT_SWAP are valid here.  */
2302   if (dtp->u.p.current_unit->flags.convert == CONVERT_NATIVE)
2303     {
2304       switch (len)
2305         {
2306         case sizeof (GFC_INTEGER_4):
2307           buf4 = buf;
2308           return swrite (dtp->u.p.current_unit->s, &buf4, &len);
2309           break;
2310
2311         case sizeof (GFC_INTEGER_8):
2312           buf8 = buf;
2313           return swrite (dtp->u.p.current_unit->s, &buf8, &len);
2314           break;
2315
2316         default:
2317           runtime_error ("Illegal value for record marker");
2318           break;
2319         }
2320     }
2321   else
2322     {
2323       switch (len)
2324         {
2325         case sizeof (GFC_INTEGER_4):
2326           buf4 = buf;
2327           reverse_memcpy (p, &buf4, sizeof (GFC_INTEGER_4));
2328           return swrite (dtp->u.p.current_unit->s, p, &len);
2329           break;
2330
2331         case sizeof (GFC_INTEGER_8):
2332           buf8 = buf;
2333           reverse_memcpy (p, &buf8, sizeof (GFC_INTEGER_8));
2334           return swrite (dtp->u.p.current_unit->s, p, &len);
2335           break;
2336
2337         default:
2338           runtime_error ("Illegal value for record marker");
2339           break;
2340         }
2341     }
2342
2343 }
2344
2345 /* Position to the next (sub)record in write mode for
2346    unformatted sequential files.  */
2347
2348 static void
2349 next_record_w_unf (st_parameter_dt *dtp, int next_subrecord)
2350 {
2351   gfc_offset c, m, m_write;
2352   size_t record_marker;
2353
2354   /* Bytes written.  */
2355   m = dtp->u.p.current_unit->recl_subrecord
2356     - dtp->u.p.current_unit->bytes_left_subrecord;
2357   c = file_position (dtp->u.p.current_unit->s);
2358
2359   /* Write the length tail.  If we finish a record containing
2360      subrecords, we write out the negative length.  */
2361
2362   if (dtp->u.p.current_unit->continued)
2363     m_write = -m;
2364   else
2365     m_write = m;
2366
2367   if (write_us_marker (dtp, m_write) != 0)
2368     goto io_error;
2369
2370   if (compile_options.record_marker == 0)
2371     record_marker = sizeof (GFC_INTEGER_4);
2372   else
2373     record_marker = compile_options.record_marker;
2374
2375   /* Seek to the head and overwrite the bogus length with the real
2376      length.  */
2377
2378   if (sseek (dtp->u.p.current_unit->s, c - m - record_marker)
2379       == FAILURE)
2380     goto io_error;
2381
2382   if (next_subrecord)
2383     m_write = -m;
2384   else
2385     m_write = m;
2386
2387   if (write_us_marker (dtp, m_write) != 0)
2388     goto io_error;
2389
2390   /* Seek past the end of the current record.  */
2391
2392   if (sseek (dtp->u.p.current_unit->s, c + record_marker) == FAILURE)
2393     goto io_error;
2394
2395   return;
2396
2397  io_error:
2398   generate_error (&dtp->common, ERROR_OS, NULL);
2399   return;
2400
2401 }
2402
2403 /* Position to the next record in write mode.  */
2404
2405 static void
2406 next_record_w (st_parameter_dt *dtp, int done)
2407 {
2408   gfc_offset m, record, max_pos;
2409   int length;
2410   char *p;
2411
2412   /* Zero counters for X- and T-editing.  */
2413   max_pos = dtp->u.p.max_pos;
2414   dtp->u.p.max_pos = dtp->u.p.skips = dtp->u.p.pending_spaces = 0;
2415
2416   switch (current_mode (dtp))
2417     {
2418     /* No records in unformatted STREAM I/O.  */
2419     case UNFORMATTED_STREAM:
2420       return;
2421
2422     case FORMATTED_DIRECT:
2423       if (dtp->u.p.current_unit->bytes_left == 0)
2424         break;
2425
2426       if (sset (dtp->u.p.current_unit->s, ' ', 
2427                 dtp->u.p.current_unit->bytes_left) == FAILURE)
2428         goto io_error;
2429
2430       break;
2431
2432     case UNFORMATTED_DIRECT:
2433       if (sfree (dtp->u.p.current_unit->s) == FAILURE)
2434         goto io_error;
2435       break;
2436
2437     case UNFORMATTED_SEQUENTIAL:
2438       next_record_w_unf (dtp, 0);
2439       dtp->u.p.current_unit->bytes_left = dtp->u.p.current_unit->recl;
2440       break;
2441
2442     case FORMATTED_STREAM:
2443     case FORMATTED_SEQUENTIAL:
2444
2445       if (is_internal_unit (dtp))
2446         {
2447           if (is_array_io (dtp))
2448             {
2449               length = (int) dtp->u.p.current_unit->bytes_left;
2450               
2451               /* If the farthest position reached is greater than current
2452               position, adjust the position and set length to pad out
2453               whats left.  Otherwise just pad whats left.
2454               (for character array unit) */
2455               m = dtp->u.p.current_unit->recl
2456                         - dtp->u.p.current_unit->bytes_left;
2457               if (max_pos > m)
2458                 {
2459                   length = (int) (max_pos - m);
2460                   p = salloc_w (dtp->u.p.current_unit->s, &length);
2461                   length = (int) (dtp->u.p.current_unit->recl - max_pos);
2462                 }
2463
2464               if (sset (dtp->u.p.current_unit->s, ' ', length) == FAILURE)
2465                 {
2466                   generate_error (&dtp->common, ERROR_END, NULL);
2467                   return;
2468                 }
2469
2470               /* Now that the current record has been padded out,
2471                  determine where the next record in the array is. */
2472               record = next_array_record (dtp, dtp->u.p.current_unit->ls);
2473               if (record == 0)
2474                 dtp->u.p.current_unit->endfile = AT_ENDFILE;
2475               
2476               /* Now seek to this record */
2477               record = record * dtp->u.p.current_unit->recl;
2478
2479               if (sseek (dtp->u.p.current_unit->s, record) == FAILURE)
2480                 {
2481                   generate_error (&dtp->common, ERROR_INTERNAL_UNIT, NULL);
2482                   return;
2483                 }
2484
2485               dtp->u.p.current_unit->bytes_left = dtp->u.p.current_unit->recl;
2486             }
2487           else
2488             {
2489               length = 1;
2490
2491               /* If this is the last call to next_record move to the farthest
2492                  position reached and set length to pad out the remainder
2493                  of the record. (for character scaler unit) */
2494               if (done)
2495                 {
2496                   m = dtp->u.p.current_unit->recl
2497                         - dtp->u.p.current_unit->bytes_left;
2498                   if (max_pos > m)
2499                     {
2500                       length = (int) (max_pos - m);
2501                       p = salloc_w (dtp->u.p.current_unit->s, &length);
2502                       length = (int) (dtp->u.p.current_unit->recl - max_pos);
2503                     }
2504                   else
2505                     length = (int) dtp->u.p.current_unit->bytes_left;
2506                 }
2507
2508               if (sset (dtp->u.p.current_unit->s, ' ', length) == FAILURE)
2509                 {
2510                   generate_error (&dtp->common, ERROR_END, NULL);
2511                   return;
2512                 }
2513             }
2514         }
2515       else
2516         {
2517           /* If this is the last call to next_record move to the farthest
2518           position reached in preparation for completing the record.
2519           (for file unit) */
2520           if (done)
2521             {
2522               m = dtp->u.p.current_unit->recl -
2523                         dtp->u.p.current_unit->bytes_left;
2524               if (max_pos > m)
2525                 {
2526                   length = (int) (max_pos - m);
2527                   p = salloc_w (dtp->u.p.current_unit->s, &length);
2528                 }
2529             }
2530           size_t len;
2531           const char crlf[] = "\r\n";
2532 #ifdef HAVE_CRLF
2533           len = 2;
2534 #else
2535           len = 1;
2536 #endif
2537           if (swrite (dtp->u.p.current_unit->s, &crlf[2-len], &len) != 0)
2538             goto io_error;
2539           
2540           if (is_stream_io (dtp))
2541             dtp->u.p.current_unit->strm_pos += len;
2542         }
2543
2544       break;
2545
2546     io_error:
2547       generate_error (&dtp->common, ERROR_OS, NULL);
2548       break;
2549     }
2550 }
2551
2552 /* Position to the next record, which means moving to the end of the
2553    current record.  This can happen under several different
2554    conditions.  If the done flag is not set, we get ready to process
2555    the next record.  */
2556
2557 void
2558 next_record (st_parameter_dt *dtp, int done)
2559 {
2560   gfc_offset fp; /* File position.  */
2561
2562   dtp->u.p.current_unit->read_bad = 0;
2563
2564   if (dtp->u.p.mode == READING)
2565     next_record_r (dtp);
2566   else
2567     next_record_w (dtp, done);
2568
2569   if (!is_stream_io (dtp))
2570     {
2571       /* Keep position up to date for INQUIRE */
2572       if (done)
2573         update_position (dtp->u.p.current_unit);
2574
2575       dtp->u.p.current_unit->current_record = 0;
2576       if (dtp->u.p.current_unit->flags.access == ACCESS_DIRECT)
2577         {
2578           fp = file_position (dtp->u.p.current_unit->s);
2579           /* Calculate next record, rounding up partial records.  */
2580           dtp->u.p.current_unit->last_record =
2581             (fp + dtp->u.p.current_unit->recl - 1) /
2582               dtp->u.p.current_unit->recl;
2583         }
2584       else
2585         dtp->u.p.current_unit->last_record++;
2586     }
2587
2588   if (!done)
2589     pre_position (dtp);
2590 }
2591
2592
2593 /* Finalize the current data transfer.  For a nonadvancing transfer,
2594    this means advancing to the next record.  For internal units close the
2595    stream associated with the unit.  */
2596
2597 static void
2598 finalize_transfer (st_parameter_dt *dtp)
2599 {
2600   jmp_buf eof_jump;
2601   GFC_INTEGER_4 cf = dtp->common.flags;
2602
2603   if ((dtp->common.flags & IOPARM_DT_HAS_SIZE) != 0)
2604     *dtp->size = (GFC_IO_INT) dtp->u.p.size_used;
2605
2606   if (dtp->u.p.eor_condition)
2607     {
2608       generate_error (&dtp->common, ERROR_EOR, NULL);
2609       return;
2610     }
2611
2612   if ((dtp->common.flags & IOPARM_LIBRETURN_MASK) != IOPARM_LIBRETURN_OK)
2613     return;
2614
2615   if ((dtp->u.p.ionml != NULL)
2616       && (cf & IOPARM_DT_HAS_NAMELIST_NAME) != 0)
2617     {
2618        if ((cf & IOPARM_DT_NAMELIST_READ_MODE) != 0)
2619          namelist_read (dtp);
2620        else
2621          namelist_write (dtp);
2622     }
2623
2624   dtp->u.p.transfer = NULL;
2625   if (dtp->u.p.current_unit == NULL)
2626     return;
2627
2628   dtp->u.p.eof_jump = &eof_jump;
2629   if (setjmp (eof_jump))
2630     {
2631       generate_error (&dtp->common, ERROR_END, NULL);
2632       return;
2633     }
2634
2635   if ((cf & IOPARM_DT_LIST_FORMAT) != 0 && dtp->u.p.mode == READING)
2636     {
2637       finish_list_read (dtp);
2638       sfree (dtp->u.p.current_unit->s);
2639       return;
2640     }
2641
2642   if (is_stream_io (dtp))
2643     {
2644       if (dtp->u.p.current_unit->flags.form == FORM_FORMATTED)
2645         next_record (dtp, 1);
2646       flush (dtp->u.p.current_unit->s);
2647       sfree (dtp->u.p.current_unit->s);
2648       return;
2649     }
2650
2651   dtp->u.p.current_unit->current_record = 0;
2652
2653   if (!is_internal_unit (dtp) && dtp->u.p.seen_dollar)
2654     {
2655       dtp->u.p.seen_dollar = 0;
2656       sfree (dtp->u.p.current_unit->s);
2657       return;
2658     }
2659
2660   /* For non-advancing I/O, save the current maximum position for use in the
2661      next I/O operation if needed.  */
2662   if (dtp->u.p.advance_status == ADVANCE_NO)
2663     {
2664       int bytes_written = (int) (dtp->u.p.current_unit->recl
2665         - dtp->u.p.current_unit->bytes_left);
2666       dtp->u.p.current_unit->saved_pos =
2667         dtp->u.p.max_pos > 0 ? dtp->u.p.max_pos - bytes_written : 0;
2668       flush (dtp->u.p.current_unit->s);
2669       return;
2670     }
2671
2672   dtp->u.p.current_unit->saved_pos = 0;
2673
2674   next_record (dtp, 1);
2675   sfree (dtp->u.p.current_unit->s);
2676 }
2677
2678 /* Transfer function for IOLENGTH. It doesn't actually do any
2679    data transfer, it just updates the length counter.  */
2680
2681 static void
2682 iolength_transfer (st_parameter_dt *dtp, bt type __attribute__((unused)), 
2683                    void *dest __attribute__ ((unused)),
2684                    int kind __attribute__((unused)), 
2685                    size_t size, size_t nelems)
2686 {
2687   if ((dtp->common.flags & IOPARM_DT_HAS_IOLENGTH) != 0)
2688     *dtp->iolength += (GFC_IO_INT) size * nelems;
2689 }
2690
2691
2692 /* Initialize the IOLENGTH data transfer. This function is in essence
2693    a very much simplified version of data_transfer_init(), because it
2694    doesn't have to deal with units at all.  */
2695
2696 static void
2697 iolength_transfer_init (st_parameter_dt *dtp)
2698 {
2699   if ((dtp->common.flags & IOPARM_DT_HAS_IOLENGTH) != 0)
2700     *dtp->iolength = 0;
2701
2702   memset (&dtp->u.p, 0, sizeof (dtp->u.p));
2703
2704   /* Set up the subroutine that will handle the transfers.  */
2705
2706   dtp->u.p.transfer = iolength_transfer;
2707 }
2708
2709
2710 /* Library entry point for the IOLENGTH form of the INQUIRE
2711    statement. The IOLENGTH form requires no I/O to be performed, but
2712    it must still be a runtime library call so that we can determine
2713    the iolength for dynamic arrays and such.  */
2714
2715 extern void st_iolength (st_parameter_dt *);
2716 export_proto(st_iolength);
2717
2718 void
2719 st_iolength (st_parameter_dt *dtp)
2720 {
2721   library_start (&dtp->common);
2722   iolength_transfer_init (dtp);
2723 }
2724
2725 extern void st_iolength_done (st_parameter_dt *);
2726 export_proto(st_iolength_done);
2727
2728 void
2729 st_iolength_done (st_parameter_dt *dtp __attribute__((unused)))
2730 {
2731   free_ionml (dtp);
2732   if (dtp->u.p.scratch != NULL)
2733     free_mem (dtp->u.p.scratch);
2734   library_end ();
2735 }
2736
2737
2738 /* The READ statement.  */
2739
2740 extern void st_read (st_parameter_dt *);
2741 export_proto(st_read);
2742
2743 void
2744 st_read (st_parameter_dt *dtp)
2745 {
2746   library_start (&dtp->common);
2747
2748   data_transfer_init (dtp, 1);
2749
2750   /* Handle complications dealing with the endfile record.  */
2751
2752   if (dtp->u.p.current_unit->flags.access == ACCESS_SEQUENTIAL)
2753     switch (dtp->u.p.current_unit->endfile)
2754       {
2755       case NO_ENDFILE:
2756         break;
2757
2758       case AT_ENDFILE:
2759         if (!is_internal_unit (dtp))
2760           {
2761             generate_error (&dtp->common, ERROR_END, NULL);
2762             dtp->u.p.current_unit->endfile = AFTER_ENDFILE;
2763             dtp->u.p.current_unit->current_record = 0;
2764           }
2765         break;
2766
2767       case AFTER_ENDFILE:
2768         generate_error (&dtp->common, ERROR_ENDFILE, NULL);
2769         dtp->u.p.current_unit->current_record = 0;
2770         break;
2771       }
2772 }
2773
2774 extern void st_read_done (st_parameter_dt *);
2775 export_proto(st_read_done);
2776
2777 void
2778 st_read_done (st_parameter_dt *dtp)
2779 {
2780   finalize_transfer (dtp);
2781   free_format_data (dtp);
2782   free_ionml (dtp);
2783   if (dtp->u.p.scratch != NULL)
2784     free_mem (dtp->u.p.scratch);
2785   if (dtp->u.p.current_unit != NULL)
2786     unlock_unit (dtp->u.p.current_unit);
2787
2788   free_internal_unit (dtp);
2789   
2790   library_end ();
2791 }
2792
2793 extern void st_write (st_parameter_dt *);
2794 export_proto(st_write);
2795
2796 void
2797 st_write (st_parameter_dt *dtp)
2798 {
2799   library_start (&dtp->common);
2800   data_transfer_init (dtp, 0);
2801 }
2802
2803 extern void st_write_done (st_parameter_dt *);
2804 export_proto(st_write_done);
2805
2806 void
2807 st_write_done (st_parameter_dt *dtp)
2808 {
2809   finalize_transfer (dtp);
2810
2811   /* Deal with endfile conditions associated with sequential files.  */
2812
2813   if (dtp->u.p.current_unit != NULL 
2814       && dtp->u.p.current_unit->flags.access == ACCESS_SEQUENTIAL)
2815     switch (dtp->u.p.current_unit->endfile)
2816       {
2817       case AT_ENDFILE:          /* Remain at the endfile record.  */
2818         break;
2819
2820       case AFTER_ENDFILE:
2821         dtp->u.p.current_unit->endfile = AT_ENDFILE;    /* Just at it now.  */
2822         break;
2823
2824       case NO_ENDFILE:
2825         /* Get rid of whatever is after this record.  */
2826         if (!is_internal_unit (dtp))
2827           {
2828             flush (dtp->u.p.current_unit->s);
2829             if (struncate (dtp->u.p.current_unit->s) == FAILURE)
2830               generate_error (&dtp->common, ERROR_OS, NULL);
2831           }
2832         dtp->u.p.current_unit->endfile = AT_ENDFILE;
2833         break;
2834       }
2835
2836   free_format_data (dtp);
2837   free_ionml (dtp);
2838   if (dtp->u.p.scratch != NULL)
2839     free_mem (dtp->u.p.scratch);
2840   if (dtp->u.p.current_unit != NULL)
2841     unlock_unit (dtp->u.p.current_unit);
2842   
2843   free_internal_unit (dtp);
2844
2845   library_end ();
2846 }
2847
2848 /* Receives the scalar information for namelist objects and stores it
2849    in a linked list of namelist_info types.  */
2850
2851 extern void st_set_nml_var (st_parameter_dt *dtp, void *, char *,
2852                             GFC_INTEGER_4, gfc_charlen_type, GFC_INTEGER_4);
2853 export_proto(st_set_nml_var);
2854
2855
2856 void
2857 st_set_nml_var (st_parameter_dt *dtp, void * var_addr, char * var_name,
2858                 GFC_INTEGER_4 len, gfc_charlen_type string_length,
2859                 GFC_INTEGER_4 dtype)
2860 {
2861   namelist_info *t1 = NULL;
2862   namelist_info *nml;
2863   size_t var_name_len = strlen (var_name);
2864
2865   nml = (namelist_info*) get_mem (sizeof (namelist_info));
2866
2867   nml->mem_pos = var_addr;
2868
2869   nml->var_name = (char*) get_mem (var_name_len + 1);
2870   memcpy (nml->var_name, var_name, var_name_len);
2871   nml->var_name[var_name_len] = '\0';
2872
2873   nml->len = (int) len;
2874   nml->string_length = (index_type) string_length;
2875
2876   nml->var_rank = (int) (dtype & GFC_DTYPE_RANK_MASK);
2877   nml->size = (index_type) (dtype >> GFC_DTYPE_SIZE_SHIFT);
2878   nml->type = (bt) ((dtype & GFC_DTYPE_TYPE_MASK) >> GFC_DTYPE_TYPE_SHIFT);
2879
2880   if (nml->var_rank > 0)
2881     {
2882       nml->dim = (descriptor_dimension*)
2883                    get_mem (nml->var_rank * sizeof (descriptor_dimension));
2884       nml->ls = (array_loop_spec*)
2885                   get_mem (nml->var_rank * sizeof (array_loop_spec));
2886     }
2887   else
2888     {
2889       nml->dim = NULL;
2890       nml->ls = NULL;
2891     }
2892
2893   nml->next = NULL;
2894
2895   if ((dtp->common.flags & IOPARM_DT_IONML_SET) == 0)
2896     {
2897       dtp->common.flags |= IOPARM_DT_IONML_SET;
2898       dtp->u.p.ionml = nml;
2899     }
2900   else
2901     {
2902       for (t1 = dtp->u.p.ionml; t1->next; t1 = t1->next);
2903       t1->next = nml;
2904     }
2905 }
2906
2907 /* Store the dimensional information for the namelist object.  */
2908 extern void st_set_nml_var_dim (st_parameter_dt *, GFC_INTEGER_4,
2909                                 index_type, index_type,
2910                                 index_type);
2911 export_proto(st_set_nml_var_dim);
2912
2913 void
2914 st_set_nml_var_dim (st_parameter_dt *dtp, GFC_INTEGER_4 n_dim,
2915                     index_type stride, index_type lbound,
2916                     index_type ubound)
2917 {
2918   namelist_info * nml;
2919   int n;
2920
2921   n = (int)n_dim;
2922
2923   for (nml = dtp->u.p.ionml; nml->next; nml = nml->next);
2924
2925   nml->dim[n].stride = stride;
2926   nml->dim[n].lbound = lbound;
2927   nml->dim[n].ubound = ubound;
2928 }
2929
2930 /* Reverse memcpy - used for byte swapping.  */
2931
2932 void reverse_memcpy (void *dest, const void *src, size_t n)
2933 {
2934   char *d, *s;
2935   size_t i;
2936
2937   d = (char *) dest;
2938   s = (char *) src + n - 1;
2939
2940   /* Write with ascending order - this is likely faster
2941      on modern architectures because of write combining.  */
2942   for (i=0; i<n; i++)
2943       *(d++) = *(s--);
2944 }