/* ARM assembly Raspberry PI  */
/*  program xiaolin1.s   */

/* REMARK 1 : this program use routines in a include file
   see task Include a file language arm assembly
   for the routine affichageMess displayerror
   see at end oh this program the instruction include */

/* REMARK 2 : display use a FrameBuffer device : see raspberry pi FrameBuffer documentation
              this solution write directly on the screen of raspberry pi
              other solution is to use X11 windows but X11 has a function drawline !! */

/* REMARK 3 : this program do not respect the convention for use, save and restau registers
              in rhe routine call !!!!   */

/*******************************************/
/* Constantes    */
/*******************************************/
.equ STDOUT,              1     @ Linux output console
.equ EXIT,                1     @ Linux syscall
.equ WRITE,               4     @ Linux syscall
.equ OPEN,                5
.equ CLOSE,               6
.equ IOCTL,               0x36
.equ MMAP,                0xC0
.equ UNMAP,               0x5B
.equ O_RDWR,              0x0002    @ open for reading and writing
.equ MAP_SHARED,          0x01      @ Share changes.
.equ PROT_READ,           0x1       @ Page can be read.
.equ PROT_WRITE,          0x2       @ Page can be written.

/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessErreur:   .asciz "File open error.\n"
szMessErreur1:  .asciz "File close error.\n"
szMessErreur2:  .asciz "File mapping error.\n"
szMessDebutPgm: .asciz "Program start. \n"
szMessFinOK:    .asciz "Normal end program. \n"
szMessErrFix:   .asciz  "Read error info fix framebuffer  \n"
szMessErrVar:   .asciz  "Read error info var framebuffer  \n"
szRetourligne:  .asciz  "\n"
szParamNom:     .asciz "/dev/fb0"         @ FrameBuffer device name
szLigneVar:     .ascii "Variables info : "
sWidth:        .fill 11, 1, ' '
                .ascii " * "
sHeight:        .fill 11, 1, ' '
                .ascii " Bits par pixel : "
sBits:           .fill 11, 1, ' '
                .asciz  "\n"
/*************************************************/
szMessErr: .ascii	"Error code hexa : "
sHexa: .space 9,' '
         .ascii "  decimal :  "
sDeci: .space 15,' '
         .asciz "\n"
.align 4
/* codes fonction pour la récupération des données fixes et variables */
FBIOGET_FSCREENINFO: .int 0x4602  @ function code for read infos fixes Framebuffer
FBIOGET_VSCREENINFO: .int 0x4600  @ function code for read infos variables Framebuffer

/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
.align 4
fix_info: .skip FBFIXSCinfo_fin                @ memory reserve for structure FSCREENINFO
.align 4
var_info: .skip FBVARSCinfo_fin                @ memory reserve for structure VSCREENINFO
/**********************************************/
/* -- Code section                            */
/**********************************************/
.text
.global main

