---
# System prepended metadata

title: Untitled

---

/* Sample file contents:

{"name": "Acme Corp", prices: [12, 14, 13, 18, 11, 14]}
{"name": "Example Enterprises", prices: [50, 49, 55, 53]}

Desired output written to a file:

{"name": "Example Enterprises", "buy_day": 1, "sell_day": 2}
...

*/

import (
   "io"
   "sys"
   "fmt"
   "ioutils"
   "json"
)
package main

const fileName="foo.bar"

func main {
    f,err:=io.ReadFile(fileName)
    if err!=nil {
      fmt.Printf("Error while reading file %s:%v",fileName,err)
      sys.Exit(1)
    }
    c,err:=ioutil.ReadAll(f)
    if err!=nil {
      fmt.Printf("Error while reading contents of file %s:%v",fileName,err)
      sys.Exit(1)
    }
    st:=stock{}
    ch:=make(chan []byte,4)
    ctlCh:=make(chan struct{},4)
    for _,v:=range c {
      <-ctlCh
      go processEntry(v,ch,ctlCh)  
    }
 
}


func processEntry (v []byte,out <-chan []byte, in chan struct{}) {
      err:=json.Unmarshal(&st,v)
      if err!=nil {
          fmt.Printf("Error while marshaling stock result %v:%v",r,err)
          os.Exit(1)
      }
      min:=stockValue{}
      max:=stockValue{}
      for i,x:=range v.Prices {
         if min.value==nil || (min.value!=nil && min.value > x){
               min=stockValue{value:&x,day:i}
               max=stockValue{}
               continue
         } 
         if max.value==nil || (max.value!=nil && max.value < x){
               max=stockValue{value:&x,day:i}
         }
      }
      r:=stockResult{Name:v.Name,BuyDay:min.day,SellDay:max.day}
      b:=[]byte{}
      err:=json.Marshal(b,r)
      if err!=nil {
          fmt.Printf("Error while marshaling stock result %v:%v",r,err)
          os.Exit(1)
      }
      // here we write to a file
      out <-b
      in<-struct{}{}
}
type concurrentWrite struct {
  f File
  mux sync.Mux
}

type Write(b []byte) interface 

func (c *concurrentWrite) Write(b []byte) {
   c.mux.Lock()
   defer c.mux.Unlock()
   f.Write(b)
}


type stockResult struct {
  Name string `json:"name"`
  BuyDay int `json:"buy_day"`
  SellDay int `json:"sell_day"`
}


type stockValue struct {
   value *int
   day   int
}

type stock struct {
 Name string `json:"name"`
 Prices []int `json:"prices"`
}