main:
    ldr r0,iAdrszMessDebutPgm
    bl affichageMess                  @ display message
    ldr r0,iAdrszParamNom             @ frameBuffer device name
    mov r1,#O_RDWR                    @ flags read/write
    mov r2,#0                         @ mode
    mov r7,#OPEN                      @ open device FrameBuffer
    svc 0
    cmp r0,#0                         @ error ?
    ble erreur
    mov r10,r0                        @ save FD du device FrameBuffer in r10

    ldr r1,iAdrFBIOGET_VSCREENINFO    @ read variables datas of FrameBuffer
    ldr r1,[r1]                       @ load code function
    ldr r2,iAdrvar_info               @ structure memory address
    mov r7, #IOCTL                    @ call system
    swi 0
    cmp r0,#0
    blt erreurVar
    ldr r2,iAdrvar_info
    ldr r0,[r2,#FBVARSCinfo_xres]     @ load screen width
    ldr r1,iAdrsWidth                 @ and convert in string for display
    bl conversion10S
    ldr r0,[r2,#FBVARSCinfo_yres]     @ load screen height
    ldr r1,iAdrsHeight                @ and convert in string for display
    bl conversion10S
    ldr r0,[r2,#FBVARSCinfo_bits_per_pixel]  @ load bits by pixel
    ldr r1,iAdrsBits                  @ and convert in string for display
    bl conversion10S
    ldr r0,iAdrszLigneVar             @ display result
    bl affichageMess

    mov r0,r10                        @ FD du FB
    ldr r1,iAdrFBIOGET_FSCREENINFO    @ read fixes datas of FrameBuffe
    ldr r1,[r1]                       @ load code function
    ldr r2,iAdrfix_info               @ structure memory address
    mov r7, #IOCTL                    @ call system
    svc 0
    cmp r0,#0                         @ error ?
    blt erreurFix
    ldr r0,iAdrfix_info

    ldr r1,iAdrfix_info               @ read size memory for datas
    ldr r1,[r1,#FBFIXSCinfo_smem_len] @ in octets
                                      @ datas mapping
    mov r0,#0
    ldr r2,iFlagsMmap
    mov r3,#MAP_SHARED
    mov r4,r10
    mov r5,#0
    mov r7, #MMAP                     @ 192 call system for mapping
    swi #0
    cmp r0,#0                         @ error ?
    beq erreur2
    mov r9,r0                         @ save mapping address in r9
    /*************************************/
    /* display draw                      */
    bl dessin
    /************************************/
    mov r0,r9                         @ mapping close
    ldr r1,iAdrfix_info
    ldr r1,[r1,#FBFIXSCinfo_smem_len] @ mapping memory size
    mov r7,#UNMAP                     @call system 91 for unmapping
    svc #0                            @ error ?
    cmp r0,#0
    blt erreur1
                                      @ close device FrameBuffer
    mov r0,r10                        @ load FB du device
    mov r7, #CLOSE                    @ call system
    swi 0
    ldr r0,iAdrszMessFinOK            @ display end message
    bl affichageMess
    mov r0,#0                         @ return code = OK
    b 100f
erreurFix:                            @ display read error datas fix
    ldr r1,iAdrszMessErrFix           @ message address
    bl   displayError                 @ call display
    mov r0,#1                         @ return code = error
    b 100f
erreurVar:                            @ display read error datas var
    ldr r1,iAdrszMessErrVar
    bl   displayError
    mov r0,#1
    b 100f
erreur:                               @ display open error
    ldr r1,iAdrszMessErreur
    bl   displayError
    mov r0,#1
    b 100f
erreur1:                              @ display unmapped error
    ldr r1,iAdrszMessErreur1
    bl   displayError
    mov r0,#1
    b 100f
erreur2:                              @ display mapped error
    ldr r1,iAdrszMessErreur2
    bl   displayError
    mov r0,#1
    b 100f
100:                                  @ end program
    mov r7, #EXIT
    svc 0
/************************************/
iAdrszParamNom:           .int szParamNom
iFlagsMmap:               .int PROT_READ|PROT_WRITE
iAdrszMessErreur:         .int szMessErreur
iAdrszMessErreur1:        .int szMessErreur1
iAdrszMessErreur2:        .int szMessErreur2
iAdrszMessDebutPgm:       .int szMessDebutPgm
iAdrszMessFinOK:          .int szMessFinOK
iAdrszMessErrFix:         .int szMessErrFix
iAdrszMessErrVar:         .int szMessErrVar
iAdrszLigneVar:           .int szLigneVar
iAdrvar_info:             .int var_info
iAdrfix_info:             .int fix_info
iAdrFBIOGET_FSCREENINFO:  .int FBIOGET_FSCREENINFO
iAdrFBIOGET_VSCREENINFO:  .int FBIOGET_VSCREENINFO
iAdrsWidth:               .int sWidth
iAdrsHeight:              .int sHeight
iAdrsBits:                .int sBits
/***************************************************/
/*   dessin                  */
/***************************************************/
/* r9 framebuffer memory address   */
dessin:
    push {r1-r12,lr}                  @ save registers
    mov r0,#255                       @ red
    mov r1,#255                       @ green
    mov r2,#255                       @ blue    3 bytes 255 = white
    bl codeRGB                        @ code color RGB  32 bits
    mov r1,r0                         @ background color
    ldr r0,iAdrfix_info               @ load memory mmap size
    ldr r0,[r0,#FBFIXSCinfo_smem_len]
    bl coloriageFond                  @
    /* draw line 1  */
    mov r0,#200                       @ X start line
    mov r1,#200                       @ Y start line
    mov r2,#200                       @ X end line
    mov r3,#100                       @ Y end line
    ldr r4,iAdrvar_info
    ldr r4,[r4,#FBVARSCinfo_xres]     @ load screen width
    bl drawLine
    /* draw line 2  */
    mov r0,#200
    mov r1,#200
    mov r2,#200
    mov r3,#300
    ldr r4,iAdrvar_info
    ldr r4,[r4,#FBVARSCinfo_xres]
    bl drawLine
    /* draw line 3  */
    mov r0,#200
    mov r1,#200
    mov r2,#100
    mov r3,#200
    ldr r4,iAdrvar_info
    ldr r4,[r4,#FBVARSCinfo_xres]
    bl drawLine
    /* draw line 4  */
    mov r0,#200
    mov r1,#200
    mov r2,#300
    mov r3,#200
    ldr r4,iAdrvar_info
    ldr r4,[r4,#FBVARSCinfo_xres]
    bl drawLine
    /* draw line 5  */
    mov r0,#200
    mov r1,#200
    mov r2,#100
    mov r3,#100
    ldr r4,iAdrvar_info
    ldr r4,[r4,#FBVARSCinfo_xres]
    bl drawLine
    /* draw line 6  */
    mov r0,#200
    mov r1,#200
    mov r2,#100
    mov r3,#300
    ldr r4,iAdrvar_info
    ldr r4,[r4,#FBVARSCinfo_xres]
    bl drawLine
    /* draw line 7  */
    mov r0,#200
    mov r1,#200
    mov r2,#300
    mov r3,#300
    ldr r4,iAdrvar_info
    ldr r4,[r4,#FBVARSCinfo_xres]
    bl drawLine
    /* draw line 8  */
    mov r0,#200
    mov r1,#200
    mov r2,#300
    mov r3,#100
    ldr r4,iAdrvar_info
    ldr r4,[r4,#FBVARSCinfo_xres]
    bl drawLine

100:
    pop {r1-r12,lr}                 @ restaur registers
    bx lr                           @ end function

/********************************************************/
/*   set background color                               */
/********************************************************/
/* r0 contains size screen memory  */
/* r1 contains rgb code color      */
/* r9 contains screen memory address */
coloriageFond:
    push {r2,lr}
    mov r2,#0                     @ counter
1:                                @ begin loop
    str r1,[r9,r2]
    add r2,#4
    cmp r2,r0
    blt 1b
    pop {r2,lr}
    bx lr
/********************************************************/
/*   Xiaolin Wu  line algorithm                        */
/*  no floating point compute,  multiply value for 128  */
/*  for integer compute                                 */
/********************************************************/
/* r0  x1 start line */
/* r1  y1 start line */
/* r2  x2 end line */
/* r3  y2 end line */
/* r4  screen width */
drawLine:
    push {fp,lr}      @ save registers ( no other registers save )
    mov r5,r0         @ save x1
    mov r6,r1         @ save y1
    cmp r2,r5         @ compar x2,x1
    subgt r1,r2,r5
    suble r1,r5,r2    @ compute dx=abs val de x1-x2
    cmp r3,r6         @ compar y2,y1
    subgt r0,r3,r6
    suble r0,r6,r3    @ compute dy = abs val de y1-y2
    cmp r1,r0         @ compare dx , dy
    blt 5f            @ dx < dy
                      @ dx > dy
    cmp r2,r5         @ compare x2,x1
    movlt r8,r5       @ x2 < x1
    movlt r5,r2       @ swap x2,x1
    movlt r2,r8
    movlt r8,r6       @ swap y2,y1
    movlt r6,r3
    movlt r3,r8
    lsl r0,#7         @ * by 128
    mov r7,r2         @ save x2
    mov r8,r3         @ save y2
    cmp r1,#0         @ divisor = 0 ?
    moveq r10,#128
    beq 1f
    bl division       @ gradient compute (* 128)
    mov r10,r2        @ r10 contient le gradient
1:
    @ display start points
    mov r0,#64
    bl colorPixel
    mov r3,r0              @ RGB color
    mov r0,r5              @ x1
    mov r1,r6              @ y1
    mov r2,r4              @ screen witdh
    bl aff_pixel_codeRGB32 @ display pixel
    add r1,#1              @ increment y1
    bl aff_pixel_codeRGB32
    @ display end points
    mov r0,r7              @ x2
    mov r1,r8              @ y2
    bl aff_pixel_codeRGB32
    add r1,#1              @ increment y2
    bl aff_pixel_codeRGB32
    cmp r8,r6              @ compar y2,y1
    blt 3f                 @ y2 < y1
    mov r4,r5              @ x =  x1
    lsl r5,r6,#7           @ compute y1 * 128
    add r5,r10             @ compute intery = (y1 * 128 + gradient * 128)
2:                         @ start loop draw line pixels
    lsr r1,r5,#7           @ intery / 128  = y
    lsl r8,r1,#7
    sub r6,r5,r8           @ reminder of intery /128 = brightness
    mov r0,r6
    bl colorPixel          @ compute rgb color brightness
    mov r3,r0              @ rgb color
    mov r0,r4              @ x
    bl aff_pixel_codeRGB32 @ display pixel 1
    add r1,#1              @ increment y
    rsb r0,r6,#128         @ compute 128 - brightness
    bl colorPixel          @ compute new rgb color
    mov r3,r0
    mov r0,r4
    bl aff_pixel_codeRGB32 @ display pixel 2
    add r5,r10             @ add gradient to intery
    add r4,#1              @ increment x
    cmp r4,r7              @ x < x2
    ble 2b                 @ yes -> loop
    b 100f                 @ else end
3:                         @ y2 < y1
    mov r4,r7              @ x = x2
    mov r7,r5              @ save x1
    lsl r5,r8,#7           @ y = y1 * 128
    add r5,r10             @ compute intery = (y1 * 128 + gradient * 128)
4:
    lsr r1,r5,#7           @ y = ent(intery / 128)
    lsl r8,r1,#7
    sub r8,r5,r8           @ brightness = remainder
    mov r0,r8
    bl colorPixel
    mov r3,r0
    mov r0,r4
    bl aff_pixel_codeRGB32
    add r1,#1
    rsb r0,r8,#128
    bl colorPixel
    mov r3,r0
    mov r0,r4
    bl aff_pixel_codeRGB32
    add r5,r10
    sub r4,#1             @ decrement x
    cmp r4,r7             @ x > x1
    bgt 4b                @ yes -> loop
    b 100f
5:                        @ dx < dy
    cmp r3,r6             @ compare y2,y1
    movlt r8,r5           @ y2 < y1
    movlt r5,r2           @ swap x1,x2
    movlt r2,r8
    movlt r8,r6           @ swap y1,y2
    movlt r6,r3
    movlt r3,r8
    mov r8,r1             @ swap r0,r1 for routine division
    mov r1,r0
    lsl r0,r8,#7          @ dx * by 128
    mov r7,r2             @ save x2
    mov r8,r3             @ save y2
    cmp r1,#0             @ dy = zero ?
    moveq r10,#128
    beq 6f
    bl division           @  compute gradient * 128
    mov r10,r2            @  gradient -> r10
6:
    @ display start points
    mov r0,#64
    bl colorPixel
    mov r3,r0             @ color pixel
    mov r0,r5             @ x1
    mov r1,r6             @ y1
    mov r2,r4             @ screen width
    bl aff_pixel_codeRGB32
    add r1,#1
    bl aff_pixel_codeRGB32
    @ display end points
    mov r0,r7
    mov r1,r8
    bl aff_pixel_codeRGB32
    add r1,#1
    bl aff_pixel_codeRGB32
    cmp r5,r7                  @ x1 < x2 ?
    blt 8f
    mov r4,r6                  @  y = y1
    lsl r5,#7                  @ compute x1 * 128
    add r5,r10                 @ compute interx
7:
    lsr r1,r5,#7               @ compute x = ent ( interx / 128)
    lsl r3,r1,#7
    sub r6,r5,r3               @ brightness = remainder
    mov r0,r6
    bl colorPixel
    mov r3,r0
    mov r0,r1                  @ new x
    add r7,r0,#1
    mov r1,r4                  @ y
    bl aff_pixel_codeRGB32
    rsb r0,r6,#128
    bl colorPixel
    mov r3,r0
    mov r0,r7                  @ new x + 1
    mov r1,r4                  @ y
    bl aff_pixel_codeRGB32
    add r5,r10
    add r4,#1
    cmp r4,r8
    ble 7b
    b 100f
8:
    mov r4,r8                  @  y = y2
    lsl r5,#7                  @ compute x1 * 128
    add r5,r10                 @ compute interx
9:
    lsr r1,r5,#7               @ compute x
    lsl r3,r1,#7
    sub r8,r5,r3
    mov r0,r8
    bl colorPixel
    mov r3,r0
    mov r0,r1                  @ new x
    add r7,r0,#1
    mov r1,r4                  @ y
    bl aff_pixel_codeRGB32
    rsb r0,r8,#128
    bl colorPixel
    mov r3,r0
    mov r0,r7                  @ new x + 1
    mov r1,r4                  @ y
    bl aff_pixel_codeRGB32
    add r5,r10
    sub r4,#1
    cmp r4,r6
    bgt 9b
    b 100f
100:
    pop {fp,lr}
    bx lr
/********************************************************/
/*   brightness color pixel                              */
/********************************************************/
/* r0 % brightness ( 0 to 128)  */
colorPixel:
    push {r1,r2,lr}    /* save des  2 registres frame et retour */
    cmp r0,#0
    beq 100f
    cmp r0,#128
    mov r0,#127
    lsl r0,#1          @ red = brightness * 2 ( 2 to 254)
    mov r1,r0          @ green = red
    mov r2,r0          @ blue = red
    bl codeRGB         @ compute rgb code color 32 bits
100:
    pop {r1,r2,lr}
    bx lr

/***************************************************/
/*   display pixels  32 bits                       */
/***************************************************/
/* r9 framebuffer memory address */
/* r0 = x */
/* r1 = y */
/* r2 screen width in pixels */
/* r3 code color RGB 32 bits  */
aff_pixel_codeRGB32:
    push {r0-r4,lr}       @  save registers
                          @ compute location pixel
    mul r4,r1,r2          @ compute y * screen width
    add r0,r0,r4          @ + x
    lsl r0,#2             @ * 4 octets
    str r3,[r9,r0]        @ store rgb code in mmap memory
    pop {r0-r4,lr}        @ restaur registers
    bx lr
/********************************************************/
/*   Code color RGB                                     */
/********************************************************/
/* r0 red r1 green  r2 blue */
/* r0 returns RGB code      */
codeRGB:
    lsl r0,#16               @ shift red color 16 bits
    lsl r1,#8                @ shift green color 8 bits
    eor r0,r1                @ or two colors
    eor r0,r2                @ or 3 colors in r0
    bx lr

/***************************************************/
/*      ROUTINES INCLUDE                 */
/***************************************************/
.include "./affichage.inc"

/***************************************************/
/*      DEFINITION DES STRUCTURES                 */
/***************************************************/
/* structure FSCREENINFO */
/* voir explication détaillée : https://www.kernel.org/doc/Documentation/fb/api.txt */
    .struct  0
FBFIXSCinfo_id:          /* identification string eg "TT Builtin" */
    .struct FBFIXSCinfo_id + 16
FBFIXSCinfo_smem_start:    /* Start of frame buffer mem */
    .struct FBFIXSCinfo_smem_start + 4
FBFIXSCinfo_smem_len:       /* Length of frame buffer mem */
    .struct FBFIXSCinfo_smem_len + 4
FBFIXSCinfo_type:    /* see FB_TYPE_*        */
    .struct FBFIXSCinfo_type + 4
FBFIXSCinfo_type_aux:      /* Interleave for interleaved Planes */
    .struct FBFIXSCinfo_type_aux + 4
FBFIXSCinfo_visual:    /* see FB_VISUAL_*        */
    .struct FBFIXSCinfo_visual + 4
FBFIXSCinfo_xpanstep:    /* zero if no hardware panning  */
    .struct FBFIXSCinfo_xpanstep + 2
FBFIXSCinfo_ypanstep:    /* zero if no hardware panning  */
    .struct FBFIXSCinfo_ypanstep + 2
FBFIXSCinfo_ywrapstep:      /* zero if no hardware ywrap    */
    .struct FBFIXSCinfo_ywrapstep + 4
FBFIXSCinfo_line_length:    /* length of a line in bytes    */
    .struct FBFIXSCinfo_line_length + 4
FBFIXSCinfo_mmio_start:     /* Start of Memory Mapped I/O   */
    .struct FBFIXSCinfo_mmio_start + 4
FBFIXSCinfo_mmio_len:        /* Length of Memory Mapped I/O  */
    .struct FBFIXSCinfo_mmio_len + 4
FBFIXSCinfo_accel:     /* Indicate to driver which    specific chip/card we have    */
    .struct FBFIXSCinfo_accel + 4
FBFIXSCinfo_capabilities:     /* see FB_CAP_*            */
    .struct FBFIXSCinfo_capabilities + 4
FBFIXSCinfo_reserved:     /* Reserved for future compatibility */
    .struct FBFIXSCinfo_reserved + 8
FBFIXSCinfo_fin:

/* structure VSCREENINFO */
    .struct  0
FBVARSCinfo_xres:           /* visible resolution        */
    .struct FBVARSCinfo_xres + 4
FBVARSCinfo_yres:
    .struct FBVARSCinfo_yres + 4
FBVARSCinfo_xres_virtual:          /* virtual resolution        */
    .struct FBVARSCinfo_xres_virtual + 4
FBVARSCinfo_yres_virtual:
    .struct FBVARSCinfo_yres_virtual + 4
FBVARSCinfo_xoffset:          /* offset from virtual to visible resolution */
    .struct FBVARSCinfo_xoffset + 4
FBVARSCinfo_yoffset:
    .struct FBVARSCinfo_yoffset + 4
FBVARSCinfo_bits_per_pixel:          /* bits par pixel */
    .struct FBVARSCinfo_bits_per_pixel + 4
FBVARSCinfo_grayscale:          /* 0 = color, 1 = grayscale,  >1 = FOURCC    */
    .struct FBVARSCinfo_grayscale + 4
FBVARSCinfo_red:          /* bitfield in fb mem if true color, */
    .struct FBVARSCinfo_red + 4
FBVARSCinfo_green:          /* else only length is significant */
    .struct FBVARSCinfo_green + 4
FBVARSCinfo_blue:
    .struct FBVARSCinfo_blue + 4
FBVARSCinfo_transp:          /* transparency            */
    .struct FBVARSCinfo_transp + 4
FBVARSCinfo_nonstd:          /* != 0 Non standard pixel format */
    .struct FBVARSCinfo_nonstd + 4
FBVARSCinfo_activate:          /* see FB_ACTIVATE_*        */
    .struct FBVARSCinfo_activate + 4
FBVARSCinfo_height:              /* height of picture in mm    */
    .struct FBVARSCinfo_height + 4
FBVARSCinfo_width:           /* width of picture in mm     */
    .struct FBVARSCinfo_width + 4
FBVARSCinfo_accel_flags:          /* (OBSOLETE) see fb_info.flags */
    .struct FBVARSCinfo_accel_flags + 4
/* Timing: All values in pixclocks, except pixclock (of course) */
FBVARSCinfo_pixclock:          /* pixel clock in ps (pico seconds) */
    .struct FBVARSCinfo_pixclock + 4
FBVARSCinfo_left_margin:
    .struct FBVARSCinfo_left_margin + 4
FBVARSCinfo_right_margin:
    .struct FBVARSCinfo_right_margin + 4
FBVARSCinfo_upper_margin:
    .struct FBVARSCinfo_upper_margin + 4
FBVARSCinfo_lower_margin:
    .struct FBVARSCinfo_lower_margin + 4
FBVARSCinfo_hsync_len:          /* length of horizontal sync    */
    .struct FBVARSCinfo_hsync_len + 4
FBVARSCinfo_vsync_len:          /* length of vertical sync    */
    .struct FBVARSCinfo_vsync_len + 4
FBVARSCinfo_sync:          /* see FB_SYNC_*        */
    .struct FBVARSCinfo_sync + 4
FBVARSCinfo_vmode:          /* see FB_VMODE_*        */
    .struct FBVARSCinfo_vmode + 4
FBVARSCinfo_rotate:          /* angle we rotate counter clockwise */
    .struct FBVARSCinfo_rotate + 4
FBVARSCinfo_colorspace:          /* colorspace for FOURCC-based modes */
    .struct FBVARSCinfo_colorspace + 4
FBVARSCinfo_reserved:          /* Reserved for future compatibility */
    .struct FBVARSCinfo_reserved + 16
FBVARSCinfo_fin:


#SingleInstance, Force
#NoEnv
SetBatchLines, -1

pToken := Gdip_Startup()
global pBitmap := Gdip_CreateBitmap(500, 500)
drawLine(100,50,400,400)
Gdip_SaveBitmapToFile(pBitmap, A_ScriptDir "\linetest.png")
Gdip_DisposeImage(pBitmap)
Gdip_Shutdown(pToken)
Run, % A_ScriptDir "\linetest.png"
ExitApp

plot(x, y, c) {
    A := DecToBase(255 * c, 16)
    Gdip_SetPixel(pBitmap, x, y, "0x" A "000000")
}

; integer part of x
ipart(x) {
    return x // 1
}

rnd(x) {
    return ipart(x + 0.5)
}

; fractional part of x
fpart(x) {
    if (x < 0)
        return 1 - (x - floor(x))
    return x - floor(x)
}

rfpart(x) {
    return 1 - fpart(x)
}

drawLine(x0,y0,x1,y1) {
    steep := abs(y1 - y0) > abs(x1 - x0)

    if (steep) {
        temp := x0, x0 := y0, y0 := temp
        temp := x1, x1 := y1, y1 := temp
    }
    if (x0 > x1 then) {
        temp := x0, x0 := x1, x1 := temp
        temp := y0, y0 := y1, y1 := temp
    }

    dx := x1 - x0
    dy := y1 - y0
    gradient := dy / dx

    ; handle first endpoint
    xend := rnd(x0)
    yend := y0 + gradient * (xend - x0)
    xgap := rfpart(x0 + 0.5)
    xpxl1 := xend ; this will be used in the main loop
    ypxl1 := ipart(yend)
    if (steep) {
        plot(ypxl1,   xpxl1, rfpart(yend) * xgap)
        plot(ypxl1+1, xpxl1,  fpart(yend) * xgap)
    }
    else {
        plot(xpxl1, ypxl1  , rfpart(yend) * xgap)
        plot(xpxl1, ypxl1+1,  fpart(yend) * xgap)
    }
    intery := yend + gradient ; first y-intersection for the main loop

    ; handle second endpoint
    xend := rnd(x1)
    yend := y1 + gradient * (xend - x1)
    xgap := fpart(x1 + 0.5)
    xpxl2 := xend ;this will be used in the main loop
    ypxl2 := ipart(yend)
    if (steep) {
        plot(ypxl2  , xpxl2, rfpart(yend) * xgap)
        plot(ypxl2+1, xpxl2,  fpart(yend) * xgap)
    }
    else {
        plot(xpxl2, ypxl2,  rfpart(yend) * xgap)
        plot(xpxl2, ypxl2+1, fpart(yend) * xgap)
    }

    ; main loop
    while (x := xpxl1 + A_Index) < xpxl2 {
        if (steep) {
            plot(ipart(intery)  , x, rfpart(intery))
            plot(ipart(intery)+1, x,  fpart(intery))
        }
        else {
            plot(x, ipart (intery),  rfpart(intery))
            plot(x, ipart (intery)+1, fpart(intery))
        }
        intery := intery + gradient
    }
}

DecToBase(n, Base) {
    static U := A_IsUnicode ? "w" : "a"
    VarSetCapacity(S,65,0)
    DllCall("msvcrt\_i64to" U, "Int64",n, "Str",S, "Int",Base)
    return, S
}


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program writeFile64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessErreur:  .asciz "Error open file.\n"
szMessErreur1: .asciz "Error close file.\n"
szMessErreur2: .asciz "Error write file.\n"
szMessWriteOK: .asciz "String write in file OK.\n"

szParamNom:    .asciz "./fic1.txt"      // file name
sZoneEcrit:    .ascii "(Over)write a file so that it contains a string."
               .equ LGZONEECRIT, . - sZoneEcrit
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss

/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                         // entry of program
                              // file open
    mov x0,AT_FDCWD           // current directory
    ldr x1,qAdrszParamNom     // filename
    mov x2,O_CREAT|O_WRONLY   //  flags
    ldr x3,oficmask1          // mode
    mov x8,OPEN               // Linux call system
    svc 0                     //
    cmp x0,0                  // error ?
    ble erreur                // yes
    mov x28,x0                // save File Descriptor
                              // x0 = FD
    ldr x1,qAdrsZoneEcrit     // write string address
    mov x2,LGZONEECRIT        // string size
    mov x8,WRITE              // Linux call system
    svc 0
    cmp x0,0                 // error ?
    ble erreur2               // yes
                              // close file
    mov x0,x28                // File Descriptor
    mov x8,CLOSE              // Linuc call system
    svc 0
    cmp x0,0                  // error ?
    blt erreur1
    ldr x0,qAdrszMessWriteOK
    bl affichageMess
    mov x0,#0                 // return code OK
    b 100f
erreur:
    ldr x1,qAdrszMessErreur
    bl affichageMess          // display error message
    mov x0,#1
    b 100f
erreur1:
    ldr x1,qAdrszMessErreur1  // x0 <- adresse chaine
    bl affichageMess          // display error message
    mov x0,#1                 // return code error
    b 100f
erreur2:
    ldr x0,qAdrszMessErreur2
    bl affichageMess          // display error message
    mov x0,#1                 // return code error
    b 100f
100:                          // program end
    mov x8,EXIT
    svc #0
qAdrszParamNom:            .quad szParamNom
qAdrszMessErreur:          .quad szMessErreur
qAdrszMessErreur1:         .quad szMessErreur1
qAdrszMessErreur2:         .quad szMessErreur2
qAdrszMessWriteOK:         .quad szMessWriteOK
qAdrsZoneEcrit:            .quad sZoneEcrit
oficmask1:                 .quad 0644         // this zone is Octal number (0 before)
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


proc MAIN()
  open (1,"D:FILE.TXT",8,0)
  printde(1,"My string")
  close(1)
return


with Ada.Text_IO;  use Ada.Text_IO;

procedure Write_Whole_File is
   File_Name : constant String := "the_file.txt";

   F : File_Type;
begin
   begin
      Open (F, Mode => Out_File, Name => File_Name);
   exception
      when Name_Error => Create (F, Mode => Out_File, Name => File_Name);
   end;

   Put (F, "(Over)write a file so that it contains a string. "               &
           "The reverse of Read entire file—for when you want to update or " &
           "create a file which you would read in its entirety all at once.");
   Close (F);
end Write_Whole_File;


IF  FILE   output;
    STRING output file name = "output.txt";
    open( output, output file name, stand out channel ) = 0
THEN
    # file opened OK #
    put( output, ( "line 1", newline, "line 2", newline ) );
    close( output )
ELSE
    # unable to open the output file #
    print( ( "Cannot open ", output file name, newline ) )
FI


contents: "Hello World!"
write "output.txt" contents


file := FileOpen("test.txt", "w")
file.Write("this is a test string")
file.Close()


      PROCdrawAntiAliasedLine(100, 100, 600, 400, 0, 0, 0)
      END

      DEF PROCdrawAntiAliasedLine(x1, y1, x2, y2, r%, g%, b%)
      LOCAL dx, dy, xend, yend, grad, yf, xgap, ix1%, iy1%, ix2%, iy2%, x%

      dx = x2 - x1
      dy = y2 - y1
      IF ABS(dx) < ABS(dy) THEN
        SWAP x1, y1
        SWAP x2, y2
        SWAP dx, dy
      ENDIF

      IF x2 < x1 THEN
        SWAP x1, x2
        SWAP y1, y2
      ENDIF

      grad = dy / dx

      xend = INT(x1 + 0.5)
      yend = y1 + grad * (xend - x1)
      xgap = xend + 0.5 - x1
      ix1% = xend
      iy1% = INT(yend)
      PROCplot(ix1%, iy1%, r%, b%, g%, (INT(yend) + 1 - yend) * xgap)
      PROCplot(ix1%, iy1% + 1, r%, b%, g%, (yend - INT(yend)) * xgap)
      yf = yend + grad

      xend = INT(x2 + 0.5)
      yend = y2 + grad * (xend - x2)
      xgap = x2 + 0.5 - xend
      ix2% = xend
      iy2% = INT(yend)
      PROCplot(ix2%, iy2%, r%, b%, g%, (INT(yend) + 1 - yend) * xgap)
      PROCplot(ix2%, iy2% + 1, r%, b%, g%, (yend - INT(yend)) * xgap)

      FOR x% = ix1% + 1 TO ix2% - 1
        PROCplot(x%, INT(yf), r%, b%, g%, INT(yf) + 1 - yf)
        PROCplot(x%, INT(yf) + 1, r%, b%, g%, yf - INT(yf))
        yf += grad
      NEXT
      ENDPROC

      DEF PROCplot(X%, Y%, R%, G%, B%, a)
      LOCAL C%
      C% = TINT(X%*2,Y%*2)
      COLOUR 1, R%*a + (C% AND 255)*(1-a), \
      \         G%*a + (C% >> 8 AND 255)*(1-a), \
      \         B%*a + (C% >> 16 AND 255)*(1-a)
      GCOL 1
      LINE X%*2, Y%*2, X%*2, Y%*2
      ENDPROC


void draw_line_antialias(
        image img,
        unsigned int x0, unsigned int y0,
        unsigned int x1, unsigned int y1,
        color_component r,
        color_component g,
        color_component b );


#include <functional>
#include <algorithm>
#include <utility>

void WuDrawLine(float x0, float y0, float x1, float y1,
                const std::function<void(int x, int y, float brightess)>& plot) {
    auto ipart = [](float x) -> int {return int(std::floor(x));};
    auto round = [](float x) -> float {return std::round(x);};
    auto fpart = [](float x) -> float {return x - std::floor(x);};
    auto rfpart = [=](float x) -> float {return 1 - fpart(x);};

    const bool steep = abs(y1 - y0) > abs(x1 - x0);
    if (steep) {
        std::swap(x0,y0);
        std::swap(x1,y1);
    }
    if (x0 > x1) {
        std::swap(x0,x1);
        std::swap(y0,y1);
    }

    const float dx = x1 - x0;
    const float dy = y1 - y0;
    const float gradient = (dx == 0) ? 1 : dy/dx;

    int xpx11;
    float intery;
    {
        const float xend = round(x0);
        const float yend = y0 + gradient * (xend - x0);
        const float xgap = rfpart(x0 + 0.5);
        xpx11 = int(xend);
        const int ypx11 = ipart(yend);
        if (steep) {
            plot(ypx11,     xpx11, rfpart(yend) * xgap);
            plot(ypx11 + 1, xpx11,  fpart(yend) * xgap);
        } else {
            plot(xpx11, ypx11,    rfpart(yend) * xgap);
            plot(xpx11, ypx11 + 1, fpart(yend) * xgap);
        }
        intery = yend + gradient;
    }

    int xpx12;
    {
        const float xend = round(x1);
        const float yend = y1 + gradient * (xend - x1);
        const float xgap = rfpart(x1 + 0.5);
        xpx12 = int(xend);
        const int ypx12 = ipart(yend);
        if (steep) {
            plot(ypx12,     xpx12, rfpart(yend) * xgap);
            plot(ypx12 + 1, xpx12,  fpart(yend) * xgap);
        } else {
            plot(xpx12, ypx12,    rfpart(yend) * xgap);
            plot(xpx12, ypx12 + 1, fpart(yend) * xgap);
        }
    }

    if (steep) {
        for (int x = xpx11 + 1; x < xpx12; x++) {
            plot(ipart(intery),     x, rfpart(intery));
            plot(ipart(intery) + 1, x,  fpart(intery));
            intery += gradient;
        }
    } else {
        for (int x = xpx11 + 1; x < xpx12; x++) {
            plot(x, ipart(intery),     rfpart(intery));
            plot(x, ipart(intery) + 1,  fpart(intery));
            intery += gradient;
        }
    }
}


# syntax: GAWK -f WRITE_ENTIRE_FILE.AWK
BEGIN {
    dev = "FILENAME.TXT"
    print("(Over)write a file so that it contains a string.") >dev
    close(dev)
    exit(0)
}


f = freefile
open f, "output.txt"
write f, "This string is to be written to the file"
close f


file% = OPENOUT filename$
PRINT#file%, text$
CLOSE#file%


put$("(Over)write a file so that it contains a string.",file,NEW)


/*
 * Write Entire File -- RossetaCode -- dirty hackish solution
 */
#define _CRT_SECURE_NO_WARNINGS  // turn off MS Visual Studio restrictions
#include <stdio.h>

int main(void)
{
    return 0 >= fputs("ANY STRING TO WRITE TO A FILE AT ONCE.",
        freopen("sample.txt","wb",stdout));
}


System.IO.File.WriteAllText("filename.txt", "This file contains a string.");


public class Line
    {
        private double x0, y0, x1, y1;
        private Color foreColor;
        private byte lineStyleMask;
        private int thickness;
        private float globalm;

        public Line(double x0, double y0, double x1, double y1, Color color, byte lineStyleMask, int thickness)
        {
            this.x0 = x0;
            this.y0 = y0;
            this.y1 = y1;
            this.x1 = x1;

            this.foreColor = color;

            this.lineStyleMask = lineStyleMask;

            this.thickness = thickness;

        }

        private void plot(Bitmap bitmap, double x, double y, double c)
        {
            int alpha = (int)(c * 255);
            if (alpha > 255) alpha = 255;
            if (alpha < 0) alpha = 0;
            Color color = Color.FromArgb(alpha, foreColor);
            if (BitmapDrawHelper.checkIfInside((int)x, (int)y, bitmap))
            {
                bitmap.SetPixel((int)x, (int)y, color);
            }
        }

        int ipart(double x) { return (int)x;}

        int round(double x) {return ipart(x+0.5);}

        double fpart(double x) {
            if(x<0) return (1-(x-Math.Floor(x)));
            return (x-Math.Floor(x));
        }

        double rfpart(double x) {
            return 1-fpart(x);
        }

        public void draw(Bitmap bitmap) {
            bool steep = Math.Abs(y1-y0)>Math.Abs(x1-x0);
             double temp;
            if(steep){
                temp=x0; x0=y0; y0=temp;
                temp=x1;x1=y1;y1=temp;
            }
            if(x0>x1){
                temp = x0;x0=x1;x1=temp;
                temp = y0;y0=y1;y1=temp;
            }

            double dx = x1-x0;
            double dy = y1-y0;
            double gradient = dy/dx;

            double xEnd = round(x0);
            double yEnd = y0+gradient*(xEnd-x0);
            double xGap = rfpart(x0+0.5);
            double xPixel1 = xEnd;
            double yPixel1 = ipart(yEnd);

            if(steep){
                plot(bitmap, yPixel1,   xPixel1, rfpart(yEnd)*xGap);
                plot(bitmap, yPixel1+1, xPixel1,  fpart(yEnd)*xGap);
            }else{
                plot(bitmap, xPixel1,yPixel1, rfpart(yEnd)*xGap);
                plot(bitmap, xPixel1, yPixel1+1, fpart(yEnd)*xGap);
            }
            double intery = yEnd+gradient;

            xEnd = round(x1);
            yEnd = y1+gradient*(xEnd-x1);
            xGap = fpart(x1+0.5);
            double xPixel2 = xEnd;
            double yPixel2 = ipart(yEnd);
            if(steep){
                plot(bitmap, yPixel2,   xPixel2, rfpart(yEnd)*xGap);
                plot(bitmap, yPixel2+1, xPixel2, fpart(yEnd)*xGap);
            }else{
                plot(bitmap, xPixel2, yPixel2, rfpart(yEnd)*xGap);
                plot(bitmap, xPixel2, yPixel2+1, fpart(yEnd)*xGap);
            }

            if(steep){
                for(int x=(int)(xPixel1+1);x<=xPixel2-1;x++){
                    plot(bitmap, ipart(intery), x, rfpart(intery));
                    plot(bitmap, ipart(intery)+1, x, fpart(intery));
                    intery+=gradient;
                }
            }else{
                for(int x=(int)(xPixel1+1);x<=xPixel2-1;x++){
                    plot(bitmap, x,ipart(intery), rfpart(intery));
                    plot(bitmap, x, ipart(intery)+1, fpart(intery));
                    intery+=gradient;
                }
            }
        }
    }


#include <fstream>
using namespace std;

int main()
{
    ofstream file("new.txt");
    file << "this is a string";
    file.close();
    return 0;
}


       IDENTIFICATION DIVISION.
       PROGRAM-ID. Overwrite.
       AUTHOR. Bill Gunshannon.
       INSTALLATION.  Home.
       DATE-WRITTEN.  31 December 2021.
      ************************************************************
      ** Program Abstract:
      **   Simple COBOL task.  Open file for output.  Write
      **     data to file. Close file.  Done...
      ************************************************************

       ENVIRONMENT DIVISION.

       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
            SELECT File-Name ASSIGN TO "File.txt"
                 ORGANIZATION IS LINE SEQUENTIAL.
       DATA DIVISION.

       FILE SECTION.

       FD  File-Name
           DATA RECORD IS Record-Name.
       01  Record-Name.
           02 Field1                  PIC X(80).

       WORKING-STORAGE SECTION.

       01 New-Val                   PIC X(80)
              VALUE 'Hello World'.

       PROCEDURE DIVISION.

       Main-Program.
           OPEN OUTPUT File-Name.
           WRITE Record-Name FROM New-Val.
           CLOSE File-Name.
           STOP RUN.

       END-PROGRAM.


(with-open-file (str "filename.txt"
                     :direction :output
                     :if-exists :supersede
                     :if-does-not-exist :create)
  (format str "File content...~%"))


import std.stdio;

void main() {
    auto file = File("new.txt", "wb");
    file.writeln("Hello World!");
}


import std.math, std.algorithm, grayscale_image;

/// Plots anti-aliased line by Xiaolin Wu's line algorithm.
void aaLine(Color)(ref Image!Color img,
                   double x1, double y1,
                   double x2, double y2,
                   in Color color) pure nothrow @safe @nogc {
    // Straight translation of Wikipedia pseudocode.

    // std.math.round is not pure. **
    static double round(in double x) pure nothrow @safe @nogc {
        return floor(x + 0.5);
    }

    static double fpart(in double x) pure nothrow @safe @nogc {
        return x - x.floor;
    }

    static double rfpart(in double x) pure nothrow @safe @nogc {
        return 1 - fpart(x);
    }

    auto dx = x2 - x1;
    auto dy = y2 - y1;
    immutable ax = dx.abs;
    immutable ay = dy.abs;

    static Color mixColors(in Color c1, in Color c2, in double p)
    pure nothrow @safe @nogc {
        static if (is(Color == RGB))
            return Color(cast(ubyte)(c1.r * p + c2.r * (1 - p)),
                         cast(ubyte)(c1.g * p + c2.g * (1 - p)),
                         cast(ubyte)(c1.b * p + c2.b * (1 - p)));
        else
            // This doesn't work for every kind of Color.
            return Color(cast(ubyte)(c1 * p + c2 * (1 - p)));
    }

    // Plot function set here to handle the two cases of slope.
    void function(ref Image!Color, in int, in int, in double, in Color)
    pure nothrow @safe @nogc plot;

    if (ax < ay) {
        swap(x1, y1);
        swap(x2, y2);
        swap(dx, dy);
        //plot = (img, x, y, p, col) {
        plot = (ref img, x, y, p, col) {
            assert(p >= 0.0 && p <= 1.0);
            img[y, x] = mixColors(col, img[y, x], p);
        };
    } else {
        //plot = (img, x, y, p, col) {
        plot = (ref img, x, y, p, col) {
            assert(p >= 0.0 && p <= 1.0);
            img[x, y] = mixColors(col, img[x, y], p);
        };
    }

    if (x2 < x1) {
        swap(x1, x2);
        swap(y1, y2);
    }
    immutable gradient = dy / dx;

    // Handle first endpoint.
    auto xEnd = round(x1);
    auto yEnd = y1 + gradient * (xEnd - x1);
    auto xGap = rfpart(x1 + 0.5);
    // This will be used in the main loop.
    immutable xpxl1 = cast(int)xEnd;
    immutable ypxl1 = cast(int)yEnd.floor;
    plot(img, xpxl1, ypxl1, rfpart(yEnd) * xGap, color);
    plot(img, xpxl1, ypxl1 + 1, fpart(yEnd) * xGap, color);
    // First y-intersection for the main loop.
    auto yInter = yEnd + gradient;

    // Handle second endpoint.
    xEnd = round(x2);
    yEnd = y2 + gradient * (xEnd - x2);
    xGap = fpart(x2 + 0.5);
    // This will be used in the main loop.
    immutable xpxl2 = cast(int)xEnd;
    immutable ypxl2 = cast(int)yEnd.floor;
    plot(img, xpxl2, ypxl2, rfpart(yEnd) * xGap, color);
    plot(img, xpxl2, ypxl2 + 1, fpart(yEnd) * xGap, color);

    // Main loop.
    foreach (immutable x; xpxl1 + 1 .. xpxl2) {
        plot(img, x, cast(int)yInter.floor, rfpart(yInter), color);
        plot(img, x, cast(int)yInter.floor + 1, fpart(yInter), color);
        yInter += gradient;
    }
}

void main() {
    auto im1 = new Image!Gray(400, 300);
    im1.clear(Gray.white);
    im1.aaLine(7.4, 12.3, 307, 122.5, Gray.black);
    im1.aaLine(177.4, 12.3, 127, 222.5, Gray.black);
    im1.savePGM("xiaolin_lines1.pgm");

    auto im2 = new Image!RGB(400, 300);
    im2.clear(RGB(0, 255, 0));
    immutable red = RGB(255, 0, 0);
    im2.aaLine(7.4, 12.3, 307, 122.5, red);
    im2.aaLine(177.4, 12.3, 127, 222.5, red);
    im2.savePPM6("xiaolin_lines2.ppm");
}


program Write_entire_file;

{$APPTYPE CONSOLE}

uses
  System.IoUtils;

begin
  TFile.WriteAllText('filename.txt', 'This file contains a string.');
end.


import system'io;

public program()
{
    File.assign("filename.txt").saveContent("This file contains a string.")
}


System.IO.File.WriteAllText("filename.txt", "This file contains a string.")


USING: io.encodings.utf8 io.files ;
"this is a string" "file.txt" utf8 set-file-contents


      OPEN (F,FILE="SomeFileName.txt",STATUS="REPLACE")
      WRITE (F,*) "Whatever you like."
      WRITE (F) BIGARRAY


program overwriteFile(input, output, stdErr);
{$mode objFPC} // for exception treatment
uses
	sysUtils; // for applicationName, getTempDir, getTempFileName
	// also: importing sysUtils converts all run-time errors to exceptions
resourcestring
	hooray = 'Hello world!';
var
	FD: text;
begin
	// on a Debian GNU/Linux distribution,
	// this will write to /tmp/overwriteFile00000.tmp (or alike)
	assign(FD, getTempFileName(getTempDir(false), applicationName()));
	try
		rewrite(FD); // could fail, if user has no permission to write
		writeLn(FD, hooray);
	finally
		close(FD);
	end;
end.


' version 21-06-2015
' compile with: fbc -s console or fbc -s gui
' Xiaolin Wu’s line-drawing algorithm
'shared var and macro's

Dim Shared As UInteger wu_color

#Macro ipart(x)
Int(x)             ' integer part
#EndMacro

#Macro round(x)
Int((x) + .5)      ' round off
#EndMacro

#Macro fpart(x)
Frac(x)            ' fractional part
#EndMacro

#Macro rfpart(x)
' 1 - Frac(x)    ' seems to give problems for very small x
IIf(1 - Frac(x) >= 1, 1, 1 - Frac(x))
#EndMacro

#Macro plot(x, y , c)
' use the alpha channel to set the amount of color
PSet(x,y), wu_color Or (Int(c * 255)) Shl 24
#EndMacro

Sub drawline(x0 As Single, y0 As Single, x1 As Single, y1 As Single,_
    col As UInteger = RGB(255,255,255))

    wu_color = col And &HFFFFFF ' strip off the alpha channel information

    Dim As Single gradient
    Dim As Single xend, yend, xgap, intery
    Dim As UInteger xpxl1, ypxl1, xpxl2, ypxl2, x
    Dim As Integer steep = Abs(y1 - y0) > Abs(x1 - x0) ' boolean

    If steep Then
        Swap x0, y0
        Swap x1, y1
    End If

    If x0 > x1 Then
        Swap x0, x1
        Swap y0, y1
    End If

    gradient = (y1 - y0) / (x1 - x0)

    ' first endpoint
    ' xend = round(x0)
    xend = ipart(x0)
    yend = y0 + gradient * (xend - x0)
    xgap = rfpart(x0 + .5)
    xpxl1 = xend              ' this will be used in the main loop
    ypxl1 = ipart(yend)
    If steep Then
        plot(ypxl1,   xpxl1, rfpart(yend) * xgap)
        plot(ypxl1+1, xpxl1,  fpart(yend) * xgap)
    Else
        plot(xpxl1, ypxl1,   rfpart(yend) * xgap)
        plot(xpxl1, ypxl1+1,  fpart(yend) * xgap)
    End If
    intery = yend + gradient  ' first y-intersecction for the main loop

    ' handle second endpoint
    ' xend = round(x1)
    xend = ipart(x1)
    yend = y1 + gradient * (xend - x1)
    xgap = fpart(x1 + .5)
    xpxl2 = xend              ' this will be used in the main loop
    ypxl2 = ipart(yend)
    If steep Then
        plot(ypxl2,   xpxl2, rfpart(yend) * xgap)
        plot(ypxl2+1, xpxl2,  fpart(yend) * xgap)
    Else
        plot(xpxl2, ypxl2,   rfpart(yend) * xgap)
        plot(xpxl2, ypxl2+1,  fpart(yend) * xgap)
    End If

    ' main loop
    If steep Then
        For x = xpxl1 + 1 To xpxl2 - 1
            plot(ipart(intery),   x, rfpart(intery))
            plot(ipart(intery)+1, x,  fpart(intery))
            intery = intery + gradient
        Next
    Else
        For x = xpxl1 + 1 To xpxl2 - 1
            plot(x, ipart(intery),   rfpart(intery))
            plot(x, ipart(intery)+1,  fpart(intery))
            intery = intery + gradient
        Next
    End If

End Sub

' ------=< MAIN >=------

#Define W_  600
#Define H_  600

#Include Once "fbgfx.bi"   ' needed setting the screen attributes
Dim As Integer i
Dim As String fname = __FILE__

ScreenRes W_, H_, 32,, FB.GFX_ALPHA_PRIMITIVES

Randomize Timer

For i = 0 To H_ Step H_\30
    drawline(0, 0, W_, i, Int(Rnd * &HFFFFFF))
Next

For i = 0 To W_ Step W_\30
    drawline(0, 0, i, H_, Int(Rnd * &HFFFFFF))
Next

i = InStr(fname,".bas")
fname = Left(fname, Len(fname)-i+1)
WindowTitle fname + "    hit any key to end program"

While Inkey <> "" : Wend
Sleep
End


' FB 1.05.0 Win64

Open "output.txt" For Output As #1
Print #1, "This is a string"
Close #1


w = new Writer["test.txt"]
w.print["I am the captain now."]
w.close[]


Public Sub Main()

File.Save(User.home &/ "test.txt", "(Over)write a file so that it contains a string.")

End


import "io/ioutil"

func main() {
    ioutil.WriteFile("path/to/your.file", []byte("data"), 0644)
}


 new File("myFile.txt").text = """a big string
that can be
splitted over lines
"""


main :: IO ( )
main = do
   putStrLn "Enter a string!"
   str <- getLine
   putStrLn "Where do you want to store this string ?"
   myFile <- getLine
   appendFile myFile str


import java.io.*;

public class Test {

    public static void main(String[] args) throws IOException {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"))) {
            bw.write("abc");
        }
    }
}


\ Load the XML text into the var 'x':
quote *
<Students>
  <Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
  <Student Name="Bob" Gender="M"  DateOfBirth="1990-03-04" />
  <Student Name="Chad" Gender="M"  DateOfBirth="1991-05-06" />
  <Student Name="Dave" Gender="M"  DateOfBirth="1992-07-08">
    <Pet Type="dog" Name="Rover" />
  </Student>
  <Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
* xml:parse var, x

\ print only xml nodes which have a tag of 'Student' and whose attributes are not empty
: .xml \ xml --
	xml:[email protected] "Student" s:cmp if drop ;; then
	xml:attrs null? if drop ;; then

	"Name" m:@ . cr drop ;

\ Iterate over the XML document in the var 'x'
x @ ' .xml xml:each bye


package raster

import "math"

func ipart(x float64) float64 {
    return math.Floor(x)
}

func round(x float64) float64 {
    return ipart(x + .5)
}

func fpart(x float64) float64 {
    return x - ipart(x)
}

func rfpart(x float64) float64 {
    return 1 - fpart(x)
}

// AaLine plots anti-aliased line by Xiaolin Wu's line algorithm.
func (g *Grmap) AaLine(x1, y1, x2, y2 float64) {
    // straight translation of WP pseudocode
    dx := x2 - x1
    dy := y2 - y1
    ax := dx
    if ax < 0 {
        ax = -ax
    }
    ay := dy
    if ay < 0 {
        ay = -ay
    }
    // plot function set here to handle the two cases of slope
    var plot func(int, int, float64)
    if ax < ay {
        x1, y1 = y1, x1
        x2, y2 = y2, x2
        dx, dy = dy, dx
        plot = func(x, y int, c float64) {
            g.SetPx(y, x, uint16(c*math.MaxUint16))
        }
    } else {
        plot = func(x, y int, c float64) {
            g.SetPx(x, y, uint16(c*math.MaxUint16))
        }
    }
    if x2 < x1 {
        x1, x2 = x2, x1
        y1, y2 = y2, y1
    }
    gradient := dy / dx

    // handle first endpoint
    xend := round(x1)
    yend := y1 + gradient*(xend-x1)
    xgap := rfpart(x1 + .5)
    xpxl1 := int(xend) // this will be used in the main loop
    ypxl1 := int(ipart(yend))
    plot(xpxl1, ypxl1, rfpart(yend)*xgap)
    plot(xpxl1, ypxl1+1, fpart(yend)*xgap)
    intery := yend + gradient // first y-intersection for the main loop

    // handle second endpoint
    xend = round(x2)
    yend = y2 + gradient*(xend-x2)
    xgap = fpart(x2 + 0.5)
    xpxl2 := int(xend) // this will be used in the main loop
    ypxl2 := int(ipart(yend))
    plot(xpxl2, ypxl2, rfpart(yend)*xgap)
    plot(xpxl2, ypxl2+1, fpart(yend)*xgap)

    // main loop
    for x := xpxl1 + 1; x <= xpxl2-1; x++ {
        plot(x, int(ipart(intery)), rfpart(intery))
        plot(x, int(ipart(intery))+1, fpart(intery))
        intery = intery + gradient
    }
}


function writeFile(filename, data)
	f = open(filename, "w")
	write(f, data)
	close(f)
end

writeFile("test.txt", "Hi there.")


// version 1.1.2

import java.io.File

fun main(args: Array<String>) {
    val text = "empty vessels make most noise"
    File("output.txt").writeText(text)
}


----------------------------------------
-- Saves string as file
-- @param {string} tFile
-- @param {string} tString
-- @return {bool} success
----------------------------------------
on writeFile (tFile, tString)
  fp = xtra("fileIO").new()
  fp.openFile(tFile, 2)
  err = fp.status()
  if not (err) then fp.delete()
  else if (err and not (err = -37)) then return false
  fp.createFile(tFile)
  if fp.status() then return false
  fp.openFile(tFile, 2)
  if fp.status() then return false
  fp.writeString(tString)
  fp.closeFile()
  return true
end


put "this is a string" into URL "file:~/Desktop/TestFile.txt"


function writeFile (filename, data)
	local f = io.open(filename, 'w')
	f:write(data)
	f:close()
end

writeFile("stringFile.txt", "Mmm... stringy.")


import Nanoquery.IO

new(File, fname).create().write(string)


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program inputXml64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/* program constantes    */
.equ XML_ELEMENT_NODE,          1
.equ    XML_ATTRIBUTE_NODE,     2
 .equ   XML_TEXT_NODE,          3
.equ    XML_CDATA_SECTION_NODE, 4
.equ    XML_ENTITY_REF_NODE,    5
.equ    XML_ENTITY_NODE,        6
.equ    XML_PI_NODE,            7
.equ    XML_COMMENT_NODE,       8
.equ    XML_DOCUMENT_NODE,      9
.equ    XML_DOCUMENT_TYPE_NODE, 10
.equ    XML_DOCUMENT_FRAG_NODE, 11
.equ    XML_NOTATION_NODE,      12
.equ    XML_HTML_DOCUMENT_NODE, 13
.equ    XML_DTD_NODE,           14
.equ    XML_ELEMENT_DECL,       15
.equ    XML_ATTRIBUTE_DECL,     16
.equ    XML_ENTITY_DECL,        17
.equ    XML_NAMESPACE_DECL,     18
.equ    XML_XINCLUDE_START,     19
.equ    XML_XINCLUDE_END,       20
.equ    XML_DOCB_DOCUMENT_NODE, 21

/*******************************************/
/* Structures                               */
/********************************************/
/* structure xmlNode  */
    .struct  0
xmlNode_private:                         // application data
    .struct  xmlNode_private + 8
xmlNode_type:                            // type number, must be second !
    .struct  xmlNode_type + 8
xmlNode_name:                            // the name of the node, or the entity
    .struct  xmlNode_name + 8
xmlNode_children:                        // parent->childs link
    .struct  xmlNode_children + 8
xmlNode_last:                            // last child link
    .struct  xmlNode_last + 8
xmlNode_parent:                          // child->parent link
    .struct  xmlNode_parent + 8
xmlNode_next:                            // next sibling link
    .struct  xmlNode_next + 8
xmlNode_prev:                            // previous sibling link
    .struct  xmlNode_prev + 8
xmlNode_doc:                             // the containing document
    .struct  xmlNode_doc + 8
xmlNode_ns:                              // pointer to the associated namespace
    .struct  xmlNode_ns + 8
xmlNode_content:                         // the content
    .struct  xmlNode_content + 8
xmlNode_properties:                      // properties list
    .struct  xmlNode_properties + 8
xmlNode_nsDef:                           // namespace definitions on this node
    .struct  xmlNode_nsDef + 8
xmlNode_psvi:                            // for type/PSVI informations
    .struct  xmlNode_psvi + 8
xmlNode_line:                            // line number
    .struct  xmlNode_line + 4
xmlNode_extra:                           // extra data for XPath/XSLT
    .struct  xmlNode_extra + 4
xmlNode_fin:

/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessEndpgm:      .asciz "Normal end of program.\n"
szMessError:       .asciz "Error detected !!!!. \n"
szText:            .ascii "<Students>\n"
                   .ascii "<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n"
                   .ascii "<Student Name=\"Bob\" Gender=\"M\"  DateOfBirth=\"1990-03-04\" />\n"
                   .ascii "<Student Name=\"Chad\" Gender=\"M\"  DateOfBirth=\"1991-05-06\" />\n"
                   .ascii "<Student Name=\"Dave\" Gender=\"M\"  DateOfBirth=\"1992-07-08\">\n"
                   .ascii "<Pet Type=\"dog\" Name=\"Rover\" />\n"
                   .ascii "</Student>\n"
                   .ascii "<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />\n"
                   .asciz "</Students>"
.equ LGSZTEXT,   . - szText            // compute text size (. is current address)

szLibExtract:      .asciz "Student"
szLibName:         .asciz "Name"
szCarriageReturn:  .asciz "\n"
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
.align 4

/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                     // entry of program
    ldr x0,qAdrszText                     // text buffer
    mov x1,#LGSZTEXT                      // text size
    mov x2,#0                             // param 3
    mov x3,#0                             // param 4
    mov x4,#0                             // param 5
    bl xmlReadMemory                      // read text in document
    cmp x0,#0                             // error ?
    beq 99f
    mov x19,x0                            // doc address
    mov x0,x19
    bl xmlDocGetRootElement               // search root return in x0
    bl affElement                         // display elements
    mov x0,x19
    bl xmlFreeDoc

    bl xmlCleanupParser
    ldr x0,qAdrszMessEndpgm
    bl affichageMess
    b 100f
99:                                        // error
    ldr x0,qAdrszMessError
    bl affichageMess
100:                                       // standard end of the program
    mov x0,0                               // return code
    mov x8,EXIT                            // request to exit program
    svc 0                                  // perform the system call

qAdrszMessError:          .quad szMessError
qAdrszMessEndpgm:         .quad szMessEndpgm
qAdrszText:               .quad szText
qAdrszCarriageReturn:     .quad szCarriageReturn

/******************************************************************/
/*     display name of student                             */
/******************************************************************/
/* x0 contains the address of node */
affElement:
    stp x24,lr,[sp,-16]!               // save  registers
    mov x24,x0                         // save node
1:
    ldr x12,[x24,#xmlNode_type]         // type ?
    cmp x12,#XML_ELEMENT_NODE
    bne 2f
    ldr x0,[x24,#xmlNode_name]         // name = "Student" ?
    ldr x1,qAdrszLibExtract
    bl comparString
    cmp x0,#0
    bne 2f                            // no
    mov x0,x24
    ldr x1,qAdrszLibName              // load property of "Name"
    bl xmlHasProp
    cmp x0,#0
    beq 2f
    ldr x1,[x0,#xmlNode_children]     // children node of property name
    ldr x0,[x1,#xmlNode_content]      // and address of content
    bl affichageMess                  // for display
    ldr x0,qAdrszCarriageReturn
    bl affichageMess
2:
    ldr x0,[x24,#xmlNode_children]     // node have children ?
    cbz x0,3f
    bl affElement                   // yes -> call procedure
3:
    ldr x1,[x24,#xmlNode_next]         // other element ?
    cmp x1,#0
    beq 100f                          // no -> end procedure

    mov x24,x1                         // else loop with next element
    b 1b

100:
    ldp x24,lr,[sp],16                 // restaur  2 registers
    ret                               // return to address lr x30
qAdrszLibName:              .quad szLibName
qAdrszLibExtract:           .quad szLibExtract
/************************************/
/* Strings comparaison              */
/************************************/
/* x0 et x1 contains strings addresses */
/* x0 return 0 dans x0 if equal */
/* return -1 if string x0 < string x1 */
/* return 1  if string x0 > string x1 */
comparString:
    stp x2,lr,[sp,-16]!            // save  registers
    stp x3,x4,[sp,-16]!            // save  registers
    mov x2,#0                   // indice
1:
    ldrb w3,[x0,x2]             // one byte string 1
    ldrb w4,[x1,x2]             // one byte string 2
    cmp w3,w4
    blt 2f                      // less
    bgt 3f                      // greather
    cmp w3,#0                   // 0 final
    beq 4f                      // equal and end
    add x2,x2,#1                //
    b 1b                        // else loop
2:
    mov x0,#-1                  // less
    b 100f
3:
    mov x0,#1                   // greather
    b 100f
4:
    mov x0,#0                   // equal
    b 100f
100:
    ldp x3,x4,[sp],16           // restaur  2 registers
    ldp x2,lr,[sp],16           // restaur  2 registers
    ret                         // return to address lr x30
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


package
{
    import flash.display.Sprite;

    public class XMLReading extends Sprite
    {
        public function XMLReading()
        {
            var xml:XML = <Students>
                            <Student Name="April" />
                            <Student Name="Bob" />
                            <Student Name="Chad" />
                            <Student Name="Dave" />
                            <Student Name="Emily" />
                          </Students>;
            for each(var node:XML in xml..Student)
            {
                trace(node.@Name);
            }
        }
    }
}


with Sax.Readers;
with Input_Sources.Strings;
with Unicode.CES.Utf8;
with My_Reader;

procedure Extract_Students is
   Sample_String : String :=
"<Students>" &
   "<Student Name=""April"" Gender=""F"" DateOfBirth=""1989-01-02"" />" &
   "<Student Name=""Bob"" Gender=""M"" DateOfBirth=""1990-03-04"" />" &
   "<Student Name=""Chad"" Gender=""M"" DateOfBirth=""1991-05-06"" />" &
   "<Student Name=""Dave"" Gender=""M"" DateOfBirth=""1992-07-08"">" &
      "<Pet Type=""dog"" Name=""Rover"" />" &
   "</Student>" &
   "<Student DateOfBirth=""1993-09-10"" Gender=""F"" Name=""Émily"" />" &
"</Students>";
   Reader : My_Reader.Reader;
   Input : Input_Sources.Strings.String_Input;
begin
   Input_Sources.Strings.Open (Sample_String, Unicode.CES.Utf8.Utf8_Encoding, Input);
   My_Reader.Parse (Reader, Input);
   Input_Sources.Strings.Close (Input);
end Extract_Students;


{-# LANGUAGE ScopedTypeVariables #-}

module Main (main) where

import Codec.Picture (writePng)
import Codec.Picture.Types (Image, MutableImage(..), Pixel, PixelRGB8(..), createMutableImage, unsafeFreezeImage, writePixel)
import Control.Monad (void)
import Control.Monad.Primitive (PrimMonad, PrimState)
import Data.Foldable (foldlM)

type MImage m px = MutableImage (PrimState m) px

-- | Create an image given a function to apply to an empty mutable image
withMutableImage
    :: (Pixel px, PrimMonad m)
    => Int                      -- ^ image width
    -> Int                      -- ^ image height
    -> px                       -- ^ background colour
    -> (MImage m px -> m ())    -- ^ function to apply to mutable image
    -> m (Image px)             -- ^ action
withMutableImage w h px f = createMutableImage w h px >>= \m -> f m >> unsafeFreezeImage m

-- | Plot a pixel at the given point in the given colour
plot
    :: (Pixel px, PrimMonad m)
    => MImage m px  -- ^ mutable image
    -> Int          -- ^ x-coordinate of point
    -> Int          -- ^ y-coordinate of point
    -> px           -- ^ colour
    -> m ()         -- ^ action
plot = writePixel

-- | Draw an antialiased line from first point to second point in given colour
drawAntialiasedLine
    :: forall px m . (Pixel px, PrimMonad m)
    => MImage m px      -- ^ mutable image
    -> Int              -- ^ x-coordinate of first point
    -> Int              -- ^ y-coordinate of first point
    -> Int              -- ^ x-coordinate of second point
    -> Int              -- ^ y-coordinate of second point
    -> (Double -> px)   -- ^ colour generator function
    -> m ()             -- ^ action
drawAntialiasedLine m p1x p1y p2x p2y colour = do
    let steep = abs (p2y - p1y) > abs (p2x - p1x)
        ((p3x, p4x), (p3y, p4y)) = swapIf steep ((p1x, p2x), (p1y, p2y))
        ((ax, ay), (bx, by)) = swapIf (p3x > p4x) ((p3x, p3y), (p4x, p4y))
        dx = bx - ax
        dy = by - ay
        gradient = if dx == 0 then 1.0 else fromIntegral dy / fromIntegral dx

    -- handle first endpoint
    let xpxl1 = ax -- round (fromIntegral ax)
        yend1 = fromIntegral ay + gradient * fromIntegral (xpxl1 - ax)
        xgap1 = rfpart (fromIntegral ax + 0.5)
    endpoint steep xpxl1 yend1 xgap1

    -- handle second endpoint
    let xpxl2 = bx -- round (fromIntegral bx)
        yend2 = fromIntegral by + gradient * fromIntegral (xpxl2 - bx)
        xgap2 = fpart (fromIntegral bx + 0.5)
    endpoint steep xpxl2 yend2 xgap2

    -- main loop
    let intery = yend1 + gradient
    void $ if steep
        then foldlM (\i x -> do
            plot m (ipart i) x (colour (rfpart i))
            plot m (ipart i + 1) x (colour (fpart i))
            pure $ i + gradient) intery [xpxl1 + 1..xpxl2 - 1]
        else foldlM (\i x -> do
            plot m x (ipart i) (colour (rfpart i))
            plot m x (ipart i + 1) (colour (fpart i))
            pure $ i + gradient) intery [xpxl1 + 1..xpxl2 - 1]

    where
        endpoint :: Bool -> Int -> Double -> Double -> m ()
        endpoint True xpxl yend xgap = do
            plot m ypxl xpxl (colour (rfpart yend * xgap))
            plot m (ypxl + 1) xpxl (colour (fpart yend * xgap))
            where ypxl = ipart yend
        endpoint False xpxl yend xgap = do
            plot m xpxl ypxl (colour (rfpart yend * xgap))
            plot m xpxl (ypxl + 1) (colour (fpart yend * xgap))
            where ypxl = ipart yend

swapIf :: Bool -> (a, a) -> (a, a)
swapIf False p = p
swapIf True (x, y) = (y, x)

ipart :: Double -> Int
ipart = truncate

fpart :: Double -> Double
fpart x
    | x > 0 = x - temp
    | otherwise = x - (temp + 1)
    where temp = fromIntegral (ipart x)

rfpart :: Double -> Double
rfpart x = 1 - fpart x

main :: IO ()
main = do
    -- We start and end the line with sufficient clearance from the edge of the
    -- image to be able to see the endpoints
    img <- withMutableImage 640 480 (PixelRGB8 0 0 0) $ \m@(MutableImage w h _) ->
            drawAntialiasedLine m 2 2 (w - 2) (h - 2)
            (\brightness -> let level = round (brightness * 255) in PixelRGB8 level level level)

    -- Write it out to a file on disc
    writePng "xiaolin-wu-algorithm.png" img


writeFile("filename.txt", "An arbitrary string")


use System.IO.File;

class WriteFile {
  function : Main(args : String[]) ~ Nil {
    writer ← FileWriter→New("test.txt");
    leaving {
      writer→Close();
    };
    writer→WriteString("this is a test string");
  }
}


let write_file filename s =
  let oc = open_out filename in
  output_string oc s;
  close_out oc;
;;

let () =
  let filename = "test.txt" in
  let s = String.init 26 (fun i -> char_of_int (i + int_of_char 'A')) in
  write_file filename s


{$ifDef FPC}{$mode ISO}{$endIf}
program overwriteFile(FD);
begin
	writeLn(FD, 'Whasup?');
	close(FD);
end.


use File::Slurper 'write_text';
write_text($filename, $data);


without js -- (file i/o)
integer res = write_lines("file.txt",{"line 1\nline 2"})
if res=-1 then crash("error") end if


import xml

var s = openin ("t.xml")
var tree = XML.parseStream (s)

foreach node tree {
    if (node.name == "Students") {
        foreach studentnode node {
            if (studentnode.name == "Student") {
                println (studentnode.getAttribute ("Name"))
            }
        }
    }
}


/* ARM assembly Raspberry PI  */
/*  program inputXml.s   */

/* Constantes    */
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ WRITE,  4     @ Linux syscall
.equ XML_ELEMENT_NODE,          1
.equ    XML_ATTRIBUTE_NODE,     2
 .equ   XML_TEXT_NODE,          3
.equ    XML_CDATA_SECTION_NODE, 4
.equ    XML_ENTITY_REF_NODE,    5
.equ    XML_ENTITY_NODE,        6
.equ    XML_PI_NODE,            7
.equ    XML_COMMENT_NODE,       8
.equ    XML_DOCUMENT_NODE,      9
.equ    XML_DOCUMENT_TYPE_NODE, 10
.equ   XML_DOCUMENT_FRAG_NODE,  11
.equ    XML_NOTATION_NODE,      12
.equ    XML_HTML_DOCUMENT_NODE, 13
.equ    XML_DTD_NODE,           14
.equ    XML_ELEMENT_DECL,       15
.equ    XML_ATTRIBUTE_DECL,     16
.equ    XML_ENTITY_DECL,        17
.equ    XML_NAMESPACE_DECL,     18
.equ    XML_XINCLUDE_START,     19
.equ    XML_XINCLUDE_END,       20
.equ    XML_DOCB_DOCUMENT_NODE  21

/*******************************************/
/* Structures                               */
/********************************************/
/* structure linkedlist*/
    .struct  0
xmlNode_private:                         @ application data
    .struct  xmlNode_private + 4
xmlNode_type:                            @ type number, must be second !
    .struct  xmlNode_type + 4
xmlNode_name:                            @ the name of the node, or the entity
    .struct  xmlNode_name + 4
xmlNode_children:                        @ parent->childs link
    .struct  xmlNode_children + 4
xmlNode_last:                            @ last child link
    .struct  xmlNode_last + 4
xmlNode_parent:                          @ child->parent link
    .struct  xmlNode_parent + 4
xmlNode_next:                            @ next sibling link
    .struct  xmlNode_next + 4
xmlNode_prev:                            @ previous sibling link
    .struct  xmlNode_prev + 4
xmlNode_doc:                             @ the containing document
    .struct  xmlNode_doc + 4
xmlNode_ns:                              @ pointer to the associated namespace
    .struct  xmlNode_ns + 4
xmlNode_content:                         @ the content
    .struct  xmlNode_content + 4
xmlNode_properties:                      @ properties list
    .struct  xmlNode_properties + 4
xmlNode_nsDef:                           @ namespace definitions on this node
    .struct  xmlNode_nsDef + 4
xmlNode_psvi:                            @ for type/PSVI informations
    .struct  xmlNode_psvi + 4
xmlNode_line:                            @ line number
    .struct  xmlNode_line + 4
xmlNode_extra:                           @ extra data for XPath/XSLT
    .struct  xmlNode_extra + 4
xmlNode_fin:

/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessEndpgm:      .asciz "Normal end of program.\n"
szMessError:       .asciz "Error detected !!!!. \n"
szText:            .ascii "<Students>\n"
                   .ascii "<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n"
                   .ascii "<Student Name=\"Bob\" Gender=\"M\"  DateOfBirth=\"1990-03-04\" />\n"
                   .ascii "<Student Name=\"Chad\" Gender=\"M\"  DateOfBirth=\"1991-05-06\" />\n"
                   .ascii "<Student Name=\"Dave\" Gender=\"M\"  DateOfBirth=\"1992-07-08\">\n"
                   .ascii  "<Pet Type=\"dog\" Name=\"Rover\" />\n"
                   .ascii "</Student>\n"
                   .ascii "<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />\n"
                   .asciz "</Students>"
.equ LGSZTEXT,   . - szText            @ compute text size (. is current address)

szLibExtract:      .asciz "Student"
szLibName:         .asciz "Name"
szCarriageReturn:  .asciz "\n"
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
.align 4

/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                     @ entry of program
    ldr r0,iAdrszText                     @ text buffer
    mov r1,#LGSZTEXT                      @ text size
    mov r2,#0                             @ param 3
    mov r3,#0                             @ param 4
    mov r4,#0                             @ param 5
    sub sp,#4                             @ stack assignement
    push {r4}                             @ param 5 on stack
    bl xmlReadMemory                      @ read text in document
    add sp,#8                             @ stack assignement for 1 push and align stack
    cmp r0,#0                             @ error ?
    beq 1f
    mov r9,r0                             @ doc address
    mov r0,r9
    bl xmlDocGetRootElement               @ search root return in r0
    bl affElement                         @ display elements

    mov r0,r9
    bl xmlFreeDoc
1:
    bl xmlCleanupParser
    ldr r0,iAdrszMessEndpgm
    bl affichageMess
    b 100f
99:
    @ error
    ldr r0,iAdrszMessError
    bl affichageMess
100:                                       @ standard end of the program
    mov r0, #0                             @ return code
    mov r7, #EXIT                          @ request to exit program
    svc #0                                 @ perform the system call

iAdrszMessError:          .int szMessError
iAdrszMessEndpgm:         .int szMessEndpgm
iAdrszText:               .int szText
iAdrszCarriageReturn:     .int szCarriageReturn

/******************************************************************/
/*     display name of student                             */
/******************************************************************/
/* r0 contains the address of node */
affElement:
    push {r1-r4,lr}                   @ save  registres
    mov r4,r0                         @ save node
1:
    ldr r2,[r4,#xmlNode_type]         @ type ?
    cmp r2,#XML_ELEMENT_NODE
    bne 2f
    ldr r0,[r4,#xmlNode_name]         @ name = "Student" ?
    ldr r1,iAdrszLibExtract
    bl comparString
    cmp r0,#0
    bne 2f                            @ no
    mov r0,r4
    ldr r1,iAdrszLibName              @ load property of "Name"
    bl xmlHasProp
    cmp r0,#0
    beq 2f
    ldr r1,[r0,#xmlNode_children]     @ children node of property name
    ldr r0,[r1,#xmlNode_content]      @ and address of content
    bl affichageMess                  @ for display
    ldr r0,iAdrszCarriageReturn
    bl affichageMess
2:
    ldr r0,[r4,#xmlNode_children]     @ node have children ?
    cmp r0,#0
    blne affElement                   @ yes -> call procedure

    ldr r1,[r4,#xmlNode_next]         @ other element ?
    cmp r1,#0
    beq 100f                          @ no -> end procedure

    mov r4,r1                         @ else loop with next element
    b 1b

100:
    pop {r1-r4,lr}                    @ restaur registers */
    bx lr                             @ return
iAdrszLibName:              .int szLibName
iAdrszLibExtract:           .int szLibExtract
/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}                   @ save  registres
    mov r2,#0                               @ counter length
1:                                          @ loop length calculation
    ldrb r1,[r0,r2]                         @ read octet start position + index
    cmp r1,#0                               @ if 0 its over
    addne r2,r2,#1                          @ else add 1 in the length
    bne 1b                                  @ and loop
                                            @ so here r2 contains the length of the message
    mov r1,r0                               @ address message in r1
    mov r0,#STDOUT                          @ code to write to the standard output Linux
    mov r7, #WRITE                          @ code call system "write"
    svc #0                                  @ call systeme
    pop {r0,r1,r2,r7,lr}                    @ restaur registers */
    bx lr                                   @ return
/******************************************************************/
/*     Converting a register to a decimal                                 */
/******************************************************************/
/* r0 contains value and r1 address area   */
.equ LGZONECAL,   10
conversion10:
    push {r1-r4,lr}                         @ save registers
    mov r3,r1
    mov r2,#LGZONECAL
1:                                          @ start loop
    bl divisionpar10                        @ r0 <- dividende. quotient ->r0 reste -> r1
    add r1,#48                              @ digit
    strb r1,[r3,r2]                         @ store digit on area
    cmp r0,#0                               @ stop if quotient = 0
    subne r2,#1                               @ previous position
    bne 1b                                  @ else loop
                                            @ end replaces digit in front of area
    mov r4,#0
2:
    ldrb r1,[r3,r2]
    strb r1,[r3,r4]                         @ store in area begin
    add r4,#1
    add r2,#1                               @ previous position
    cmp r2,#LGZONECAL                       @ end
    ble 2b                                  @ loop
    mov r1,#' '
3:
    strb r1,[r3,r4]
    add r4,#1
    cmp r4,#LGZONECAL                       @ end
    ble 3b
100:
    pop {r1-r4,lr}                          @ restaur registres
    bx lr                                   @return
/***************************************************/
/*   division par 10   signé                       */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and   http://www.hackersdelight.org/            */
/***************************************************/
/* r0 dividende   */
/* r0 quotient */
/* r1 remainder  */
divisionpar10:
  /* r0 contains the argument to be divided by 10 */
    push {r2-r4}                           @ save registers  */
    mov r4,r0
    mov r3,#0x6667                         @ r3 <- magic_number  lower
    movt r3,#0x6666                        @ r3 <- magic_number  upper
    smull r1, r2, r3, r0                   @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0)
    mov r2, r2, ASR #2                     @ r2 <- r2 >> 2
    mov r1, r0, LSR #31                    @ r1 <- r0 >> 31
    add r0, r2, r1                         @ r0 <- r2 + r1
    add r2,r0,r0, lsl #2                   @ r2 <- r0 * 5
    sub r1,r4,r2, lsl #1                   @ r1 <- r4 - (r2 * 2)  = r4 - (r0 * 10)
    pop {r2-r4}
    bx lr                                  @ return
/************************************/
/* comparaison de chaines           */
/************************************/
/* r0 et r1 contiennent les adresses des chaines */
/* retour 0 dans r0 si egalite */
/* retour -1 si chaine r0 < chaine r1 */
/* retour 1  si chaine r0> chaine r1 */
comparString:
    push {r1-r4}                @ save des registres
    mov r2,#0                   @ indice
1:
    ldrb r3,[r0,r2]             @ octet chaine 1
    ldrb r4,[r1,r2]             @ octet chaine 2
    cmp r3,r4
    movlt r0,#-1                @ plus petite
    movgt r0,#1                 @ plus grande
    bne 100f                    @ pas egaux
    cmp r3,#0                   @ 0 final
    moveq r0,#0                 @ egalite
    beq 100f                    @ c est la fin
    add r2,r2,#1                @ sinon plus 1 dans indice
    b 1b                        @ et boucle
100:
    pop {r1-r4}
    bx lr


load'gl2'
coinsert'jgl2'

drawpt=:4 :0"0 1
   glrgb <.(-.x)*255 255 255
   glpixel y
)

drawLine=:3 :0 NB. drawline x1,y1,x2,y2
   pts=. 2 2$y
   isreversed=. </ |d=. -~/pts
   r=. |.^:isreversed"1
   pts=. /:~ pts \:"1 |d
   gradient=. %~/ (\:|)d

   'x y'=. |:pts
   xend=. <.0.5+ x
   yend=. y + gradient* xend-x
   xgap=. -.1|x+0.5

   n=. i. >: -~/ xend
   'xlist ylist'=. (n*/~1,gradient) + ({.xend),({.yend)
   weights=. ((2&}.,~ xgap*2&{.)&.(_1&|.) (,.~-.) 1|ylist)
   weights (drawpt r)"1 2 (,:+&0 1)"1 xlist,.<.ylist
)


import java.awt.*;
import static java.lang.Math.*;
import javax.swing.*;

public class XiaolinWu extends JPanel {

    public XiaolinWu() {
        Dimension dim = new Dimension(640, 640);
        setPreferredSize(dim);
        setBackground(Color.white);
    }

    void plot(Graphics2D g, double x, double y, double c) {
        g.setColor(new Color(0f, 0f, 0f, (float)c));
        g.fillOval((int) x, (int) y, 2, 2);
    }

    int ipart(double x) {
        return (int) x;
    }

    double fpart(double x) {
        return x - floor(x);
    }

    double rfpart(double x) {
        return 1.0 - fpart(x);
    }

    void drawLine(Graphics2D g, double x0, double y0, double x1, double y1) {

        boolean steep = abs(y1 - y0) > abs(x1 - x0);
        if (steep)
            drawLine(g, y0, x0, y1, x1);

        if (x0 > x1)
            drawLine(g, x1, y1, x0, y0);

        double dx = x1 - x0;
        double dy = y1 - y0;
        double gradient = dy / dx;

        // handle first endpoint
        double xend = round(x0);
        double yend = y0 + gradient * (xend - x0);
        double xgap = rfpart(x0 + 0.5);
        double xpxl1 = xend; // this will be used in the main loop
        double ypxl1 = ipart(yend);

        if (steep) {
            plot(g, ypxl1, xpxl1, rfpart(yend) * xgap);
            plot(g, ypxl1 + 1, xpxl1, fpart(yend) * xgap);
        } else {
            plot(g, xpxl1, ypxl1, rfpart(yend) * xgap);
            plot(g, xpxl1, ypxl1 + 1, fpart(yend) * xgap);
        }

        // first y-intersection for the main loop
        double intery = yend + gradient;

        // handle second endpoint
        xend = round(x1);
        yend = y1 + gradient * (xend - x1);
        xgap = fpart(x1 + 0.5);
        double xpxl2 = xend; // this will be used in the main loop
        double ypxl2 = ipart(yend);

        if (steep) {
            plot(g, ypxl2, xpxl2, rfpart(yend) * xgap);
            plot(g, ypxl2 + 1, xpxl2, fpart(yend) * xgap);
        } else {
            plot(g, xpxl2, ypxl2, rfpart(yend) * xgap);
            plot(g, xpxl2, ypxl2 + 1, fpart(yend) * xgap);
        }

        // main loop
        for (double x = xpxl1 + 1; x <= xpxl2 - 1; x++) {
            if (steep) {
                plot(g, ipart(intery), x, rfpart(intery));
                plot(g, ipart(intery) + 1, x, fpart(intery));
            } else {
                plot(g, x, ipart(intery), rfpart(intery));
                plot(g, x, ipart(intery) + 1, fpart(intery));
            }
            intery = intery + gradient;
        }
    }

    @Override
    public void paintComponent(Graphics gg) {
        super.paintComponent(gg);
        Graphics2D g = (Graphics2D) gg;

        drawLine(g, 550, 170, 50, 435);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setTitle("Xiaolin Wu's line algorithm");
            f.setResizable(false);
            f.add(new XiaolinWu(), BorderLayout.CENTER);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        });
    }
}


(out "file.txt"
   (prinl "My string") )


Get-Process | Out-File -FilePath .\ProcessList.txt


EnableExplicit

Define fOutput$ = "output.txt" ; enter path of file to create or overwrite
Define str$ = "This string is to be written to the file"

If OpenConsole()
  If CreateFile(0, fOutput$)
    WriteString(0, str$)
    CloseFile(0)
  Else
    PrintN("Error creating or opening output file")
  EndIf
  PrintN("Press any key to close the console")
  Repeat: Delay(10) : Until Inkey() <> ""
  CloseConsole()
EndIf


with open(filename, 'w') as f:
    f.write(data)


#lang racket/base
(with-output-to-file "/tmp/out-file.txt" #:exists 'replace
  (lambda () (display "characters")))


# Program to overwrite an existing file

open(11,FILE="file.txt")
101 format(A)
write(11,101) "Hello World"
close(11)

end


data: {
<Students>
    <Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
    <Student Name="Bob" Gender="M"  DateOfBirth="1990-03-04" />
    <Student Name="Chad" Gender="M"  DateOfBirth="1991-05-06" />
    <Student Name="Dave" Gender="M"  DateOfBirth="1992-07-08">
        <Pet Type="dog" Name="Rover" />
    </Student>
    <Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
}

students: read.xml data
print join.with:"\n" map students 'student -> student\Name


students =
(
<Students>
  <Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
  <Student Name="Bob" Gender="M"  DateOfBirth="1990-03-04" />
  <Student Name="Chad" Gender="M"  DateOfBirth="1991-05-06" />
  <Student Name="Dave" Gender="M"  DateOfBirth="1992-07-08">
    <Pet Type="dog" Name="Rover" />
  </Student>
  <Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
)

quote = " ; "
pos = 1
while, pos := RegExMatch(students, "Name=.(\w+)" . quote . "\sGender"
, name, pos + 1)
names .= name1 . "`n"

msgbox % names


function parse_buf()
{
    if ( match(buffer, /<Student[ \t]+[^>]*Name[ \t]*=[ \t]*"([^"]*)"/, mt) != 0 ) {
      students[mt[1]] = 1
    }
    buffer = ""
}

BEGIN {
  FS=""
  mode = 0
  buffer = ""
  li = 1
}

mode==1 {
  for(i=1; i <= NF; i++) {
    buffer = buffer $i
    if ( $i == ">" ) {
      mode = 0;
      break;
    }
  }
  if ( mode == 0 ) {
    li = i
  } else {
    li = 1
  }
  # let us process the buffer if "complete"
  if ( mode == 0 ) {
    parse_buf()
  }
}

mode==0 {
  for(i=li; i <= NF; i++) {
    if ( $i == "<" ) {
      mode = 1
      break;
    }
  }
  for(j=i; i <= NF; i++) {
    buffer = buffer $i
    if ( $i == ">" ) {
      mode = 0
      parse_buf()
    }
  }
  li = 1
}

END {
  for(k in students) {
    print k
  }
}


using Images

fpart(x) = mod(x, one(x))
rfpart(x) = one(x) - fpart(x)

function drawline!(img::Matrix{Gray{N0f8}}, x0::Integer, y0::Integer, x1::Integer, y1::Integer)
    steep = abs(y1 - y0) > abs(x1 - x0)

    if steep
        x0, y0 = y0, x0
        x1, y1 = y1, x1
    end
    if x0 > x1
        x0, x1 = x1, x0
        y0, y1 = y1, y0
    end

    dx = x1 - x0
    dy = y1 - y0
    grad = dy / dx

    if iszero(dx)
        grad = oftype(grad, 1.0)
    end

    # handle first endpoint
    xend = round(Int, x0)
    yend = y0 + grad * (xend - x0)
    xgap = rfpart(x0 + 0.5)
    xpxl1 = xend
    ypxl1 = floor(Int, yend)

    if steep
        img[ypxl1,   xpxl1] = rfpart(yend) * xgap
        img[ypxl1+1, xpxl1] =  fpart(yend) * xgap
    else
        img[xpxl1, ypxl1  ] = rfpart(yend) * xgap
        img[xpxl1, ypxl1+1] =  fpart(yend) * xgap
    end
    intery = yend + grad # first y-intersection for the main loop

    # handle second endpoint
    xend = round(Int, x1)
    yend = y1 + grad * (xend - x1)
    xgap = fpart(x1 + 0.5)
    xpxl2 = xend
    ypxl2 = floor(Int, yend)
    if steep
        img[ypxl2,   xpxl2] = rfpart(yend) * xgap
        img[ypxl2+1, xpxl2] =  fpart(yend) * xgap
    else
        img[xpxl2, ypxl2  ] = rfpart(yend) * xgap
        img[xpxl2, ypxl2+1] =  fpart(yend) * xgap
    end

    # main loop
    if steep
        for x in xpxl1+1:xpxl2-1
            img[floor(Int, intery),   x] = rfpart(intery)
            img[floor(Int, intery)+1, x] =  fpart(intery)
            intery += grad
        end
    else
        for x in xpxl1+1:xpxl2-1
            img[x, floor(Int, intery)  ] = rfpart(intery)
            img[x, floor(Int, intery)+1] =  fpart(intery)
            intery += grad
        end
    end

    return img
end

img = fill(Gray(1.0N0f8), 250, 250);
drawline!(img, 8, 8, 192, 154)


// version 1.1.2

import java.awt.*
import javax.swing.*

class XiaolinWu: JPanel() {
    init {
        preferredSize = Dimension(640, 640)
        background = Color.white
    }

    private fun plot(g: Graphics2D, x: Double, y: Double, c: Double) {
        g.color = Color(0f, 0f, 0f, c.toFloat())
        g.fillOval(x.toInt(), y.toInt(), 2, 2)
    }

    private fun ipart(x: Double) = x.toInt()

    private fun fpart(x: Double) = x - Math.floor(x)

    private fun rfpart(x: Double) = 1.0 - fpart(x)

    private fun drawLine(g: Graphics2D, x0: Double, y0: Double, x1: Double, y1: Double) {
        val steep = Math.abs(y1 - y0) > Math.abs(x1 - x0)
        if (steep) drawLine(g, y0, x0, y1, x1)
        if (x0 > x1) drawLine(g, x1, y1, x0, y0)

        val dx = x1 - x0
        val dy = y1 - y0
        val gradient = dy / dx

        // handle first endpoint
        var xend = Math.round(x0).toDouble()
        var yend = y0 + gradient * (xend - x0)
        var xgap = rfpart(x0 + 0.5)
        val xpxl1 = xend  // this will be used in the main loop
        val ypxl1 = ipart(yend).toDouble()

        if (steep) {
            plot(g, ypxl1, xpxl1, rfpart(yend) * xgap)
            plot(g, ypxl1 + 1.0, xpxl1, fpart(yend) * xgap)
        }
        else {
            plot(g, xpxl1, ypxl1, rfpart(yend) * xgap)
            plot(g, xpxl1, ypxl1 + 1.0, fpart(yend) * xgap)
        }

        // first y-intersection for the main loop
        var intery = yend + gradient

        // handle second endpoint
        xend = Math.round(x1).toDouble()
        yend = y1 + gradient * (xend - x1)
        xgap = fpart(x1 + 0.5)
        val xpxl2 = xend  // this will be used in the main loop
        val ypxl2 = ipart(yend).toDouble()

        if (steep) {
            plot(g, ypxl2, xpxl2, rfpart(yend) * xgap)
            plot(g, ypxl2 + 1.0, xpxl2, fpart(yend) * xgap)
        }
        else {
            plot(g, xpxl2, ypxl2, rfpart(yend) * xgap)
            plot(g, xpxl2, ypxl2 + 1.0, fpart(yend) * xgap)
        }

        // main loop
        var x = xpxl1 + 1.0
        while (x <=  xpxl2 - 1) {
            if (steep) {
                plot(g, ipart(intery).toDouble(), x, rfpart(intery))
                plot(g, ipart(intery).toDouble() + 1.0, x, fpart(intery))
            }
            else {
                plot(g, x, ipart(intery).toDouble(), rfpart(intery))
                plot(g, x, ipart(intery).toDouble() + 1.0, fpart(intery))
            }
            intery += gradient
            x++
        }
    }

    override protected fun paintComponent(gg: Graphics) {
        super.paintComponent(gg)
        val g = gg as Graphics2D
        drawLine(g, 550.0, 170.0, 50.0, 435.0)
    }
}

fun main(args: Array<String>) {
    SwingUtilities.invokeLater {
        val f = JFrame()
        f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        f.title = "Xiaolin Wu's line algorithm"
        f.isResizable = false
        f.add(XiaolinWu(), BorderLayout.CENTER)
        f.pack()
        f.setLocationRelativeTo(null)
        f.isVisible = true
    }
}


/*REXX*/

of='file.txt'
'erase' of
s=copies('1234567890',10000)
Call charout of,s
Call lineout of
Say chars(of) length(s)


use std::fs::File;
use std::io::Write;

fn main() -> std::io::Result<()> {
    let data = "Sample text.";
    let mut file = File::create("filename.txt")?;
    write!(file, "{}", data)?;
    Ok(())
}


import java.io.{File, PrintWriter}

object Main extends App {
  val pw = new PrintWriter(new File("Flumberboozle.txt"),"UTF8"){
  print("My zirconconductor short-circuited and I'm having trouble fixing this issue.\nI researched" +
    " online and they said that I need to connect my flumberboozle to the XKG virtual port, but I was" +
    " wondering if I also needed a galvanized tungsten retrothruster array? Maybe it'd help the" +
    " frictional radial anti-stabilizer vectronize from the flumberboozle to the XKG virtual port?")
  close()}
}


put "New String" into file "~/Desktop/myFile.txt"


var file = File(__FILE__)
file.open_w(\var fh, \var err) || die "Can't open #{file}: #{err}"
fh.print("Hello world!")       || die "Can't write to #{file}: #{$!}"


'file.txt' asFilename contents:'Hello World'


      INSTALL @lib$+"XMLLIB"
      xmlfile$ = "C:\students.xml"
      PROC_initXML(xmlobj{}, xmlfile$)

      level% = FN_skipTo(xmlobj{}, "Students", 0)
      IF level%=0 ERROR 100, "Students not found"

      REPEAT
        IF FN_isTag(xmlobj{}) THEN
          tag$ = FN_nextToken(xmlobj{})
          IF LEFT$(tag$, 8) = "<Student" THEN
            np% = INSTR(tag$, "Name")
            IF np% THEN PRINT FN_repEnt(EVAL(MID$(tag$, np%+5)))
          ENDIF
        ELSE
          dummy$ = FN_nextToken(xmlobj{})
        ENDIF
      UNTIL FN_getLevel(xmlobj{}) < level%

      PROC_exitXML(xmlobj{})


( :?names
& (   get$("students.xml",X,ML)
    :   ?
        ( ( Student
          .   (? (Name.?name) ?,)
            | ? (Name.?name) ?
          )
        & !names !name:?names
        & ~
        )
        ?
  | !names
  )
)


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libxml/parser.h>
#include <libxml/tree.h>

static void print_names(xmlNode *node)
{
  xmlNode *cur_node = NULL;
  for (cur_node = node; cur_node; cur_node = cur_node->next) {
    if (cur_node->type == XML_ELEMENT_NODE) {
      if ( strcmp(cur_node->name, "Student") == 0 ) {
	xmlAttr *prop = NULL;
	if ( (prop = xmlHasProp(cur_node, "Name")) != NULL ) {
	  printf("%s\n", prop->children->content);

	}
      }
    }
    print_names(cur_node->children);
  }
}

const char *buffer =
  "<Students>\n"
  "  <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n"
  "  <Student Name=\"Bob\" Gender=\"M\"  DateOfBirth=\"1990-03-04\" />\n"
  "  <Student Name=\"Chad\" Gender=\"M\"  DateOfBirth=\"1991-05-06\" />\n"
  "  <Student Name=\"Dave\" Gender=\"M\"  DateOfBirth=\"1992-07-08\">\n"
  "    <Pet Type=\"dog\" Name=\"Rover\" />\n"
  "  </Student>\n"
  "  <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />\n"
  "</Students>\n";

int main()
{
  xmlDoc *doc = NULL;
  xmlNode *root = NULL;

  doc = xmlReadMemory(buffer, strlen(buffer), NULL, NULL, 0);
  if ( doc != NULL ) {
    root = xmlDocGetRootElement(doc);
    print_names(root);
    xmlFreeDoc(doc);
  }
  xmlCleanupParser();
  return 0;
}


NoMainWin
WindowWidth = 270
WindowHeight = 290
UpperLeftX=int((DisplayWidth-WindowWidth)/2)
UpperLeftY=int((DisplayHeight-WindowHeight)/2)

Global variablesInitialized : variablesInitialized = 0
Global BackColor$ : BackColor$ = "0 0 0"
'    BackColor$ = "255 255 255"
    'now, right click randomizes BG
Global size : size = 1'4
global mousepoints.mouseX0,  mousepoints.mouseY0, mousepoints.mouseX1, mousepoints.mouseY1

'StyleBits #main.gbox, 0, _WS_BORDER, 0, 0
GraphicBox #main.gbox, 0, 0, 253, 252

Open "Click Twice to Form Line" For Window As #main
Print #main, "TrapClose quit"
Print #main.gbox, "Down; Color Black"
Print #main.gbox, "Down; fill ";BackColor$
Print #main.gbox, "When leftButtonUp gBoxClick"
Print #main.gbox, "When rightButtonUp RandomBG"
Print #main.gbox, "Size "; size

result = drawAntiAliasedLine(126.5, 0, 126.5, 252, "255 0 0")
result = drawAntiAliasedLine(0, 126, 253, 126, "255 0 0")
result = drawAntiAliasedLine(0, 0, 253, 252, "255 0 0")
result = drawAntiAliasedLine(253, 0, 0, 252, "255 0 0")
Wait

    Sub quit handle$
        Close #main
        End
    End Sub

sub RandomBG handle$, MouseX, MouseY
    BackColor$ = int(rnd(1)*256);" ";int(rnd(1)*256);" ";int(rnd(1)*256)
    Print #main.gbox, "CLS; fill ";BackColor$
    variablesInitialized = 0
end sub

    Sub gBoxClick handle$, MouseX, MouseY
        'We will use the mousepoints "struct" to hold the values
        'that way they are retained between subroutine calls
        If variablesInitialized = 0 Then
            Print #main.gbox, "CLS; fill ";BackColor$
            mousepoints.mouseX0 = MouseX
            mousepoints.mouseY0 = MouseY
            variablesInitialized = 1
        Else
            If variablesInitialized = 1 Then
                mousepoints.mouseX1 = MouseX
                mousepoints.mouseY1 = MouseY
                variablesInitialized = 0
                result = drawAntiAliasedLine(mousepoints.mouseX0, mousepoints.mouseY0, mousepoints.mouseX1, mousepoints.mouseY1, "255 0 0")
            End If
        End If
    End Sub

    Function Swap(Byref a,Byref b)
        aTemp = b
        b = a
        a = aTemp
    End Function

    Function RoundtoInt(val)
        RoundtoInt = Int(val + 0.5)
    End Function

    Function PlotAntiAliased(x, y, RGB$, b, steep)

        RGB$ = Int(Val(Word$(BackColor$, 1))*(1-b) + Val(Word$(RGB$, 1)) * b) ; " " ; _
               Int(Val(Word$(BackColor$, 2))*(1-b) + Val(Word$(RGB$, 3)) * b) ; " " ; _
               Int(Val(Word$(BackColor$, 3))*(1-b) + Val(Word$(RGB$, 2)) * b)

        if steep then 'x and y reversed
            Print #main.gbox, "Down; Color " + RGB$ + "; Set " + str$(y) + " " + str$(x)
        else
            Print #main.gbox, "Down; Color " + RGB$ + "; Set " + str$(x) + " " + str$(y)
        end if
    End Function

    Function fracPart(x)
        fracPart = (x Mod 1)
    End function

    Function invFracPart(x)
        invFracPart = (1 - fracPart(x))
    End Function

    Function drawAntiAliasedLine(x1, y1, x2, y2, RGB$)
        If (x2 - x1)=0 Or (y2 - y1)=0 Then
            Print #main.gbox, "Down; Color " + RGB$
            result = BresenhamLine(x1, y1, x2, y2)
            Exit Function
        End If
        steep = abs(x2 - x1) < abs(y2 - y1)
        if steep then   'x and y should be reversed
            result = Swap(x1, y1)
            result = Swap(x2, y2)
        end if

        If (x2 < x1) Then
            result = Swap(x1, x2)
            result = Swap(y1, y2)
        End If
        dx = (x2 - x1)
        dy = (y2 - y1)
        grad = (dy/ dx)
        'Handle the First EndPoint
        xend = RoundtoInt(x1)
        yend = y1 + grad * (xend - x1)
        xgap = invFracPart(x1 + 0.5)
        ix1 = xend
        iy1 = Int(yend)
        result = PlotAntiAliased(ix1, iy1, RGB$, invFracPart(yend) * xgap, steep )
        result = PlotAntiAliased(ix1, (iy1 + size), RGB$, fracPart(yend) * xgap, steep )
        yf = (yend + grad)
        'Handle the Second EndPoint
        xend = RoundtoInt(x2)
        yend = y2 + grad * (xend - x2)
        xgap = fracPart(x2 + 0.5)
        ix2 = xend
        iy2 = Int(yend)
        result = PlotAntiAliased(ix2, iy2, RGB$, invFracPart(yend) * xgap, steep )
        result = PlotAntiAliased(ix2, (iy2 + size), RGB$, fracPart(yend) * xgap, steep )
        For x = ix1 + 1 To ix2 - 1
            result = PlotAntiAliased(x, Int(yf), RGB$, invFracPart(yf), steep )
            result = PlotAntiAliased(x, (Int(yf) + size), RGB$, fracPart(yf), steep )
            yf = (yf + grad)
        Next x
    End Function

    Function BresenhamLine(x0, y0, x1, y1)
        dx = Abs(x1 - x0)
        dy = Abs(y1 - y0)
        sx = ((x1 > x0) + Not(x0 < x1))
        sy = ((y1 > y0) + Not(y0 < y1))
        errornum = (dx - dy)
        Do While 1
            Print #main.gbox, "Set " + str$(x0) + " " + str$(y0)
            If (x0 = x1) And (y0 = y1) Then Exit Do
            errornum2 = (2 * errornum)
            If errornum2 > (-1 * dy) Then
                errornum = (errornum - dy)
                x0 = (x0 + sx)
            End If
            If errornum2 < dx Then
                errornum = (errornum + dx)
                y0 = (y0 + sy)
            End If
        Loop
    End Function


#.writetext("file.txt","This is the string")


fun writeFile (path, str) =
  (fn strm =>
    TextIO.output (strm, str) before TextIO.closeOut strm) (TextIO.openOut path)


proc writefile {filename data} {
    set fd [open $filename w]   ;# truncate if exists, else create
    try {
        puts -nonewline $fd $data
    } finally {
        close $fd
    }
}


$$ MODE TUSCRIPT
content="new text that will overwrite content of myfile"
LOOP
 path2file=FULLNAME (TUSTEP,"myfile",-std-)
 status=WRITE (path2file,content)
 IF (status=="OK") EXIT
 IF (status=="CREATE") ERROR/STOP CREATE ("myfile",seq-o,-std-)
ENDLOOP


Option Explicit

Const strName As String = "MyFileText.txt"
Const Text As String = "(Over)write a file so that it contains a string. " & vbCrLf & _
           "The reverse of Read entire file—for when you want to update or " & vbCrLf & _
           "create a file which you would read in its entirety all at once."

Sub Main()
Dim Nb As Integer

Nb = FreeFile
Open "C:\Users\" & Environ("username") & "\Desktop\" & strName For Output As #Nb
    Print #1, Text
Close #Nb
End Sub